package com.testor.ddd.safetyControl.infrastructure.uitls.RiskTemplate;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.biz.file.service.SysFileService;
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.ddd.safetyControl.application.service.equipmentManage.EquipmentManageService;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.equipment.TSafeEquipmentVO;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DownloadRiskTemplateUtil {

    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket}")
    private String bucketName;

    @Resource
    private SysOrgService orgService;

    @Resource
    private SysUserService userService;

    @Resource
    private EquipmentManageService equipmentManageService;

    @Resource
    private SpaceManageService spaceManageService;

    @Resource
    private SysDictDataService dictDataService;

    @Resource
    private SysDictTypeService dictTypeService;

    @Resource
    private SysFileService sysFileService;

    /**
     * @param response
     * @param fileName
     * @param orgId
     */
    public void downloadRiskSourceTemplate(HttpServletResponse response, String fileName, String orgId) {
        try {
            /*
            List<SysFile> fileList = sysFileService.findByFileName(fileName);
            if(fileList == null || fileList.size() == 0) {
                return;
            }
            String fileDownName = fileList.get(0).getFileDowName();
            */
            InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/wxydrmb.xlsx");

            String fileName2 = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName2);

            OutputStream outputStream = response.getOutputStream();

            // 企业信息
            List<TemplateEntity> orgList = findOrgList(orgId);
            // 危险源分类
            List<DictDataTemplateEntity> sourceTypeList = findDictDataList("risk_source_type", null);
            // 可能导致的后果
            //List<DictDataTemplateEntity> consequenceList = findDictDataList("risk_source_consequence", null);
            List<DictDataTemplateEntity> consequenceList = findDictDataList("ACCIDENT_TYPE", null);
            // 固有风险
            List<DictDataTemplateEntity> inherentList = findDictDataList("inherent_level", null);
            // 检查频次
            List<DictDataTemplateEntity> frequencyList = findDictDataList("check_frequency", null);

            // 部门
            List<SysOrg> departmentEntityList = findDepartmentList(orgId);
            Map<String, String> departmentMap = new HashMap<>();
            for (SysOrg department : departmentEntityList) {
                departmentMap.put(department.getOrgId(), department.getOrgName());
            }
            List<DictDataTemplateEntity> departmentList = findDepartmentTemplateList(departmentEntityList);
            // 人员
            List<UserTemplateEntity> userList = findDepartmentUserList(orgId, departmentMap);

            // 管控层级
            List<DictDataTemplateEntity> controlLevelList = findDictDataList("control_level", null);

            // 设备
            List<EquipmentTemplateEntity> equipmentList = findEquipmentList(orgId);
            // 空间
            List<SpaceTemplateEntity> spaceList = findWorkAreaList(orgId);
            // 危险等级
            List<DictDataTemplateEntity> riskLevelList = findDictDataList("risk_level", null);

            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(templatePathName).build();
            WriteSheet writeSheet2 = EasyExcel.writerSheet(2).head(TemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet3 = EasyExcel.writerSheet(3).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet4 = EasyExcel.writerSheet(4).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet5 = EasyExcel.writerSheet(5).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet6 = EasyExcel.writerSheet(6).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet7 = EasyExcel.writerSheet(7).head(UserTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet8 = EasyExcel.writerSheet(8).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet9 = EasyExcel.writerSheet(9).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet10 = EasyExcel.writerSheet(10).head(EquipmentTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet11 = EasyExcel.writerSheet(11).head(SpaceTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet12 = EasyExcel.writerSheet(12).head(DictDataTemplateEntity.class).needHead(false).build();

            excelWriter.write(orgList, writeSheet2);
            excelWriter.write(sourceTypeList, writeSheet3);
            excelWriter.write(consequenceList, writeSheet4);
            excelWriter.write(inherentList, writeSheet5);
            excelWriter.write(frequencyList, writeSheet6);
            excelWriter.write(userList, writeSheet7);
            excelWriter.write(departmentList, writeSheet8);
            excelWriter.write(controlLevelList, writeSheet9);
            excelWriter.write(equipmentList, writeSheet10);
            excelWriter.write(spaceList, writeSheet11);
            excelWriter.write(riskLevelList, writeSheet12);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param response
     * @param fileName
     * @param orgId
     */
    public void downloadRiskPointTemplate(HttpServletResponse response, String fileName, String orgId) {
        try {
            /*List<SysFile> fileList = sysFileService.findByFileName(fileName);
            if (fileList == null || fileList.size() == 0) {
                return;
            }
            String fileDownName = fileList.get(0).getFileDowName();*/

            InputStream in = this.getClass().getClassLoader().getResourceAsStream("excel/fxddrmb.xlsx");;

            String fileName2 = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName2);

            OutputStream outputStream = response.getOutputStream();

            // 企业信息
            List<TemplateEntity> orgList = findOrgList(orgId);
            // 风险分类
            List<DictDataTemplateEntity> riskTypeList = findDictDataList("risk_type", null);
            // 部门
            List<SysOrg> departmentEntityList = findDepartmentList(orgId);
            Map<String, String> departmentMap = new HashMap<>();
            for (SysOrg department : departmentEntityList) {
                departmentMap.put(department.getOrgId(), department.getOrgName());
            }
            List<DictDataTemplateEntity> departmentList = findDepartmentTemplateList(departmentEntityList);
            // 人员
            List<UserTemplateEntity> userList = findDepartmentUserList(orgId, departmentMap);
            // 管控层级
            List<DictDataTemplateEntity> controlLevelList = findDictDataList("control_level", null);
            // 设备
            List<EquipmentTemplateEntity> equipmentList = findEquipmentList(orgId);
            // 空间
            List<SpaceTemplateEntity> spaceList = findWorkAreaList(orgId);

            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(in).build();
            WriteSheet writeSheet2 = EasyExcel.writerSheet(2).head(TemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet3 = EasyExcel.writerSheet(3).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet4 = EasyExcel.writerSheet(4).head(UserTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet5 = EasyExcel.writerSheet(5).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet6 = EasyExcel.writerSheet(6).head(DictDataTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet7 = EasyExcel.writerSheet(7).head(EquipmentTemplateEntity.class).needHead(false).build();
            WriteSheet writeSheet8 = EasyExcel.writerSheet(8).head(SpaceTemplateEntity.class).needHead(false).build();

            excelWriter.write(orgList, writeSheet2);
            excelWriter.write(riskTypeList, writeSheet3);
            excelWriter.write(userList, writeSheet4);
            excelWriter.write(departmentList, writeSheet5);
            excelWriter.write(controlLevelList, writeSheet6);
            excelWriter.write(equipmentList, writeSheet7);
            excelWriter.write(spaceList, writeSheet8);

            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取企业信息
     *
     * @return
     */
    public List<TemplateEntity> findOrgList(String orgId) {
        List<SysOrg> orgList;
        if (!StrUtil.isBlank(orgId)) {
            SysOrg org = orgService.getById(orgId);
            orgList = new ArrayList<>();
            orgList.add(org);
        } else {
            orgList = orgService.list();
        }
//        List<SysOrg> orgList = orgService.list();
//        if(orgList == null || orgList.size() == 0) {
//            return null;
//        }
        List<TemplateEntity> templateEntityList = orgList.stream().map(p -> new TemplateEntity(p.getOrgName(), p.getOrgCode())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * @param dictType
     * @param isRelation 级联数据（字典项的子项）是否查询， 默认不查 1-查
     * @return
     */
    public List<DictDataTemplateEntity> findDictDataList(String dictType, Integer isRelation) {
        if (StrUtil.isBlank(dictType)) {
            return null;
        }
        LambdaQueryWrapper<SysDictType> typeQueryWrapper = new LambdaQueryWrapper<>();
        typeQueryWrapper.eq(SysDictType::getStatus, BizConstants.STATUS_ENABLE)
                .eq(SysDictType::getDictType, dictType);
        SysDictType dictTypeObj = dictTypeService.getOne(typeQueryWrapper);
        if (dictTypeObj == null) {
            return null;
        }

        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getStatus, BizConstants.STATUS_ENABLE)
                .eq(SysDictData::getDictId, dictTypeObj.getDictId());
        if (isRelation == null || isRelation != 1) {
            queryWrapper.eq(SysDictData::getParentId, "0");
        }
        List<SysDictData> dictDataList = dictDataService.list(queryWrapper);
        if (dictDataList == null || dictDataList.size() == 0) {
            return null;
        }
        List<DictDataTemplateEntity> templateEntityList = dictDataList.stream().map(p -> new DictDataTemplateEntity(p.getDictValue())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * 获取 设备 信息
     *
     * @param orgId
     * @return
     */
    public List<EquipmentTemplateEntity> findEquipmentList(String orgId) {
        if (StrUtil.isBlank(orgId)) {
            return null;
        }
        TSafeEquipmentDTOParam equipmentDTOParam = new TSafeEquipmentDTOParam();
        equipmentDTOParam.setStatus(BizConstants.STATUS_ENABLE);
        equipmentDTOParam.setOrgId(orgId);
        List<TSafeEquipmentVO> equipmentDTOList = equipmentManageService.listByPage(equipmentDTOParam).getData();
        if (equipmentDTOList == null || equipmentDTOList.size() == 0) {
            return null;
        }

        List<EquipmentTemplateEntity> templateEntityList = equipmentDTOList.stream().map(p -> new EquipmentTemplateEntity(p.getSysTypeName(), p.getEquipmentTypeName(), p.getName(), p.getCode())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * 获取 空间 信息
     *
     * @param orgId
     * @return
     */
    public List<SpaceTemplateEntity> findWorkAreaList(String orgId) {
        if (StrUtil.isBlank(orgId)) {
            return null;
        }
        TSafeSpaceDTOParam spaceDTOParam = new TSafeSpaceDTOParam();
        spaceDTOParam.setStatus(BizConstants.STATUS_ENABLE);
        spaceDTOParam.setOrgId(orgId);
        spaceDTOParam.setLevel(2);
        List<TSafeSpaceVO> spaceDTOList = spaceManageService.listByPage(spaceDTOParam).getData();

        if (spaceDTOList == null || spaceDTOList.size() == 0) {
            return null;
        }

        List<SpaceTemplateEntity> templateEntityList = spaceDTOList.stream().map(p -> new SpaceTemplateEntity(p.getSpaceTypeName(), p.getSpaceName(), p.getSpaceCode(), p.getName(), p.getCode())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * 获取 部门 信息
     *
     * @param orgId
     * @return
     */
    public List<SysOrg> findDepartmentList(String orgId) {
        if (StrUtil.isBlank(orgId)) {
            return null;
        }

        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getStatus, BizConstants.STATUS_ENABLE)
                .eq(SysOrg::getParentId, orgId)
                .eq(SysOrg::getIsDept, "1");

        List<SysOrg> orgList = orgService.list(queryWrapper);
        return orgList;
    }

    /**
     * 获取 部门 信息
     *
     * @param orgList
     * @return
     */
    public List<DictDataTemplateEntity> findDepartmentTemplateList(List<SysOrg> orgList) {
        if (orgList == null || orgList.size() == 0) {
            return null;
        }

        List<DictDataTemplateEntity> templateEntityList = orgList.stream().map(p -> new DictDataTemplateEntity(p.getOrgName())).collect(Collectors.toList());
        return templateEntityList;
    }

    /**
     * 获取 部门人员 信息
     *
     * @param orgId
     * @return
     */
    public List<UserTemplateEntity> findDepartmentUserList(String orgId, Map<String, String> departmentListMap) {
        if (StrUtil.isBlank(orgId)) {
            return null;
        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getStatus, BizConstants.STATUS_ENABLE)
                .eq(SysUser::getOrgId, orgId);
        List<SysUser> userList = userService.list(queryWrapper);

        if (userList == null || userList.size() == 0) {
            return null;
        }

        List<UserTemplateEntity> templateEntityList = userList.stream().map(p -> {
            String departmentName = departmentListMap.get(p.getDeptId());
            return new UserTemplateEntity(departmentName == null ? "改用户位分配部门" : departmentName, p.getUserName(), p.getLoginName());
        }).collect(Collectors.toList());
        return templateEntityList;
    }
}
