package com.testor.module.regime.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.file.model.dto.FileDTO;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataComplexResponse;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataRequest;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataResponse;
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.core.utils.DateUtils;
import com.testor.common.core.utils.StringUtils;
import com.testor.module.notice.model.domain.TSysFile;
import com.testor.module.notice.service.TSysFileService;
import com.testor.module.regime.dao.TRegimeDataDao;
import com.testor.module.regime.model.domain.TRegimeData;
import com.testor.module.regime.model.dto.ReturnReleaseUnit;
import com.testor.module.regime.model.dto.TRegimeDataDelParam;
import com.testor.module.regime.model.dto.TRegimeDataListVo;
import com.testor.module.regime.model.dto.TRegimeDataParam;
import com.testor.module.regime.service.TRegimeDataService;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
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.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
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 org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 制度资料管理Service业务层处理
 *
 * @author testor-framework
 * @date 2022-07-01 14:14:14
 */
@Service
public class TRegimeDataServiceImpl extends SuperServiceImpl<TRegimeDataDao, TRegimeData> implements TRegimeDataService {
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TSysFileService tSysFileService;
    @Autowired
    private SysDictDataController sysDictDataController;
    @Autowired
    private TRegimeDataDao regimeDataDao;

    @Override
    public BaseResponse<List<ReturnReleaseUnit>> getReleaseUnit(String level) throws Exception {
        BaseResponse<List<ReturnReleaseUnit>> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(level)) {
            UserInfo loginUser = ContextUtils.getLoginUser();
            String orgId = loginUser.getOrgId();
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
            String treeLevel = one.getTreeLevel().toString();
            List<SysOrg> list = null;
            List<ReturnReleaseUnit> arrayList = new ArrayList<>();
            if ("3".equals(level)) {
                if ("1".equals(treeLevel)) {
                    ReturnReleaseUnit returnReleaseUnit = null;
                    list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, one.getOrgId())
                            .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                            .eq(SysOrg.IS_DEPT, "0")
                    );
                    for (SysOrg sysOrg : list) {
                        returnReleaseUnit = BeanHelper.beanToBean(sysOrg, ReturnReleaseUnit.class);
                        arrayList.add(returnReleaseUnit);
                    }
                }
                if ("2".equals(treeLevel)) {
                    ReturnReleaseUnit returnReleaseUnit = null;
                    list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, one.getOrgId())
                            .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                            .eq(SysOrg.IS_DEPT, "0")
                    );
                    for (SysOrg sysOrg : list) {
                        returnReleaseUnit = BeanHelper.beanToBean(sysOrg, ReturnReleaseUnit.class);
                        arrayList.add(returnReleaseUnit);
                    }
                }
                if ("3".equals(treeLevel)) {
                    ReturnReleaseUnit returnReleaseUnit = null;
                    list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, one.getParentId())
                            .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                            .eq(SysOrg.IS_DEPT, "0")
                    );
                    for (SysOrg sysOrg : list) {
                        returnReleaseUnit = BeanHelper.beanToBean(sysOrg, ReturnReleaseUnit.class);
                        arrayList.add(returnReleaseUnit);
                    }
                }
            }
            if ("4".equals(level)) {
                if ("1".equals(treeLevel)) {
                    list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, one.getOrgId())
                            .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                            .eq(SysOrg.IS_DEPT, "0")
                    );
                    for (SysOrg sysOrg : list) {
                        ReturnReleaseUnit returnReleaseUnit = BeanHelper.beanToBean(sysOrg, ReturnReleaseUnit.class);
                        List<SysOrg> list1 = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, sysOrg.getOrgId()));
                        returnReleaseUnit.setChild(list1);
                        arrayList.add(returnReleaseUnit);
                    }
                }
                if ("2".equals(treeLevel)) {
                    ReturnReleaseUnit returnReleaseUnit = null;
                    list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, one.getOrgId())
                            .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                            .eq(SysOrg.IS_DEPT, "0"));
                    for (SysOrg sysOrg : list) {
                        returnReleaseUnit = BeanHelper.beanToBean(sysOrg, ReturnReleaseUnit.class);
                        arrayList.add(returnReleaseUnit);
                    }
                }
                if ("3".equals(treeLevel)) {
                    ReturnReleaseUnit returnReleaseUnit = null;
                    list = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, one.getOrgId())
                            .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE)
                            .eq(SysOrg.IS_DEPT, "0")
                    );
                    for (SysOrg sysOrg : list) {
                        returnReleaseUnit = BeanHelper.beanToBean(sysOrg, ReturnReleaseUnit.class);
                        arrayList.add(returnReleaseUnit);
                    }
                }
            }
            baseResponse.setData(arrayList);
        } else {
            throw new BusinessException("参数异常");
        }

        return baseResponse;
    }

    @Override
    public BaseResponseList<TRegimeDataListVo> pageList(Page<TRegimeData> resultPage, TRegimeDataParam param) {
        BaseResponseList<TRegimeDataListVo> baseResponseList = new BaseResponseList<>();
        convertPara(param);
        IPage<TRegimeDataListVo> iPage = regimeDataDao.findDepositoryList(resultPage, param);
        if (iPage == null || CollectionUtils.isEmpty(iPage.getRecords())) {
            baseResponseList.setTotal(0);
            baseResponseList.setData(new ArrayList<>());
            return baseResponseList;
        }
        iPage.getRecords().forEach(item -> {
            String oneMaterialsType = item.getOneMaterialsType();
            String senMaterialsType = item.getSenMaterialsType();
            String companyNature = item.getCompanyNature();
            SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "MATERIALS", oneMaterialsType).getData();
            if (ObjectHelper.isNotEmpty(materials2)) {
                String materials = materials2.getDictValue();
                item.setOneMaterialsType(materials);
            }
            SysDictDataResponse materials3 = sysDictDataController.getDictTypeDetail("", "MATERIALS", senMaterialsType).getData();
            if (ObjectHelper.isNotEmpty(materials3)) {
                String materials1 = materials3.getDictValue();
                item.setSenMaterialsType(materials1);
            }
            SysDictDataResponse nature = sysDictDataController.getDictTypeDetail("", "NATURE", companyNature).getData();
            if (ObjectHelper.isNotEmpty(nature)) {
                String natureDictValue = nature.getDictValue();
                item.setCompanyNature(natureDictValue);
            }
            if (StringUtils.isNotBlank(senMaterialsType) && StringUtils.contains(senMaterialsType, "other")) {
                item.setSenMaterialsType("其他");
            }


        });
        baseResponseList.setData(iPage.getRecords());
        baseResponseList.setTotal(iPage.getTotal());
        return baseResponseList;
    }

    private void convertPara(TRegimeDataParam param) {

        List<String> oneMaterialsTypeList = new ArrayList<>();
        List<String> senMaterialsTypeList = new ArrayList<>();

        if (StringUtils.isNotBlank(param.getOneMaterialsType()) && StringUtils.isBlank(param.getSenMaterialsType())) {
            String oneMaterialsType = param.getOneMaterialsType();
            //安全生产
            if ("an".equals(oneMaterialsType)) {
                senMaterialsTypeList.add("jc_aqsc");
                senMaterialsTypeList.add("ywdw_aqsc");
                senMaterialsTypeList.add("zlmy_aqsc");
                senMaterialsTypeList.add("jituan_aqsc");
                senMaterialsTypeList.add("fa_aqsc");
                param.setSenMaterialsTypeList(senMaterialsTypeList);
                oneMaterialsTypeList.add("an");
                param.setOneMaterialsTypeList(oneMaterialsTypeList);
            }
            //综合管理
            if ("jc_zhgl".equals(oneMaterialsType)) {
                senMaterialsTypeList.add("jc_zhgl");
                senMaterialsTypeList.add("ywdw_zhgl");
                senMaterialsTypeList.add("zlmy_zhgl");
                senMaterialsTypeList.add("jituan_zhgl");
                senMaterialsTypeList.add("fa_zhgl");
                param.setSenMaterialsTypeList(senMaterialsTypeList);
            }
            //5S管理
            if ("jc_5sgl".equals(oneMaterialsType)) {
                senMaterialsTypeList.add("jc_5sgl");
                senMaterialsTypeList.add("ywdw_5sgl");
                senMaterialsTypeList.add("zlmy_5sgl");
                param.setSenMaterialsTypeList(senMaterialsTypeList);
            }
            //节能环保 jie
            if ("jie".equals(oneMaterialsType)) {
                senMaterialsTypeList.add("jc_jnhb");
                senMaterialsTypeList.add("ywdw_jnhb");
                senMaterialsTypeList.add("zlmy_jnhb");
                senMaterialsTypeList.add("jituan_jnhb");
                senMaterialsTypeList.add("fa_jnhb");
                param.setSenMaterialsTypeList(senMaterialsTypeList);
                oneMaterialsTypeList.add("jie");
                param.setOneMaterialsTypeList(oneMaterialsTypeList);
            }
            if ("yij".equals(oneMaterialsType)) {
                oneMaterialsTypeList.add("yij");
                param.setOneMaterialsTypeList(oneMaterialsTypeList);
            }
        }


        if (StringUtils.isNotBlank(param.getStartTime())) {
            param.setStartTime(param.getStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(param.getEndTime())) {
            param.setEndTime(param.getEndTime() + " 23:59:59");
        }
    }


    @Override
    public BaseResponse<TRegimeData> addEntity(TRegimeData addRequest) throws Exception {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        BaseResponse<TRegimeData> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            String materialsName = addRequest.getMaterialsName();
            TRegimeData one = this.getOne(new QueryWrapper<TRegimeData>().eq(TRegimeData.MATERIALS_NAME, materialsName)
                    .eq(TRegimeData.RELEASE_UNIT_ID, loginUser.getOrgId())
                    .ne(TRegimeData.STATUS, BizConstants.STATUS_DELETE));
            if (one != null) {
                throw new BusinessException("材料名称不能重复");
            }
            String id = IdHelper.getId32bit();
            TRegimeData data = BeanHelper.beanToBean(addRequest, TRegimeData.class);
            data.setOrgId(loginUser.getOrgId());
            String level = addRequest.getLevel().toString();
            if ("1".equals(level)) {
                data.setReleaseUnit("中粮集团");
                data.setUpdateUnit("中粮集团");
            } else {
                data.setReleaseUnit(sysOrg.getOrgName());
                data.setUpdateUnit(sysOrg.getOrgName());
            }
            data.setReleaseUnitId(sysOrg.getOrgId());
            data.setLevel(addRequest.getLevel());
            data.setId(id);
            boolean result = false;
            try {
                result = this.save(data);
            } catch (org.springframework.dao.DataIntegrityViolationException e) {
                throw new BusinessException("名称过长");
            }
            if (result) {
                TRegimeData newEntity = new TRegimeData();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        } else {
            throw new BusinessException("参数异常");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TRegimeData> getByIds(String id) throws Exception {
        BaseResponse<TRegimeData> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TRegimeData data = this.getById(id);
            TRegimeDataParam tRegimeDataParam = BeanHelper.beanToBean(data, TRegimeDataParam.class);
            String refId = data.getRefId();
            if (refId != null) {
                String[] split = refId.split(",");
                List<FileDTO> list = new ArrayList<>();
                if (split.length > 0) {
                    for (String s : split) {
                        FileDTO fileDTO = new FileDTO();
                        TSysFile tSysFile = tSysFileService.getById(s);
                        if (tSysFile != null && !(tSysFile.getStatus().equals("1"))) {
                            fileDTO.setFilePath(tSysFile.getFilePath());
                            fileDTO.setFileName(tSysFile.getFileName());
                            fileDTO.setFileDowName(tSysFile.getFileDowName());
                            fileDTO.setFileId(s);
                            list.add(fileDTO);
                        }
                    }
                    String createBy = tRegimeDataParam.getCreateBy();
                    String updateBy = tRegimeDataParam.getUpdateBy();
                    SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, createBy));
                    SysUser sysUser1 = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.USER_ID, updateBy));
                    if (ObjectHelper.isNotEmpty(sysUser)) {
                        tRegimeDataParam.setCreateBy(sysUser.getUserName());
                    }
                    if (ObjectHelper.isNotEmpty(sysUser1)) {
                        tRegimeDataParam.setUpdateBy(sysUser1.getUserName());
                    }
//                    SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "MATERIALS", tRegimeDataParam.getOneMaterialsType()).getData();
//                    if (ObjectHelper.isNotEmpty(materials2)) {
//                        String materials = materials2.getDictValue();
//                        tRegimeDataParam.setOneMaterialsType(materials);
//                    }
//                    SysDictDataResponse materials = sysDictDataController.getDictTypeDetail("", "MATERIALS", tRegimeDataParam.getSenMaterialsType()).getData();
//                    if (ObjectHelper.isNotEmpty(materials)) {
//                        String materials1 = materials.getDictValue();
//                        tRegimeDataParam.setSenMaterialsType(materials1);
//                    }
                    tRegimeDataParam.setRefId(null);
                    tRegimeDataParam.setFileDTOS(list);
                }
            }

            baseResponse.setData(tRegimeDataParam);
        } else {
            throw new BusinessException("参数异常");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> updateEntity(TRegimeData updateRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            UserInfo loginUser = ContextUtils.getLoginUser();
            SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
            TRegimeData regimeData = this.getById(updateRequest.getId());
            if (StringUtils.isNotBlank(updateRequest.getRegimeDataType())) {
                if (updateRequest.getMaterialsName().equals(regimeData.getMaterialsName()) &&
                        updateRequest.getOneMaterialsType().equals(regimeData.getOneMaterialsType()) &&
                        updateRequest.getSenMaterialsType().equals(regimeData.getSenMaterialsType()) &&
                        updateRequest.getRefId().equals(regimeData.getRefId()) &&
                        updateRequest.getRegimeDataType().equals(regimeData.getRegimeDataType())) {
                    throw new BusinessException("未修改相关内容");
                }
            }else {
                if (updateRequest.getMaterialsName().equals(regimeData.getMaterialsName()) &&
                        updateRequest.getOneMaterialsType().equals(regimeData.getOneMaterialsType()) &&
                        updateRequest.getSenMaterialsType().equals(regimeData.getSenMaterialsType()) &&
                        updateRequest.getRefId().equals(regimeData.getRefId())) {
                    throw new BusinessException("未修改相关内容");
                }
            }


            if (!updateRequest.getMaterialsName().equals(regimeData.getMaterialsName())) {
                TRegimeData one = this.getOne(new QueryWrapper<TRegimeData>().eq(TRegimeData.MATERIALS_NAME, updateRequest.getMaterialsName())
                        .ne(TRegimeData.STATUS, BizConstants.STATUS_DELETE));
                if (one != null) {
                    throw new BusinessException("材料名称不能重复");
                }
            }
            regimeData.setId(updateRequest.getId());
            regimeData.setMaterialsName(updateRequest.getMaterialsName());
            regimeData.setOneMaterialsType(updateRequest.getOneMaterialsType());
            regimeData.setSenMaterialsType(updateRequest.getSenMaterialsType());
            regimeData.setRefId(updateRequest.getRefId());
            TRegimeData data = this.getById(updateRequest.getId());
            regimeData.setUpdateUnit(sysOrg.getOrgName());
            regimeData.setRegimeDataType(updateRequest.getRegimeDataType());
            if ("中粮集团".equals(data.getReleaseUnit())) {
                regimeData.setUpdateUnit("中粮集团");
            }
            regimeData.setUpdateBy(loginUser.getUserId());
            boolean result = false;
            try {
                result = this.updateById(regimeData);
            } catch (org.springframework.dao.DataIntegrityViolationException e) {
                throw new BusinessException("名称过长");
            }
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("参数异常");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> deleteEntity(TRegimeDataDelParam deleteRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TRegimeData data = new TRegimeData();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("参数异常");
        }
        return baseResponse;
    }
}
