package com.testor.module.train.database.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataResponse;
import com.testor.common.constant.DefaultRule;
import com.testor.module.train.database.model.domain.TTrainDatabase;
import com.testor.module.train.database.model.dto.TTrainDatabaseDelParam;
import com.testor.module.train.database.model.dto.TTrainDatabaseParam;
import com.testor.module.train.database.service.TTrainDatabaseService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 培训资料管理——安全培训教育Controller
 *
 * @author testor-framework
 * @date 2022-07-12 10:01:27
 */
@RestController
@RequestMapping("/database")
@Api(value = "TTrainDatabase", tags = "安全培训教育——培训资料管理")
@Slf4j
public class TTrainDatabaseController extends SuperController {
    @Autowired
    private TTrainDatabaseService tTrainDatabaseService;
    @Autowired
    private SysRuleService sysRuleService;
    @Autowired
    private SysDictDataController sysDictDataController;

    /* Generated Method*/
    @ApiOperation(value = "新增 培训资料管理——安全培训教育", notes = "Add TTrainDatabase")
    @PostMapping(value = "/add")
    public BaseResponse<TTrainDatabase> addEntity(@RequestBody TTrainDatabase addRequest) throws Exception {
        return tTrainDatabaseService.addEntity(addRequest);
    }

    @ApiOperation(value = "获取 培训资料管理——安全培训教育 ", notes = "Get TTrainDatabase By Id")
    @GetMapping(value = "/get")
    public BaseResponse<TTrainDatabaseParam> getById(String id) throws Exception {
        return tTrainDatabaseService.getByIds(id);
    }

    @ApiOperation(value = "修改 培训资料管理——安全培训教育 ", notes = "Update TTrainDatabase By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TTrainDatabase updateRequest) throws Exception {
        return tTrainDatabaseService.updateEntity(updateRequest);
    }

    @ApiOperation(value = "删除 培训资料管理——安全培训教育 ", notes = "delete TTrainDatabase By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TTrainDatabaseDelParam deleteRequest) throws Exception {
        return tTrainDatabaseService.deleteEntity(deleteRequest);
    }

    //    @ApiOperation(value = "批量删除培训资料管理——安全培训教育", notes = "delete TTrainDatabase by batch Id")
//    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TTrainDatabaseDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TTrainDatabase> tTrainDatabaseList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TTrainDatabase data = new TTrainDatabase();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tTrainDatabaseList.add(data);
            }
            boolean result = tTrainDatabaseService.updateBatchById(tTrainDatabaseList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 培训资料管理——安全培训教育 分页列表", notes = "List TTrainDatabase with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TTrainDatabase>> listEntity(TTrainDatabaseParam param) {
        BaseResponse<BaseResponseList<TTrainDatabase>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TTrainDatabase> resultPage = new Page<>(page, limit);
        QueryWrapper<TTrainDatabase> queryWrapper = this.createQuery(param);
        Page<TTrainDatabase> resultList = tTrainDatabaseService.page(resultPage, queryWrapper);
        BaseResponseList<TTrainDatabase> baseResponseList = new BaseResponseList<>();
        List<TTrainDatabase> records = resultList.getRecords();
        List<TTrainDatabase> tTrainDatabases = converDict(records);
        baseResponseList.setData(tTrainDatabases);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /**
     * 转字典值
     *
     * @param baseResponseList
     * @return
     */
    private List<TTrainDatabase> converDict(List<TTrainDatabase> baseResponseList) {
        List<TTrainDatabase> data1 = new ArrayList<>();
        for (TTrainDatabase datum : baseResponseList) {
            TTrainDatabase tTrainDatabase = BeanHelper.beanToBean(datum, TTrainDatabase.class);
            String stairSubject = tTrainDatabase.getStairSubject();
            String secondSubject = tTrainDatabase.getSecondSubject();
            String dataType = tTrainDatabase.getDataType();
            String subject_level = sysDictDataController.getDictTypeDetail("", "SUBJECT_LEVEL", stairSubject).getData().getDictValue();
            tTrainDatabase.setStairSubject(subject_level);
            String subject_level1 = sysDictDataController.getDictTypeDetail("", "SUBJECT_LEVEL", secondSubject).getData().getDictValue();
            tTrainDatabase.setSecondSubject(subject_level1);
            String dictValue = null;
            SysDictDataResponse type = sysDictDataController.getDictTypeDetail("", "DATA_TYPE", dataType).getData();
            if (ObjectHelper.isNotEmpty(type)) {
                dictValue = type.getDictValue();
                tTrainDatabase.setDataType(dictValue);
            }
            data1.add(tTrainDatabase);
        }

        return data1;
    }

    //    @ApiOperation(value = "获取 培训资料管理——安全培训教育 列表", notes = "List TTrainDatabase all")
//    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TTrainDatabase>> listAllEntity(TTrainDatabaseParam param) {
        BaseResponse<BaseResponseList<TTrainDatabase>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TTrainDatabase> queryWrapper = this.createQuery(param);
        List<TTrainDatabase> resultList = tTrainDatabaseService.list(queryWrapper);
        BaseResponseList<TTrainDatabase> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TTrainDatabase> createQuery(TTrainDatabaseParam queryParam) {
        QueryWrapper<TTrainDatabase> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(TTrainDatabase.CREATE_DATE);
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_ALL.name());
        if (StringUtils.isNotEmpty(rule)) {
            queryWrapper.apply(rule);
        }
        if (StringHelper.isNotEmpty(queryParam.getStartDateTime()) && StringHelper.isNotEmpty(queryParam.getEndDateTime())) {
            queryWrapper.between(TTrainDatabase.CREATE_DATE, queryParam.getStartDateTime()+" 00:00:00", queryParam.getEndDateTime()+" 23:59:59");
        }
        if (StringHelper.isNotEmpty(queryParam.getDataName())) {
            queryWrapper.like(TTrainDatabase.DATA_NAME, queryParam.getDataName());
        }
        if (StringHelper.isNotEmpty(queryParam.getStairSubject())) {
            queryWrapper.eq(TTrainDatabase.STAIR_SUBJECT, queryParam.getStairSubject());
        }
        if (StringHelper.isNotEmpty(queryParam.getSecondSubject())) {
            queryWrapper.eq(TTrainDatabase.SECOND_SUBJECT, queryParam.getSecondSubject());
        }
        if (StringHelper.isNotEmpty(queryParam.getDataType())) {
            if (!"0".equals(queryParam.getDataType())) {
                queryWrapper.eq(TTrainDatabase.DATA_TYPE, queryParam.getDataType());
            }
        }
        if (StringHelper.isNotEmpty(queryParam.getLevel())) {
            if (!"0".equals(queryParam.getLevel())) {
                queryWrapper.eq(TTrainDatabase.LEVEL, queryParam.getLevel());
            }
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TTrainDatabase.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TTrainDatabase.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TTrainDatabase.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
