package com.testor.module.threeframework.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.model.domain.SysDictData;
import com.testor.biz.sys.dict.data.service.SysDictDataService;
import com.testor.biz.sys.dict.type.model.domain.SysDictType;
import com.testor.biz.sys.dict.type.service.SysDictTypeService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.constant.DefaultRule;
import com.testor.module.threeframework.enums.ThreeTimePlanEnum;
import com.testor.module.threeframework.model.domain.TThreeTime;
import com.testor.module.threeframework.model.dto.TThreeTimeDelParam;
import com.testor.module.threeframework.model.dto.TThreeTimeEditDTO;
import com.testor.module.threeframework.model.dto.TThreeTimeParam;
import com.testor.module.threeframework.model.vo.TThreeTimeVO;
import com.testor.module.threeframework.service.TThreeTimeService;
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 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-09-15 17:16:20
 */
@RestController
@RequestMapping("/module/three/framework/time")
@Api(value = "TThreeTime", tags = "建设项目安全管理")
@Slf4j
public class TThreeTimeController extends SuperController {
    @Autowired
    private TThreeTimeService tThreeTimeService;

    @Autowired
    private SysDictDataService sysDictDataService;
    @Autowired
    private SysDictTypeService sysDictTypeService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRuleService sysRuleService;


    @ApiOperation(value = "新增 建设项目安全管理", notes = "Add TThreeTime")
    @PostMapping(value = "/add")
    public BaseResponse<TThreeTime> addEntity(@RequestBody TThreeTimeEditDTO addRequest) {
        return tThreeTimeService.addEntity(addRequest);
    }

    @ApiOperation(value = "获取 建设项目安全管理 ", notes = "Get TThreeTime By Id")
    @GetMapping(value = "/get")
    public BaseResponse<List<TThreeTimeVO>> getById(String id) {
        return tThreeTimeService.getThreeTime(id);
    }

    @ApiOperation(value = "修改 建设项目安全管理 ", notes = "Update TThreeTime By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TThreeTimeEditDTO updateRequest) {
        return tThreeTimeService.updateEntity(updateRequest);
    }

    @ApiOperation(value = "删除 建设项目安全管理 ", notes = "delete TThreeTime By Id")
    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TThreeTimeDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            // TODO 按需求添加数据去重，特殊值设定，业务异常
            TThreeTime data = new TThreeTime();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tThreeTimeService.updateById(data);
            baseResponse.setData(BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "批量删除建设项目安全管理", notes = "delete TThreeTime by batch Id")
    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(@RequestBody TThreeTimeDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TThreeTime> tThreeTimeList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TThreeTime data = new TThreeTime();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tThreeTimeList.add(data);
            }
            boolean result = tThreeTimeService.updateBatchById(tThreeTimeList);
            baseResponse.setData(BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 建设项目安全管理 分页列表", notes = "List TThreeTime with page")
    @PostMapping(value = "/list")
    public BaseResponse<BaseResponseList<TThreeTime>> listEntity(@RequestBody TThreeTimeParam param) {
        BaseResponse<BaseResponseList<TThreeTime>> 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<TThreeTime> resultPage = new Page<>(page, limit);
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TThreeTime> queryWrapper = this.createQuery(param);

        List<String> orgIds = param.getOrgIds();
        if (null != orgIds && orgIds.size() > 0) {
            queryWrapper.in("org_id", orgIds);
        }

        String endDate = param.getEndDate();
        String startDate = param.getStartDate();

        if(null!=startDate && null!=endDate){
            queryWrapper.between("project_approval_date",startDate,endDate);
        }

        Page<TThreeTime> resultList = tThreeTimeService.page(resultPage, queryWrapper);

        List<TThreeTime> records = resultList.getRecords();
        for (TThreeTime record : records) {
            String projectNature = record.getProjectNature();
            projectNature = getDictName("three_project_nature", projectNature);
            record.setProjectNature(projectNature);

            String plan = record.getPlan();
            plan = ThreeTimePlanEnum.getName(plan);
            record.setPlan(plan);

            String orgId = record.getOrgId();
            SysOrg org = sysOrgService.getById(orgId);
            record.setOrgName(org.getOrgName());

            String updateBy = record.getUpdateBy();
            SysUser user = sysUserService.getById(updateBy);
            record.setUpdateBy(user.getUserName());

        }

        BaseResponseList<TThreeTime> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "获取 建设项目安全管理 列表", notes = "List TThreeTime all")
    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TThreeTime>> listAllEntity(TThreeTimeParam param) {
        BaseResponse<BaseResponseList<TThreeTime>> baseResponse = new BaseResponse<>();
        // TODO 根据需求修改查询条件及查询参数
        QueryWrapper<TThreeTime> queryWrapper = this.createQuery(param);
        List<TThreeTime> resultList = tThreeTimeService.list(queryWrapper);
        BaseResponseList<TThreeTime> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }


    /**
     * 根据字典key 及 值 获取对应字典名称
     *
     * @param dictType key
     * @param dictKey  值
     * @return .
     */
    private String getDictName(String dictType, String dictKey) {
        SysDictType one = this.sysDictTypeService.getOne(new QueryWrapper<SysDictType>().eq("dict_type", dictType));
        String dictId = one.getDictId();
        SysDictData data = this.sysDictDataService.getOne(new QueryWrapper<SysDictData>().eq("dict_id", dictId).eq("dict_key", dictKey).ne("status", "1").last("LIMIT 1"));
        if (ObjectHelper.isNotEmpty(data)) {
            return data.getDictValue();
        }
        return dictKey;
    }


    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TThreeTime> createQuery(TThreeTimeParam queryParam) {
        QueryWrapper<TThreeTime> queryWrapper = new QueryWrapper<>();
        String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
        if (StringUtils.isNotEmpty(rule)) {
            queryWrapper.apply(rule);
        }
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TThreeTime.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TThreeTime.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TThreeTime.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TThreeTime.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TThreeTime.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getSerialNumber())) {
            queryWrapper.eq(TThreeTime.SERIAL_NUMBER, queryParam.getSerialNumber());
        }
        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            queryWrapper.eq(TThreeTime.ORG_ID, queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProjectNature())) {
            queryWrapper.eq(TThreeTime.PROJECT_NATURE, queryParam.getProjectNature());
        }
        if (StringHelper.isNotEmpty(queryParam.getName())) {
            queryWrapper.like(TThreeTime.NAME, queryParam.getName());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getProjectApprovalDate())) {
            queryWrapper.eq(TThreeTime.PROJECT_APPROVAL_DATE, queryParam.getProjectApprovalDate());
        }
        if (StringHelper.isNotEmpty(queryParam.getPlan())) {
            queryWrapper.eq(TThreeTime.PLAN, queryParam.getPlan());
        }
        if (StringHelper.isNotEmpty(queryParam.getIntro())) {
            queryWrapper.eq(TThreeTime.INTRO, queryParam.getIntro());
        }
        if (StringHelper.isNotEmpty(queryParam.getSafetyEvaluation())) {
            queryWrapper.eq(TThreeTime.SAFETY_EVALUATION, queryParam.getSafetyEvaluation());
        }
        if (StringHelper.isNotEmpty(queryParam.getEvlAppraisal())) {
            queryWrapper.eq(TThreeTime.EVL_APPRAISAL, queryParam.getEvlAppraisal());
        }
        if (StringHelper.isNotEmpty(queryParam.getSafetyFacilities())) {
            queryWrapper.eq(TThreeTime.SAFETY_FACILITIES, queryParam.getSafetyFacilities());
        }
        if (StringHelper.isNotEmpty(queryParam.getEvlProtection())) {
            queryWrapper.eq(TThreeTime.EVL_PROTECTION, queryParam.getEvlProtection());
        }
        if (StringHelper.isNotEmpty(queryParam.getConstruction())) {
            queryWrapper.eq(TThreeTime.CONSTRUCTION, queryParam.getConstruction());
        }
        if (StringHelper.isNotEmpty(queryParam.getSafetyAcceptance())) {
            queryWrapper.eq(TThreeTime.SAFETY_ACCEPTANCE, queryParam.getSafetyAcceptance());
        }
        if (StringHelper.isNotEmpty(queryParam.getEvlSurvey())) {
            queryWrapper.eq(TThreeTime.EVL_SURVEY, queryParam.getEvlSurvey());
        }
        if (StringHelper.isNotEmpty(queryParam.getPostEvaluation())) {
            queryWrapper.eq(TThreeTime.POST_EVALUATION, queryParam.getPostEvaluation());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TThreeTime.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TThreeTime.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(TThreeTime.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
