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

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.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.file.util.MinioUtilS;
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.ProcessStatus;
import com.testor.common.constant.StatusEnum;
import com.testor.common.util.DateUtil;
import com.tongtech.tfw.backend.common.models.exceptions.ServiceException;
import com.testor.common.util.cron.FrequencyUtil;
import com.testor.common.util.excel.LocalDateTimeConverter;
import com.testor.ddd.safetyControl.infrastructure.uitls.IsMajorEnum;
import com.testor.module.duty.util.PoiExcelUtils;
import com.testor.module.safe.model.enums.HazardLevelEnum;
import com.testor.module.messageNotice.model.domain.TSysMsgRemindConf;
import com.testor.module.messageNotice.service.TSysMsgRemindConfService;
import com.testor.module.safe.dao.TSafeHazardOrgDao;
import com.testor.module.safe.model.domain.TSafeHazardOrg;
import com.testor.module.safe.model.domain.TSafeHazardStandardType;
import com.testor.module.safe.model.dto.TSafeHazardOrgDTO;
import com.testor.module.safe.model.dto.TSafeHazardOrgParam;
import com.testor.module.safe.model.vo.*;
import com.testor.module.safe.service.TSafeHazardOrgService;
import com.testor.module.safe.service.TSafeHazardStandardTypeService;
import com.testor.module.safeCheck.model.domain.*;
import com.testor.module.safeCheck.service.*;
import com.testor.module.sys.constant.NatureEnum;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.model.dto.CountVo;
import com.testor.module.sys.model.dto.SysUserInfo;
import com.testor.module.sys.service.NewSysDictDataService;
import com.testor.module.sys.service.NewSysOrgService;
import com.testor.module.sys.service.TOrgService;
import com.testor.module.sys.service.TSysUserService;
import com.testor.xxl.job.task.response.ReturnT;
import com.testor.xxl.job.task.util.CronUtil;
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.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.response.ResponseInfo;
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.bean.BeanHelper;
import com.tongtech.tfw.workflow.apis.instance.controller.ProcessInstanceController;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
import com.tongtech.tfw.workflow.apis.task.model.dto.CompleteTask;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTasksRequest;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTasksResponse;
import com.tongtech.tfw.workflow.service.TfwProcessInsService;
import com.tongtech.tfw.workflow.service.dto.ProcessInsStartParams;
import com.tongtech.tfw.workflow.service.dto.ProcessInsStartResult;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患上报台账Service业务层处理
 *
 * @author testor-framework
 * @date 2022-08-04 14:01:01
 */
@Service
public class TSafeHazardOrgServiceImpl extends SuperServiceImpl<TSafeHazardOrgDao, TSafeHazardOrg> implements TSafeHazardOrgService {
    private static final Logger logger = LoggerFactory.getLogger(TSafeHazardOrgServiceImpl.class);

    @Autowired(required = false)
    private TSafeHazardOrgDao tSafeHazardOrgDao;

    @Autowired
    private SysDictDataService sysDictDataService;

    @Autowired
    private NewSysDictDataService newSysDictDataService;

    @Autowired
    private SysDictTypeService sysDictTypeService;

    @Resource
    private FrequencyUtil frequencyUtil;

    @Autowired
    private TSysMsgRemindConfService tSysMsgRemindConfService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private NewSysOrgService newSysOrgService;

    @Autowired
    private TSafeHazardStandardTypeService tSafeHazardStandardTypeService;

    @Autowired
    private SysUserService sysUserService;

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${minio.endpoint}")
    private String targetHost;

    @Autowired
    private TOrgService tOrgService;

    @Autowired
    private MinioUtilS minioUtil;

    @Autowired
    private TfwProcessInsService tfwProcessInsService;

    @Autowired
    private TSysUserService tSysUserService;

    @Autowired
    private TSafeCheckOrgService tSafeCheckOrgService;

    @Autowired
    private TSafeCheckTaskRecordService tSafeCheckTaskRecordService;

    @Autowired
    private WfTaskController wfTaskController;

    @Override
    public BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> listEntity(TSafeHazardOrgParam param) {

        BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> 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<TSafeHazardOrgDTO> resultPage = new Page<>(page, limit);
        String orgId = param.getOrgId();

        if (StringUtils.isBlank(param.getOrgId())) {
            orgId = ContextUtils.getLoginUser().getOrgId();
        }else {
            // 按逗号分割 orgIds 字符串
            String[] ids = orgId.split(",");
            // 获取数组中的最后一个元素
            orgId = ids[ids.length - 1];
        }
        List<String> orgIds = new ArrayList<>();
        String finalOrgId = orgId;
        /*if (param.getCondOrgIdList() != null && param.getCondOrgIdList().size() > 0) {
            orgIds = param.getCondOrgIdList();
        }else {
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().and(sysOrgQueryWrapper -> sysOrgQueryWrapper.like(SysOrg.PARENT_IDS, finalOrgId).or().eq(SysOrg.ORG_ID, finalOrgId)).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        }*/
        if (StringUtils.isBlank(param.getOrgId())) {
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().and(sysOrgQueryWrapper -> sysOrgQueryWrapper.like(SysOrg.PARENT_IDS, finalOrgId).or().eq(SysOrg.ORG_ID, finalOrgId)).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        }else{
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().and(sysOrgQueryWrapper -> sysOrgQueryWrapper.eq(SysOrg.ORG_ID, finalOrgId)).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        }
        if (param.getIds() == null) {
            param.setCondOrgIdList(orgIds);
        }
        IPage<TSafeHazardOrgDTO> tSafeHazardOrgDTOIPage = tSafeHazardOrgDao.selectBaseList(resultPage, param);
        BaseResponseList<TSafeHazardOrgDTO> baseResponseList = new BaseResponseList<>();

        Map<String, String> map1 = new HashMap<>(16);
        Map<String, String> map2 = new HashMap<>(16);
        Map<String, String> map3 = new HashMap<>(16);
        Map<String, String> map4 = new HashMap<>(16);

        List<TSafeHazardOrgDTO> records = tSafeHazardOrgDTOIPage.getRecords();
        for (TSafeHazardOrgDTO record : records) {

            // 隐患分类
            String classify = record.getClassify();
            String classifyDictName = map1.get(classify);
            if (StringHelper.isEmpty(classifyDictName)) {
                classifyDictName = getDictName("safe_hazard_org_classify", classify);
                map1.put(classify, classifyDictName);
            }
            record.setClassify(classifyDictName);


            // 隐患级别
            String level = record.getLevel();
            String levelDictName = map2.get(level);
            if (StringHelper.isEmpty(levelDictName)) {
                levelDictName = getDictName("safe_hazard_org_level", level);
                map2.put(level, levelDictName);
            }
            record.setLevel(levelDictName);

            // 隐患类型
            String type = record.getType();
            String typeDictName = map3.get(type);
            if (StringHelper.isEmpty(typeDictName)) {
                typeDictName = getDictName("safe_hazard_org_type", type);
                map3.put(type, typeDictName);
            }
            record.setType(typeDictName);

            // 发现形式
            String checkType = record.getCheckType();
            String checkTypeDictName = map4.get(checkType);
            if (StringHelper.isEmpty(checkTypeDictName)) {
                checkTypeDictName = getDictName("safe_hazard_org_check_type", checkType);
                map4.put(checkType, checkTypeDictName);
            }
            record.setCheckType(checkTypeDictName);

            SysOrg regionalCompany = tOrgService.getRegionalCompany(record.getOrgId());
            if (regionalCompany != null) {
                record.setBusinessOrgName(regionalCompany.getOrgName());
            }

        }


        baseResponseList.setData(records);
        baseResponseList.setTotal(tSafeHazardOrgDTOIPage.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }
    @Override
    public BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> listEntityTodoList(TSafeHazardOrgParam param) {

        BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> 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<TSafeHazardOrgDTO> resultPage = new Page<>(page, limit);

        IPage<TSafeHazardOrgDTO> tSafeHazardOrgDTOIPage = tSafeHazardOrgDao.selectBaseList(resultPage, param);
        BaseResponseList<TSafeHazardOrgDTO> baseResponseList = new BaseResponseList<>();

        Map<String, String> map1 = new HashMap<>(16);
        Map<String, String> map2 = new HashMap<>(16);
        Map<String, String> map3 = new HashMap<>(16);
        Map<String, String> map4 = new HashMap<>(16);

        List<TSafeHazardOrgDTO> records = tSafeHazardOrgDTOIPage.getRecords();
        for (TSafeHazardOrgDTO record : records) {

            // 隐患分类
            String classify = record.getClassify();
            String classifyDictName = map1.get(classify);
            if (StringHelper.isEmpty(classifyDictName)) {
                classifyDictName = getDictName("safe_hazard_org_classify", classify);
                map1.put(classify, classifyDictName);
            }
            record.setClassify(classifyDictName);


            // 隐患级别
            String level = record.getLevel();
            String levelDictName = map2.get(level);
            if (StringHelper.isEmpty(levelDictName)) {
                levelDictName = getDictName("safe_hazard_org_level", level);
                map2.put(level, levelDictName);
            }
            record.setLevel(levelDictName);

            // 隐患类型
            String type = record.getType();
            String typeDictName = map3.get(type);
            if (StringHelper.isEmpty(typeDictName)) {
                typeDictName = getDictName("safe_hazard_org_type", type);
                map3.put(type, typeDictName);
            }
            record.setType(typeDictName);

            // 发现形式
            String checkType = record.getCheckType();
            String checkTypeDictName = map4.get(checkType);
            if (StringHelper.isEmpty(checkTypeDictName)) {
                checkTypeDictName = getDictName("safe_hazard_org_check_type", checkType);
                map4.put(checkType, checkTypeDictName);
            }
            record.setCheckType(checkTypeDictName);

            SysOrg regionalCompany = tOrgService.getRegionalCompany(record.getOrgId());
            if (regionalCompany != null) {
                record.setBusinessOrgName(regionalCompany.getOrgName());
            }

        }


        baseResponseList.setData(records);
        baseResponseList.setTotal(tSafeHazardOrgDTOIPage.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @Override
    public void createOrgTask(String id) {
        TSafeHazardOrg tSafeHazardOrg = getOne(
                new QueryWrapper<TSafeHazardOrg>()
                        .eq("id", id)
                        .eq("status", StatusEnum.USE.getCode())
        );
        if (ObjectHelper.isEmpty(tSafeHazardOrg)) {
            return;
        }

        TSysMsgRemindConf tSysMsgRemindConf;
        try {
            tSysMsgRemindConf = tSysMsgRemindConfService.getOne(
                    new QueryWrapper<TSysMsgRemindConf>()
                            .eq("type", 4)
                            .ne("status", StatusEnum.DELETE.getCode())
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 功能配置-上报
        String sysMsgStatus = tSysMsgRemindConf.getStatus();


        // 整改期限
        LocalDateTime rectifyDate = DateUtil.dateToLocalDateTime(tSafeHazardOrg.getRectifyDate());

        String taskCronStr = CronUtil.generateCronByOne(rectifyDate);


        /*JSONObject json = new JSONObject();
        json.put("id", id);
        json.put("rectifyDate", rectifyDate);*/
        // 时间点发送
        ReturnT hiddenRectification = frequencyUtil.createTaskJobResult(id, taskCronStr, "隐患上报-隐患整改-" + id + "-single", "hiddenRectificationSingle");
        int xxlJobCode = hiddenRectification.getCode();
        if (200 == xxlJobCode) {
            String xxlJobId = String.valueOf(hiddenRectification.getContent());
        }

        if (StatusEnum.USE.getCode().equals(sysMsgStatus)) {
            // 启用状态下才会发送消息

            // 单位（1-小时；2-天）
            Integer unit = tSysMsgRemindConf.getUnit();

            // 值
            Long value = tSysMsgRemindConf.getValue();

            // 任务频次key
            String frequencyKey = tSysMsgRemindConf.getFrequencyKey();
            if (1 == unit) {
                // 小时 减去 x 小时
                rectifyDate = rectifyDate.minusHours(value);
            } else if (2 == unit) {
                // 天 减去 x 天
                rectifyDate = rectifyDate.minusHours(value);
            }

            JSONObject pollingJson = new JSONObject();
            pollingJson.put("frequencyKey", frequencyKey);
            pollingJson.put("id", id);

            String params = pollingJson.toJSONString();

            taskCronStr = CronUtil.generateCronByOne(rectifyDate);
            ReturnT hiddenRectificationPolling = frequencyUtil.createTaskJobResult(params, taskCronStr, "隐患上报-隐患整改-调度创建初始", "createHiddenRectification");
            xxlJobCode = hiddenRectification.getCode();
            if (200 == xxlJobCode) {
                String xxlJobId = String.valueOf(hiddenRectification.getContent());
            }

        }
    }

    @Override
    public List<TSafeHazardOrgStatisticsVO> hiddenDangerStatistics(TSafeHazardOrgParam tSafeHazardOrgParam) {
        String orgId = tSafeHazardOrgParam.getOrgId();
        if (StringHelper.isEmpty(orgId)) {
            // 获取登录企业
            orgId = ContextUtils.getLoginUser().getOrgId();
        }
        String finalOrgId = orgId;
        List<String> orgIds = new ArrayList<>();
        if (tSafeHazardOrgParam.getCondOrgIdList() != null && tSafeHazardOrgParam.getCondOrgIdList().size() > 0) {
            orgIds = tSafeHazardOrgParam.getCondOrgIdList();
        }else {
            //如果只查当前机构数据
            if (tSafeHazardOrgParam.isThisOrg()) {
                orgIds.add(orgId);
            } else {
                List<String> ids = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, finalOrgId).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort")).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
                //如果下级机构为空
                if (ids == null || ids.size() == 0) {
                    //存入当前机构
                    ids.add(finalOrgId);
                }
                orgIds.addAll(ids);
            }
        }
        List<TSafeHazardOrgStatisticsVO> tSafeHazardOrgStatisticsVOS = new ArrayList<>();
        orgIds.stream().forEach(item -> {
            TSafeHazardOrgStatisticsVO tSafeHazardOrgStatisticsVO = new TSafeHazardOrgStatisticsVO();
            List<String> ids = new ArrayList<>();
            if (tSafeHazardOrgParam.isThisOrg()){
                ids.add(finalOrgId);
            }else {
                //如果下级机构为空
                ids = sysOrgService.list(new QueryWrapper<SysOrg>().and(sysOrgQueryWrapper -> sysOrgQueryWrapper.like(SysOrg.PARENT_IDS, item).or().eq(SysOrg.ORG_ID,item))
                        .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort")).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
                if (ids == null || ids.size() == 0) {
                    //存入当前机构
                    ids.add(finalOrgId);
                }
            }
            //完成数量
            QueryWrapper<TSafeHazardOrg> queryWrapperFinish = new QueryWrapper<>();
            //数量
            QueryWrapper<TSafeHazardOrg> queryWrapper = new QueryWrapper<>();
            //隐患级别
            if (StringHelper.isNotBlank(tSafeHazardOrgParam.getLevel())) {
                queryWrapperFinish.eq("\"level\"", tSafeHazardOrgParam.getLevel());
                queryWrapper.eq("\"level\"", tSafeHazardOrgParam.getLevel());
            }
            //上报时间筛选
            if (StringUtils.isNotBlank(tSafeHazardOrgParam.getStartTime()) && StringUtils.isNotBlank(tSafeHazardOrgParam.getEndTime())) {
                queryWrapperFinish.between("create_date", tSafeHazardOrgParam.getStartTime(), tSafeHazardOrgParam.getEndTime());
                queryWrapper.between("create_date", tSafeHazardOrgParam.getStartTime(), tSafeHazardOrgParam.getEndTime());
            }
            //重复隐患
            if (StringUtils.isNotBlank(tSafeHazardOrgParam.getIsRepeat())) {
                queryWrapperFinish.eq("is_repeat", tSafeHazardOrgParam.getIsRepeat());
                queryWrapper.eq("is_repeat", tSafeHazardOrgParam.getIsRepeat());
            }
            //计点状态
            if (StringUtils.isNotBlank(tSafeHazardOrgParam.getIsCount())) {
                queryWrapperFinish.eq("is_count", tSafeHazardOrgParam.getIsCount());
                queryWrapper.eq("is_count", tSafeHazardOrgParam.getIsCount());
            }
            if (ids.size() <= 0) {
                ids.add("-1");
            }
            queryWrapperFinish.in("org_id", ids);
            queryWrapper.in("org_id", ids);
            queryWrapperFinish
                    .eq(TSafeHazardOrg.STATUS, BizConstants.STATUS_ENABLE).eq("process_status", 5);
            long finishCount = this.list(queryWrapperFinish).stream().count();
            queryWrapper
                    .eq(TSafeHazardOrg.STATUS, BizConstants.STATUS_ENABLE);
            long hiddenDangersCount = this.list(queryWrapper).stream().count();
            tSafeHazardOrgStatisticsVO.setOrgId(item);
            tSafeHazardOrgStatisticsVO.setFinishCount(finishCount);
            tSafeHazardOrgStatisticsVO.setHiddenDangersCount(hiddenDangersCount);
            tSafeHazardOrgStatisticsVO.setOrgName(sysOrgService.getById(item).getOrgName());
            tSafeHazardOrgStatisticsVOS.add(tSafeHazardOrgStatisticsVO);
        });

        /*List<TSafeHazardOrgStatisticsVO> collect = tSafeHazardOrgStatisticsVOS.stream().sorted(
                Comparator.comparing(TSafeHazardOrgStatisticsVO::getGenerallyFinish, Comparator.reverseOrder())
                        .thenComparing(TSafeHazardOrgStatisticsVO::getGenerallyUndone, Comparator.reverseOrder())
                        .thenComparing(TSafeHazardOrgStatisticsVO::getMajorUndone)
                        .thenComparing(TSafeHazardOrgStatisticsVO::getMajorFinish, Comparator.reverseOrder())).collect(Collectors.toList());*/

        return tSafeHazardOrgStatisticsVOS;
    }

    /*@Override
    public List<TSafeHazardOrgStatisticsVO> hiddenDangerStatistics(TSafeHazardOrgParam tSafeHazardOrgParam) {
        String orgId = tSafeHazardOrgParam.getOrgId();
        if (StringHelper.isEmpty(orgId)) {
            // 获取登录企业的下级企业
            orgId = ContextUtils.getLoginUser().getOrgId();
        }
        List<String> orgIds = new ArrayList<>();
        SysOrg org = sysOrgService.getById(orgId);
        //如果当前登录机构不为粮库
        if (!"3".equals(org.getTreeLevel().toString())) {
            //获取下级机构id
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, orgId).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        } else {
            //获取当前机构
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        }
        List<TSafeHazardOrgStatisticsVO> tSafeHazardOrgStatisticsVOS = new ArrayList<>();
        orgIds.stream().forEach(item -> {
            TSafeHazardOrgStatisticsVO tSafeHazardOrgStatisticsVO = new TSafeHazardOrgStatisticsVO();
            List<String> ids = new ArrayList<>();
            if ("1".equals(org.getTreeLevel().toString())) {
                ids = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.PARENT_IDS, item)
                        .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort")).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            }
            if ("2".equals(org.getTreeLevel().toString()) || "3".equals(org.getTreeLevel().toString())) {
                ids = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.ORG_ID, item)
                        .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort")).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            }

            QueryWrapper<TSafeHazardOrg> queryWrappergenerallyFinish = new QueryWrapper<>();
            QueryWrapper<TSafeHazardOrg> queryWrappergenerallyUndone = new QueryWrapper<>();
            QueryWrapper<TSafeHazardOrg> queryWrappermajorFinish = new QueryWrapper<>();
            QueryWrapper<TSafeHazardOrg> queryWrappermajorUndone = new QueryWrapper<>();
            if (StringHelper.isNotBlank(tSafeHazardOrgParam.getClassify())) {
                queryWrappergenerallyFinish.eq("classify", tSafeHazardOrgParam.getClassify());
                queryWrappergenerallyUndone.eq("classify", tSafeHazardOrgParam.getClassify());
                queryWrappermajorFinish.eq("classify", tSafeHazardOrgParam.getClassify());
                queryWrappermajorUndone.eq("classify", tSafeHazardOrgParam.getClassify());
            }
            if (StringUtils.isNotBlank(tSafeHazardOrgParam.getStartTime()) && StringUtils.isNotBlank(tSafeHazardOrgParam.getEndTime())) {
                queryWrappergenerallyFinish.between("create_date", tSafeHazardOrgParam.getStartTime(), tSafeHazardOrgParam.getEndTime());
                queryWrappergenerallyUndone.between("create_date", tSafeHazardOrgParam.getStartTime(), tSafeHazardOrgParam.getEndTime());
                queryWrappermajorFinish.between("create_date", tSafeHazardOrgParam.getStartTime(), tSafeHazardOrgParam.getEndTime());
                queryWrappermajorUndone.between("create_date", tSafeHazardOrgParam.getStartTime(), tSafeHazardOrgParam.getEndTime());
            }
            if (ids.size() <= 0) {
                ids.add("11111111111");
            }
            queryWrappergenerallyFinish.in("org_id", ids);
            queryWrappergenerallyUndone.in("org_id", ids);
            queryWrappermajorFinish.in("org_id", ids);
            queryWrappermajorUndone.in("org_id", ids);
//            }
            // generallyFinish  一般不符合项 - 完成
            queryWrappergenerallyFinish
                    .ne(TSafeHazardOrg.STATUS, BizConstants.STATUS_DELETE).eq("\"level\"", 1).eq("process_status", 5);
            long generallyFinish = this.list(queryWrappergenerallyFinish).stream().count();
            // generallyUndone  一般不符合项 - 未完成
            queryWrappergenerallyUndone
                    .ne(TSafeHazardOrg.STATUS, BizConstants.STATUS_DELETE).eq("\"level\"", 1).ne("process_status", 5);
            long generallyUndone = this.list(queryWrappergenerallyUndone).stream().count();
            // majorFinish      重大不符合项 - 完成
            queryWrappermajorFinish
                    .ne(TSafeHazardOrg.STATUS, BizConstants.STATUS_DELETE).eq("\"level\"", 2).eq("process_status", 5);
            long majorFinish = this.list(queryWrappermajorFinish).stream().count();
            // majorUndone      重大不符合项 - 未完成
            queryWrappermajorUndone
                    .ne(TSafeHazardOrg.STATUS, BizConstants.STATUS_DELETE).eq("\"level\"", 2).ne("process_status", 5);
            long majorUndone = this.list(queryWrappermajorUndone).stream().count();
            tSafeHazardOrgStatisticsVO.setOrgId(item);
            tSafeHazardOrgStatisticsVO.setGenerallyFinish((int) generallyFinish);
            tSafeHazardOrgStatisticsVO.setGenerallyUndone((int) generallyUndone);
            tSafeHazardOrgStatisticsVO.setMajorFinish((int) majorFinish);
            tSafeHazardOrgStatisticsVO.setMajorUndone((int) majorUndone);
            tSafeHazardOrgStatisticsVO.setOrgName(sysOrgService.getById(item).getOrgName());
            tSafeHazardOrgStatisticsVOS.add(tSafeHazardOrgStatisticsVO);
        });

        List<TSafeHazardOrgStatisticsVO> collect = tSafeHazardOrgStatisticsVOS.stream().sorted(
                Comparator.comparing(TSafeHazardOrgStatisticsVO::getGenerallyFinish, Comparator.reverseOrder())
                        .thenComparing(TSafeHazardOrgStatisticsVO::getGenerallyUndone, Comparator.reverseOrder())
                        .thenComparing(TSafeHazardOrgStatisticsVO::getMajorUndone)
                        .thenComparing(TSafeHazardOrgStatisticsVO::getMajorFinish, Comparator.reverseOrder())).collect(Collectors.toList());

        return tSafeHazardOrgStatisticsVOS;
    }*/

    /**
     * 获取当前级下级的所属 orgId，如果没有下级就取本级
     *
     * @param tSafeHazardOrgParam .
     * @return .
     */
    private List<String> getOrgIds(TSafeHazardOrgParam tSafeHazardOrgParam) {
        String orgId = tSafeHazardOrgParam.getOrgId();

        if (StringUtils.isEmpty(orgId)) {
            // 如果为空查询自己所属下
            UserInfo loginUser = ContextUtils.getLoginUser();
            orgId = loginUser.getOrgId();
        }

        List<String> orgIds = new ArrayList<>();
        List<SysOrg> orgList = sysOrgService.getOrgListByParentId(orgId);
        if (ObjectUtils.isEmpty(orgList)) {
            // 如果为空查询自己
            orgIds.add(orgId);
        } else {
            // 不为空查询本级一下
            orgIds = orgList.stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        }
        return orgIds;
    }

    @Override
    public List<TSafeHazardOrgStatisticsTypeVO> hiddenStatisticsHistogram(TSafeHazardOrgParam tSafeHazardOrgParam) {

        List<String> orgIds = getOrgIds(tSafeHazardOrgParam);

        List<String> resultOrgIds = new ArrayList<>(orgIds);

        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        SysOrg sysOrg = sysOrgService.getById(orgId);
        String treeLevel = sysOrg.getTreeLevel().toString();
//        if ("1".equals(treeLevel) && StringUtils.isEmpty(tSafeHazardOrgParam.getOrgId())) {
        for (String id : orgIds) {
            // 查询区域公司下的所有粮库
            List<String> orgIdGrainDepot = sysOrgService.getOrgListByParentId(id).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            resultOrgIds.addAll(orgIdGrainDepot);
        }
//        }

        tSafeHazardOrgParam.setCondOrgIdList(resultOrgIds);


        List<TSafeHazardOrgStatisticsTypeVO> resultList = new ArrayList<>();

        List<TSafeHazardStandardType> tSafeHazardStandardTypeList = tSafeHazardStandardTypeService.listLevelOne();
        for (TSafeHazardStandardType tSafeHazardStandardType : tSafeHazardStandardTypeList) {
            TSafeHazardOrgStatisticsTypeVO tSafeHazardOrgStatisticsTypeVO = new TSafeHazardOrgStatisticsTypeVO();
            List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS = null;
            String name = tSafeHazardStandardType.getName();
            tSafeHazardOrgParam.setManageObject(name);
            if ("设备设施".equals(name)) {
                tSafeHazardOrgStatisticsTypeVOS = tSafeHazardOrgDao.hiddenDangerStatisticsEquipmentType(tSafeHazardOrgParam);
            } else if ("空间场所".equals(name)) {
                tSafeHazardOrgStatisticsTypeVOS = tSafeHazardOrgDao.hiddenDangerStatisticsSpaceType(tSafeHazardOrgParam);
            } else {
                // 功能配置
                tSafeHazardOrgStatisticsTypeVOS = tSafeHazardOrgDao.hiddenDangerStatisticsStandardType(tSafeHazardOrgParam);
            }
            tSafeHazardOrgStatisticsTypeVO.setName(name);
            tSafeHazardOrgStatisticsTypeVO.setTypeVOList(tSafeHazardOrgStatisticsTypeVOS);

            resultList.add(tSafeHazardOrgStatisticsTypeVO);
        }


        return resultList;
    }

    @Override
    public List<TSafeHazardOrgStatisticsTypeVO> hiddenStatisticsPieChart(TSafeHazardOrgParam tSafeHazardOrgParam) {


        List<String> orgIds = getOrgIds(tSafeHazardOrgParam);

        List<String> resultOrgIds = new ArrayList<>(orgIds);

        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        SysOrg sysOrg = sysOrgService.getById(orgId);
        String treeLevel = sysOrg.getTreeLevel().toString();
//        if ("1".equals(treeLevel) && StringUtils.isEmpty(tSafeHazardOrgParam.getOrgId())) {
        for (String id : orgIds) {
            // 查询区域公司下的所有粮库
            List<String> orgIdGrainDepot = sysOrgService.getOrgListByParentId(id).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            resultOrgIds.addAll(orgIdGrainDepot);
        }
//        }

        tSafeHazardOrgParam.setCondOrgIdList(resultOrgIds);

        List<TSafeHazardOrgStatisticsTypeVO> resultList = new ArrayList<>();


        // 隐患类型统计
        TSafeHazardOrgStatisticsTypeVO type = new TSafeHazardOrgStatisticsTypeVO();
        Map<String, String> typeMap = new HashMap<>();
        List<TSafeHazardOrgStatisticsTypeVO> typeVOS = tSafeHazardOrgDao.hiddenDangerStatisticsType(tSafeHazardOrgParam);
        setVODictName(typeMap, typeVOS, "safe_hazard_org_type");
        type.setTypeVOList(typeVOS);
        type.setName("隐患类型统计");
        resultList.add(type);

        // 隐患发现形式统计
        TSafeHazardOrgStatisticsTypeVO checkType = new TSafeHazardOrgStatisticsTypeVO();
        Map<String, String> checkTypeMap = new HashMap<>();
        List<TSafeHazardOrgStatisticsTypeVO> checkTypeVOS = tSafeHazardOrgDao.hiddenDangerStatisticsCheckType(tSafeHazardOrgParam);
        setVODictName(checkTypeMap, checkTypeVOS, "safe_hazard_org_check_type");
        checkType.setTypeVOList(checkTypeVOS);
        checkType.setName("隐患发现形式统计");
        resultList.add(checkType);


        // 隐患问题原因统计
        // 这个是查询已通过
        tSafeHazardOrgParam.setProcessStatus(ProcessStatus.PASSED.getCode());
        TSafeHazardOrgStatisticsTypeVO reason = new TSafeHazardOrgStatisticsTypeVO();
        Map<String, String> reasonMap = new HashMap<>();
        List<TSafeHazardOrgStatisticsTypeVO> reasonVOS = tSafeHazardOrgDao.hiddenDangerStatisticsReason(tSafeHazardOrgParam);
        setVODictName(reasonMap, reasonVOS, "safe_hazard_org_problem_causes");
        reason.setTypeVOList(reasonVOS);
        reason.setName("隐患问题原因统计");
        resultList.add(reason);

        return resultList;
    }

    @Override
    public List<HiddenDangerVO> getHiddenDangerNumber(List<String> orgIds, int treeLevel) {
        return tSafeHazardOrgDao.getHiddenDangerNumber(orgIds,treeLevel);
    }

    @Override
    public List<HiddenDangerVO> getHiddenDanger(List<String> orgIds) {
        return tSafeHazardOrgDao.getHiddenDanger(orgIds);
    }

    @Autowired
    private ProcessInstanceController processInstanceController;

    /*@SneakyThrows
    @Override
    public Boolean exportEntity(TSafeHazardOrgParam param, HttpServletResponse response) {
        try {
            String orgId = param.getOrgId();
            if (StringUtils.isBlank(orgId)) {
                orgId = ContextUtils.getLoginUser().getOrgId();
            }
            List<String> orgIds = new ArrayList<>();
            String finalOrgId = orgId;
            if (param.getCondOrgIdList() != null && param.getCondOrgIdList().size() > 0) {
                orgIds = param.getCondOrgIdList();
            }else {
                if (param.isThisOrg()) {
                    orgIds.add(orgId);
                } else {
                    orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.PARENT_IDS, finalOrgId).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                            .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
                    if (orgIds == null || orgIds.size() == 0) {
                        //存入当前机构
                        orgIds.add(finalOrgId);
                    }
                }
            }
            param.setCondOrgIdList(orgIds);
            List<TSafeHazardExportVO> tSafeHazardExportVOS = exportBuild(param);
            logger.info("**************************************写入模板*****************************");
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            String fileName = URLEncoder.encode("隐患台账", "utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");

            String fileName = "隐患台账";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");



            WriteSheet dealerSheet = EasyExcel.writerSheet(0, "隐患台账")
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).head(TSafeHazardExportVO.class).build();
            ExcelWriter build = EasyExcelFactory.write(response.getOutputStream()).build();
            build.write(tSafeHazardExportVOS,dealerSheet);
            build.finish();

            *//*InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/tzdc.xlsx");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(templatePathName).registerConverter(new LocalDateTimeConverter()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(tSafeHazardExportVOS, fillConfig, writeSheet);
            excelWriter.finish();
            byte[] bytes = out.toByteArray();
            out.flush();
            out.close();
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();*//*
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;

    }*/

    @SneakyThrows
    @Override
    public Boolean exportEntity(TSafeHazardOrgParam param, HttpServletResponse response) {
        try {
            /*String orgId = param.getOrgId();
            if (StringUtils.isBlank(orgId)) {
                orgId = ContextUtils.getLoginUser().getOrgId();
            }
            List<String> orgIds = new ArrayList<>();
            String finalOrgId = orgId;
            if (param.getCondOrgIdList() != null && param.getCondOrgIdList().size() > 0) {
                orgIds = param.getCondOrgIdList();
            }else {
                if (param.isThisOrg()) {
                    orgIds.add(orgId);
                } else {
                    orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.PARENT_IDS, finalOrgId).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                            .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
                    if (orgIds == null || orgIds.size() == 0) {
                        //存入当前机构
                        orgIds.add(finalOrgId);
                    }
                }
            }*/

            BaseResponse<BaseResponseList<TSafeHazardOrgDTO>> 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<TSafeHazardOrgDTO> resultPage = new Page<>(page, limit);
            String orgId = param.getOrgId();

            if (StringUtils.isBlank(param.getOrgId())) {
                orgId = ContextUtils.getLoginUser().getOrgId();
            }else {
                // 按逗号分割 orgIds 字符串
                String[] ids = orgId.split(",");
                // 获取数组中的最后一个元素
                orgId = ids[ids.length - 1];
            }
            List<String> orgIds = new ArrayList<>();
            String finalOrgId = orgId;
            if (StringUtils.isBlank(param.getOrgId())) {
                orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().and(sysOrgQueryWrapper -> sysOrgQueryWrapper.like(SysOrg.PARENT_IDS, finalOrgId).or().eq(SysOrg.ORG_ID, finalOrgId)).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                        .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            }else{
                orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().and(sysOrgQueryWrapper -> sysOrgQueryWrapper.eq(SysOrg.ORG_ID, finalOrgId)).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort"))
                        .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            }
            if (param.getIds() == null) {
                param.setCondOrgIdList(orgIds);
            }

            param.setCondOrgIdList(orgIds);
            List<TSafeHazardExportVO> tSafeHazardExportVOS = exportBuild(param);
            logger.info("**************************************写入模板*****************************");
//            response.setContentType("application/vnd.ms-excel");
//            response.setCharacterEncoding("utf-8");
//            String fileName = URLEncoder.encode("隐患台账", "utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//            response.addHeader("Pargam", "no-cache");
//            response.addHeader("Cache-Control", "no-cache");

            String fileName = "隐患台账";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");



            WriteSheet dealerSheet = EasyExcel.writerSheet(0, "隐患台账")
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).head(TSafeHazardExportVO.class).build();
            ExcelWriter build = EasyExcelFactory.write(response.getOutputStream()).build();
            build.write(tSafeHazardExportVOS,dealerSheet);
            build.finish();

            InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/tzdc.xlsx");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(templatePathName).registerConverter(new LocalDateTimeConverter()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(tSafeHazardExportVOS, fillConfig, writeSheet);
            excelWriter.finish();
            byte[] bytes = out.toByteArray();
            out.flush();
            out.close();
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;

    }

    private List<TSafeHazardExportVO> exportBuild(TSafeHazardOrgParam param) {
        Long page = Long.valueOf(param.getPage());
        Long limit = Long.valueOf(param.getLimit());
        Page<TSafeHazardOrgDTO> resultPage = new Page<>(page, limit);
        //根据条件拿到源数据
        IPage<TSafeHazardExportVO> tSafeHazardOrgDTOIPage = tSafeHazardOrgDao.exportList(resultPage, param);
        List<TSafeHazardExportVO> records = tSafeHazardOrgDTOIPage.getRecords();
        Integer number = 1;
        for (TSafeHazardExportVO tSafeHazardExportVO : records) {
            logger.info("****************************************封装数据**************************************");
            String orgId = tSafeHazardExportVO.getOrgId();
            tSafeHazardExportVO.setNumber(number);
            NewSysOrg byId = newSysOrgService.getById(orgId);
            if (byId != null) {
                String nature = byId.getNature();
                if (StringUtils.isBlank(nature)){
                    nature = String.valueOf(byId.getTreeLevel());
                }

                /*if ( byId.getTreeLevel().toString().equals("2")){
                    tSafeHazardExportVO.setRegionalUnits(byId.getOrgName());
                }else if (byId.getTreeLevel().toString().equals("3")){
                    NewSysOrg parenOrg = newSysOrgService.getById(byId.getParentId());
                    tSafeHazardExportVO.setRegionalUnits(parenOrg.getOrgName());
                    tSafeHazardExportVO.setGrassrootsUnits(byId.getOrgName());
                }*/
                //如果为大区
                if (nature.equals(NatureEnum.REGION.getCode())) {
                    tSafeHazardExportVO.setRegionalUnits(byId.getOrgName());
                //如果组织架构为经营部
                }else if (nature.equals(NatureEnum.BUSINESS_DEPARTMENT.getCode())) {
                    //设置大区
                    NewSysOrg parenOrg = newSysOrgService.getById(byId.getParentId());
                    tSafeHazardExportVO.setRegionalUnits(parenOrg.getOrgName());
                    //设置经营部
                    tSafeHazardExportVO.setBusinessDepartment(byId.getOrgName());
                }else if (nature.equals(NatureEnum.GRASSROOT.getCode())) {
                    //设置经营部
                    NewSysOrg parenOrg = newSysOrgService.getById(byId.getParentId());
                    String parenNature = parenOrg.getNature();
                    if (StringUtils.isBlank(parenNature)){
                        parenNature = String.valueOf(parenOrg.getTreeLevel());
                    }
                    //如果上级为大区
                    if (parenNature.equals(NatureEnum.REGION.getCode())){
                        tSafeHazardExportVO.setRegionalUnits(parenOrg.getOrgName());
                    }else {
                        //设置经营部
                        tSafeHazardExportVO.setBusinessDepartment(parenOrg.getOrgName());
                        //设置大区
                        NewSysOrg regionalUnit = newSysOrgService.getById(parenOrg.getParentId());
                        tSafeHazardExportVO.setRegionalUnits(regionalUnit.getOrgName());
                    }
                    //基层粮库
                    tSafeHazardExportVO.setGrassrootsUnits(byId.getOrgName());
                }
                //企业性质
                SysDictData natureData = newSysDictDataService.getDictTypeDetail(null, "NATURE", nature);
                if (natureData != null) {
                    tSafeHazardExportVO.setGrassroots(natureData.getDictValue());
                }
            }
            number ++;
            //隐患位置
            /*SysDictData locationData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_location", record.getLocation());
            if (locationData != null) {
                tSafeHazardExportVO.setLocation(locationData.getDictValue());
            }
            //隐患级别
            SysDictData levelData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_level", record.getLevel());
            if (levelData != null) {
                tSafeHazardExportVO.setLevel(levelData.getDictValue());
            }
            //隐患分类
            SysDictData classifyData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_classify", record.getClassify());
            if (classifyData != null) {
                tSafeHazardExportVO.setClassify(classifyData.getDictValue());
            }
            //隐患类型
            */

        }
        return records;
    }

   /* @SneakyThrows
    private List<TSafeHazardExportVO> exportBuild(TSafeHazardOrgParam param) {
        logger.info("****************************************进入封装**************************************");
        //整改状态
        Map<String, String> rectificationStatus = new HashMap<>();
        rectificationStatus.put("1", "已立行政");
        rectificationStatus.put("2", "整改完成");
        rectificationStatus.put("3", "需建立长效机制");
        //整改意见
        Map<String, String> acceptanceOpinion = new HashMap<>();
        acceptanceOpinion.put("1", "符合");
        acceptanceOpinion.put("2", "不符合");
        List<TSafeHazardExportVO> tSafeHazardExportVOS = new ArrayList<>();
        Long page = Long.valueOf(param.getPage());
        Long limit = Long.valueOf(param.getLimit());
        Page<TSafeHazardOrgDTO> resultPage = new Page<>(page, limit);
        //根据条件拿到源数据
        IPage<TSafeHazardOrgDTO> tSafeHazardOrgDTOIPage = tSafeHazardOrgDao.selectBaseList(resultPage, param);
        List<TSafeHazardOrgDTO> records = tSafeHazardOrgDTOIPage.getRecords();
        Integer number = 1;
        for (TSafeHazardOrgDTO record : records) {
            logger.info("****************************************封装数据**************************************");
            TSafeHazardExportVO tSafeHazardExportVO = new TSafeHazardExportVO();
            BeanUtils.copyProperties(record, tSafeHazardExportVO);
            ProcessInsVarRequest processInsVarRequest = new ProcessInsVarRequest();
            processInsVarRequest.setProcessInstanceId(record.getProcessId());
            logger.info("****************************************获取数据**************************************");
            Map<String, Object> data = processInstanceController.processInsVars(processInsVarRequest).getData();
            logger.info("****************************************数据是" + data + "**************************************");
            //序号
            tSafeHazardExportVO.setNumber(number);
            //隐患级别
            tSafeHazardExportVO.setLevel(getDictName("safe_hazard_org_level", record.getLevel()));
            //隐患类型
            tSafeHazardExportVO.setType(getDictName("safe_hazard_org_type", record.getType()));
            //发现形式
            tSafeHazardExportVO.setCheckType(getDictName("safe_hazard_org_check_type", record.getCheckType()));
            //业务单位
            tSafeHazardExportVO.setOrgId(getCompanyName(record.getOrgId()));
            //基层单位
            SysOrg byId = sysOrgService.getById(record.getOrgId());
            if (byId != null) {
                tSafeHazardExportVO.setBasicLevel(byId.getOrgName());
            }
            //问题分析
            tSafeHazardExportVO.setHiddenDangerReason(getDictName("safe_hazard_org_check_type", record.getHiddenDangerReason()));
            //整改人
            if (record.getRectifyPeople() != null && record.getRectifyPeople() != "") {
                tSafeHazardExportVO.setRectifyPeople(getUserName(record.getRectifyPeople()));
            }
            //验收人
            if (record.getAcceptance() != null && record.getAcceptance() != "") {
                tSafeHazardExportVO.setAcceptance(getUserName(record.getAcceptance()));
            }
            if (data == null) {
                continue;
            }
            //法规依据
            Object rule = data.get("rule");
            if (rule != null) {
                tSafeHazardExportVO.setRule(rule.toString());
            }
            //整改措施
            Object guardAgainst = data.get("guardAgainst");
            if (guardAgainst != null) {
                tSafeHazardExportVO.setRectification(guardAgainst.toString());
            }
            //整改前图片
            Object images = data.get("images");
            if (images != null) {
                String[] split = images.toString().split(",");
                if (split.length > 1) {
                    images = split[0];
                }
                if (active.equals("prod")) {
                    tSafeHazardExportVO.setRectificationPicture(new URL(replaceIpAddressAndPath(images.toString())));
                } else {
                    tSafeHazardExportVO.setRectificationPicture(checkUrl(images.toString()));
                }
            }
            //整改后图片
            Object imagesLast = data.get("imagesLast");
            if (imagesLast != null) {
                String[] split = imagesLast.toString().split(",");
                if (split.length > 1) {
                    imagesLast = split[0];
                }
                if (active.equals("prod")) {
                    tSafeHazardExportVO.setImagesLast(new URL(replaceIpAddressAndPath(images.toString())));
                } else {
                    tSafeHazardExportVO.setImagesLast(checkUrl(imagesLast.toString()));
                }
            }
            //整改状态
            Object rectificationStatus1 = data.get("rectificationStatus");
            if (rectificationStatus1 != null) {
                tSafeHazardExportVO.setRectificationStatus(rectificationStatus.get(rectificationStatus1.toString()));
            }
            //整改验收意见
            Object acceptanceOpinion1 = data.get("acceptanceOpinion");
            if (acceptanceOpinion1 != null) {
                tSafeHazardExportVO.setAcceptanceOpinion(acceptanceOpinion.get(acceptanceOpinion1.toString()));
            }
            //长效机制建设
            Object longMechanism = data.get("longMechanism");
            if (longMechanism != null) {
                tSafeHazardExportVO.setLongMechanism(longMechanism.toString());
            }
            //追责形态
            Object responsibleForm = data.get("responsibleForm");
            if (responsibleForm != null) {
                tSafeHazardExportVO.setResponsibleForm(responsibleForm.toString());
            }
            //追责结果
            Object responsibleResult = data.get("responsibleResult");
            if (responsibleResult != null) {
                tSafeHazardExportVO.setResponsibleResult(responsibleResult.toString());
            }
            //验证材料清单
            Object material = data.get("material");
            if (material != null) {
                tSafeHazardExportVO.setMaterial(material.toString());
            }
            tSafeHazardExportVOS.add(tSafeHazardExportVO);
            number++;
        }
        return tSafeHazardExportVOS;
    }*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buildData(){
        List<TSafeHazardOrg> tSafeHazardOrgs = this.list();
        DateTimeFormatter inputFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
        DateTimeFormatter inputFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (TSafeHazardOrg tSafeHazardOrg : tSafeHazardOrgs) {
            String processId = tSafeHazardOrg.getProcessId();
            if (StringUtils.isBlank(processId)) {
                continue;
            }

            HisTasksRequest hisTasksRequest = new HisTasksRequest();
            hisTasksRequest.setProcessInstanceId(processId);

            try {
                BaseResponse<BaseResponseList<HisTasksResponse>> historyByInstanceId = wfTaskController.getHistoryByInstanceId(hisTasksRequest);
                if (historyByInstanceId != null) {
                    BaseResponseList<HisTasksResponse> data = historyByInstanceId.getData();
                    if (data != null) {
                        List<HisTasksResponse> hisTasksResponses = data.getData();
                        Map<String, HisTasksResponse> taskMap = hisTasksResponses.stream()
                                .collect(Collectors.toMap(
                                        HisTasksResponse::getTaskName, // 使用taskType作为key
                                        task -> task,                  // 使用整个对象作为value
                                        (existing, replacement) -> replacement // 如果有重复的key，保留新的value
                                ));

                        // 存入整改开始时间 问题原因 整改投入 验证材料 整改措施 整改后照片
                        HisTasksResponse userTask = taskMap.get("隐患整改");
                        if (userTask != null) {
                            Map<String, Object> vars = userTask.getVars();
                            if (vars != null) {
                                Object openrTime = vars.get("openrTime");
                                if (openrTime != null) {
                                    LocalDateTime dateTime = parseDate(openrTime.toString(), inputFormatter1, inputFormatter2);

                                    if (dateTime != null) {
                                        tSafeHazardOrg.setRectifyStartDate(DateUtil.localDateTimeToDate(dateTime));
                                    }
                                }
                                tSafeHazardOrg.setProblemCauses(vars.getOrDefault("problemCauses", "").toString());
                                tSafeHazardOrg.setPutIn(vars.getOrDefault("putIn", "").toString());
                                tSafeHazardOrg.setMaterial(vars.getOrDefault("material", "").toString());
                                tSafeHazardOrg.setRectificationReform(vars.getOrDefault("guardAgainst", "").toString());
                                tSafeHazardOrg.setImagesLast(vars.getOrDefault("imagesLast", "").toString());
                            }
                        }

                        // 处理整改验收任务
                        HisTasksResponse acceptance = taskMap.get("整改验收");
                        if (acceptance != null) {
                            Map<String, Object> vars = acceptance.getVars();
                            if (vars != null) {
                                Object rectificationStatus = vars.get("rectificationStatus");
                                if (rectificationStatus != null) {
                                    tSafeHazardOrg.setRectificationStatus(rectificationStatus.toString());
                                }
                                tSafeHazardOrg.setAcceptanceOpinion(vars.getOrDefault("acceptanceOpinion", "").toString());
                                tSafeHazardOrg.setLongMechanism(vars.getOrDefault("longMechanism", "").toString());
                                Object acceptanceTime = vars.get("openrTime");
                                if (acceptanceTime != null) {
                                    LocalDateTime acceptanceDateTime = parseDate(acceptanceTime.toString(), inputFormatter1, inputFormatter2);
                                    if (acceptanceDateTime != null) {
                                        tSafeHazardOrg.setAcceptanceTime(DateUtil.localDateTimeToDate(acceptanceDateTime));
                                    }
                                }
                            }
                        }

                        // 处理工单指派任务
                        HisTasksResponse assigned = taskMap.get("工单指派");
                        if (assigned != null) {
                            Map<String, Object> vars = assigned.getVars();
                            if (vars != null) {
                                Object openrTime = vars.get("openrTime");
                                if (openrTime != null) {
                                    LocalDateTime assignedDateTime = parseDate(openrTime.toString(), inputFormatter1, inputFormatter2);
                                    if (assignedDateTime != null) {
                                        tSafeHazardOrg.setAssignedTime(DateUtil.localDateTimeToDate(assignedDateTime));
                                    }
                                }
                            }
                        }
                    }
                    this.updateById(tSafeHazardOrg);
                }
            } catch (NullPointerException e) {
                log.debug("----------------------------------------------------" + hisTasksRequest);
            }
        }
    }

    // 日期解析方法
    private LocalDateTime parseDate(String dateStr, DateTimeFormatter formatter1, DateTimeFormatter formatter2) {
        LocalDateTime dateTime = null;
        try {
            dateTime = LocalDateTime.parse(dateStr, formatter1);
        } catch (DateTimeParseException e) {
            try {
                dateTime = LocalDateTime.parse(dateStr, formatter2);
            } catch (DateTimeParseException e2) {
                log.debug("Date parsing error: " + dateStr);
            }
        }
        return dateTime;
    }

    public static String replaceIpAddressAndPath(String url) {
        try {
            URL oldURL = new URL(url);
            String protocol = oldURL.getProtocol();
            String path = oldURL.getPath().replace("/minio", "");
            String newUrl = protocol + "://" + "10.6.72.39:9000" + path;
            return newUrl;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return url; // Return the original URL if there is an error
        }
    }

    private String getUserName(String userId) {
        if (userId == null || userId == "") {
            return null;
        }
        SysUser byId = sysUserService.getById(userId);
        if (byId != null) {
            return byId.getUserName();
        }
        return null;
    }

    private URL checkUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        URL last = null;
        try {
            last = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) last.openConnection();
            conn.setRequestMethod("HEAD");
            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                last = null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            last = null;
        }
        return last;
    }

    /**
     * @description: 获取单位
     * @param: [orgId]
     * @return: {@link String}
     * @date: 2023/4/7 21:12
     */
    private String getCompanyName(String orgId) {
        SysOrg byId = sysOrgService.getById(orgId);
        if (byId == null) {
            return null;
        }
        List<String> split = Arrays.stream(byId.getParentIds().split(",")).collect(Collectors.toList());
        //如果父id有3个
        if (split.size() == 3) {
            return byId.getOrgName();
        }
        String id = split.get(1);
        SysOrg byId1 = sysOrgService.getById(id);
        return byId1.getOrgName();
    }


    private void setVODictName(Map<String, String> checkTypeMap, List<TSafeHazardOrgStatisticsTypeVO> checkTypeVOS, String dictType) {
        for (TSafeHazardOrgStatisticsTypeVO tSafeHazardOrgStatisticsTypeVO : checkTypeVOS) {
            String name = tSafeHazardOrgStatisticsTypeVO.getName();
            String dictName = checkTypeMap.get(name);
            if (StringUtils.isEmpty(dictName)) {
                dictName = getDictName(dictType, name);
                checkTypeMap.put(name, dictName);
            }
            tSafeHazardOrgStatisticsTypeVO.setName(dictName);
        }
    }

    /**
     * 根据字典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;
    }

    @Override
    public int getHiddenDangerCount(String orgId) {
        return this.baseMapper.getHiddenDangerCount(orgId);
    }

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importData(MultipartFile file, TSafeHazardOrgParam tSafeHazardOrg) {
        InputStream inputStream = file.getInputStream();
        // 读取Excel⽂件⼯作表
        Workbook workbook = PoiExcelUtils.readFile(inputStream, file.getOriginalFilename());
        //取得第⼀个⼯作表
        Sheet sheet = workbook.getSheetAt(0);

        List<Map<Integer, Object>> dataList = PoiExcelUtils.getBody(sheet, 21, 3);
        StringBuilder errorMsg = new StringBuilder();
        //校验数据
        List<TSafeHazardOrgParam> tSafeHazardOrgParams = checkData(dataList, errorMsg);
        if (errorMsg.length() > 0) {
            throw new ServiceException(ResponseInfo.builder().code(400).msg(errorMsg.toString()).build());
        }
        for (TSafeHazardOrgParam tSafeHazardOrgParam : tSafeHazardOrgParams) {
            tSafeHazardOrgParam.setTaskId(tSafeHazardOrg.getTaskId());
            //存储台账
            saveData(tSafeHazardOrgParam);
            //执行流程
            startProcess(tSafeHazardOrgParam);
        }
        return true;
    }


    private List<TSafeHazardOrgParam> checkData(List<Map<Integer, Object>> dataList,StringBuilder errorMsg){
        List<TSafeHazardOrgParam> tSafeHazardOrgParams = new ArrayList<>();
        //报表上传的没条数据
        int row = 3;
        DateTimeFormatter timeDtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        UserInfo loginUser = ContextUtils.getLoginUser();
        String orgId = loginUser.getOrgId();
        SysOrg sysOrg = sysOrgService.getById(orgId);
        for (Map<Integer, Object> integerObjectMap : dataList) {
            TSafeHazardOrgParam tSafeHazardOrg = new TSafeHazardOrgParam();
            row ++;
            //隐患单位编码
            String orgCode = String.valueOf(integerObjectMap.get(1));
            NewSysOrg sysOrgByCode = newSysOrgService.getSysOrgByCode(orgCode);
            if (sysOrgByCode == null) {
                errorMsg.append("第"+row+"行隐患单位编号"+orgCode+"不存在;");
                continue;
            }
            tSafeHazardOrg.setOrgId(sysOrgByCode.getOrgId());
            //隐患名称
            String name = String.valueOf(integerObjectMap.get(2));
            tSafeHazardOrg.setName(name);
            //发现形式编号
            String checkType = String.valueOf(integerObjectMap.get(3));
            SysDictData safeHazardOrgCheckType = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_check_type", checkType);
            //SysDictData checkTypeData = sysDictDataService.getOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, "32cb3c5f84904464b10188f027e53a15").eq(SysDictData::getDictKey, checkType));
            if (safeHazardOrgCheckType == null) {
                errorMsg.append(String.format("第%s行,发现形式编号【%s】数据不合法;",row,checkType));
                continue;
            }
            tSafeHazardOrg.setCheckType(checkType);
            //隐患位置编号
            String location = String.valueOf(integerObjectMap.get(4));
            SysDictData safeHazardOrgLocation = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_location", location);
            //SysDictData locationData = sysDictDataService.getOne(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, "2c737b4ee8d94431952cd52131c4e0de").eq(SysDictData::getDictKey, location));
            if (safeHazardOrgLocation == null) {
                errorMsg.append(String.format("第%s行,隐患位置编号【%s】数据不合法;",row,location));
                continue;
            }
            tSafeHazardOrg.setLocation(location);
            //隐患描述
            String remarks = String.valueOf(integerObjectMap.get(5));
            tSafeHazardOrg.setRemarks(remarks);
            //是否重复隐患
            String isRepeat = String.valueOf(integerObjectMap.get(6));
            if (isRepeat.equals(IsMajorEnum.yes.getMsg())) {
                isRepeat = "1";
            }else {
                isRepeat = "0";
            }
            tSafeHazardOrg.setIsRepeat(isRepeat);
            //隐患级别
            String level = String.valueOf(integerObjectMap.get(7));
            String code = HazardLevelEnum.getCodeByMsg(level);
            tSafeHazardOrg.setLevel(code);
            List<String> urls = new ArrayList<>();

            Object img1 = integerObjectMap.get(8);
            if (StringUtils.isBlank(img1.toString())) {
                errorMsg.append(String.format("第%s行,隐患图片1不能为空;",row));
                continue;
            }
            //隐患图片1
            PictureData pictureData1 = (PictureData) img1;
            String url1 = uploadFile(pictureData1);
            if (StringUtils.isNotBlank(url1)){
                urls.add(url1);
            }

            Object img2 = integerObjectMap.get(9);
            if (StringUtils.isNotBlank(img2.toString())) {
                //隐患图片2
                PictureData pictureData2 = (PictureData) img2;
                String url2 = uploadFile(pictureData2);
                if (StringUtils.isNotBlank(url2)){
                    urls.add(url2);
                }
            }

            Object img3 = integerObjectMap.get(10);
            if (StringUtils.isNotBlank(img3.toString())) {
                //隐患图片3
                PictureData pictureData3 = (PictureData) img3;
                String url3 = uploadFile(pictureData3);
                if (StringUtils.isNotBlank(url3)) {
                    urls.add(url3);
                }
            }
            //设置隐患照片
            tSafeHazardOrg.setImages(String.join(",", urls));
            //是否计点
            String isCount = String.valueOf(integerObjectMap.get(11));
            tSafeHazardOrg.setIsCount("0");
            //如果计点
            if (isCount.equals(IsMajorEnum.yes.getMsg())) {
                //计点编号
                String countCode = String.valueOf(integerObjectMap.get(12));
                if (StringUtils.isBlank(countCode)){
                    errorMsg.append("第"+row+"行,计点编号不能为空;");
                    continue;
                }
                List<String> list = Arrays.asList(countCode.split(","));
                int finalRow = row;
                list.stream().forEach(item -> {
                    SysDictData safeHazardOrgCount = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_count", item);
                    /*SysDictData one = sysDictDataService.getOne(
                            new LambdaQueryWrapper<SysDictData>()
                                    .eq(SysDictData::getDictId, "22693421408e4becaea321870beeb08a")
                                    .eq(SysDictData::getDictKey, item)
                    );*/
                    if (safeHazardOrgCount == null) {
                        errorMsg.append(String.format("第%s行,计点编号【%s】不存在;", finalRow,item));
                    }
                });
                //如果当前登录的账号为总部账号一个计点项算两分
                if (sysOrg.getTreeLevel().equals("1")) {
                    tSafeHazardOrg.setScore(String.valueOf(list.size() * 2));
                }else {
                    tSafeHazardOrg.setScore(String.valueOf(list.size()));
                }
                tSafeHazardOrg.setIsCount("1");
                tSafeHazardOrg.setCountDetail(countCode);
            }
            //是否转工单
            String transfer = String.valueOf(integerObjectMap.get(13));
            String transferCode = IsMajorEnum.no.getCode();
            //如果转工单
            if (transfer.equals(IsMajorEnum.yes.getMsg())) {
                transfer(row,tSafeHazardOrg,integerObjectMap,timeDtf,errorMsg);
                transferCode = IsMajorEnum.yes.getCode();
            }
            tSafeHazardOrg.setWorkOrder(transferCode);
            tSafeHazardOrgParams.add(tSafeHazardOrg);
        }
        return tSafeHazardOrgParams;
    }

    private void transfer(int row,TSafeHazardOrg tSafeHazardOrg,Map<Integer, Object> integerObjectMap,DateTimeFormatter timeDtf,StringBuilder errorMsg) {
        // 隐患分类
        String classify = String.valueOf(integerObjectMap.get(14));
        if (classify == null || classify.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行隐患分类编号不能为空;");
            return;
        }
        SysDictData classifyData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_classify", classify);
        if (classifyData == null) {
            errorMsg.append(String.format("第%s行,隐患分类编号【%s】数据不合法;",row,classify));
            return;
        }
        tSafeHazardOrg.setClassify(classify);

        // 隐患类型
        String type = String.valueOf(integerObjectMap.get(15));
        if (type == null || type.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行,隐患类型编号不能为空;");
            return;
        }
        SysDictData typeData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_type", type);
        if (typeData == null) {
            errorMsg.append(String.format("第%s行,隐患类型编号【%s】数据不合法;",row,type));
            return;
        }
        tSafeHazardOrg.setType(type);

        // 法依法规
        String rule = String.valueOf(integerObjectMap.get(16));
        if (rule == null || rule.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行法依法规不能为空;");
            return;
        }
        tSafeHazardOrg.setRule(rule);

        // 整改前措施
        String guardAgainst = String.valueOf(integerObjectMap.get(17));
        if (guardAgainst == null || guardAgainst.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行整改前措施不能为空;");
            return;
        }
        tSafeHazardOrg.setGuardAgainst(guardAgainst);
        // 整改人
        String rectifyPeople = String.valueOf(integerObjectMap.get(18));
        if (rectifyPeople == null || rectifyPeople.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行,整改人账号不能为空;");
            return;
        }
        SysUser rectifyUser = tSysUserService.getUserByLoginName(rectifyPeople);
        if (rectifyUser == null) {
            errorMsg.append("第 " + row + " 行,整改人账号【"+rectifyPeople+"】不存在;");
            return;
        }
        tSafeHazardOrg.setRectifyPeople(rectifyUser.getUserId());

        // 验收人
        String acceptance = String.valueOf(integerObjectMap.get(19));
        if (acceptance == null || acceptance.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行,验收人不能为空;");
            return;
        }
        SysUser acceptanceUser = tSysUserService.getUserByLoginName(acceptance);
        if (acceptanceUser == null) {
            errorMsg.append("第 " + row + " 行,验收人账号【"+acceptance+"】不存在;");
            return;
        }
        tSafeHazardOrg.setAcceptance(acceptanceUser.getUserId());
        // 整改日期
        String rectifyDate = String.valueOf(integerObjectMap.get(20));
        if (rectifyDate == null || rectifyDate.trim().isEmpty()) {
            errorMsg.append("第 " + row + " 行,整改日期不能为空;");
            return;
        }
        //设置指派人、指派时间
        tSafeHazardOrg.setAssigner(ContextUtils.getLoginUserId());
        tSafeHazardOrg.setAssignedTime(new Date());
        //设置待签收
        tSafeHazardOrg.setProcessStatus("2");
        try {
            LocalDateTime date = LocalDateTime.parse(rectifyDate, timeDtf);
            tSafeHazardOrg.setRectifyStartDate(DateUtil.localDateTimeToDate(date));
        } catch (DateTimeParseException e) {
            errorMsg.append("第 ").append(row).append(" 行,整改日期格式无效: ").append(rectifyDate).append(";");
        }
    }

    private void startProcess(TSafeHazardOrg tSafeHazardOrg){
        ProcessInsStartParams processInsStartParams = new ProcessInsStartParams();
        processInsStartParams.setBizKey(tSafeHazardOrg.getId());
        processInsStartParams.setProcessDefinitionKey("hiddenDangerReport");
        //流转到被隐患单位，要用隐患单位id
        processInsStartParams.setOrgId(tSafeHazardOrg.getOrgId());
        processInsStartParams.setUserId(tSafeHazardOrg.getCreateBy());
        Map<String, Object> varMap = new HashMap<>();

        String rectifyPeople = tSafeHazardOrg.getRectifyPeople();
        varMap.put("orgId", tSafeHazardOrg.getOrgId());
        String processStatus = "3";
        SysOrg byId = sysOrgService.getById(tSafeHazardOrg.getOrgId());
        varMap.put("orgName", byId.getOrgName());
        varMap.put("location",tSafeHazardOrg.getLocation());
        varMap.put("remarks",tSafeHazardOrg.getRemarks());
        varMap.put("images",tSafeHazardOrg.getImages());
        varMap.put("create_person",tSafeHazardOrg.getCreateBy());
        varMap.put("create_Time",tSafeHazardOrg.getCreateDate());
        varMap.put("checkType",tSafeHazardOrg.getCheckType());
        varMap.put("name",tSafeHazardOrg.getName());
        varMap.put("workOrder",tSafeHazardOrg.getWorkOrder());

        //待指派
        varMap.put("processStatus", processStatus);
        varMap.put("bizKeyId",tSafeHazardOrg.getId());
        processInsStartParams.setVariables(varMap);
        ProcessInsStartResult processInsStartResult = tfwProcessInsService.startProcessInsByKey(processInsStartParams);
        String code = processInsStartResult.getCode();
        tSafeHazardOrg.setProcessId(code);
        tSafeHazardOrg.setProcessStatus(processStatus);
        this.updateById(tSafeHazardOrg);
        //如果有整改人 转工单
        if (StringUtils.isNotBlank(rectifyPeople)) {
            HisTasksRequest hisTasksRequest = new HisTasksRequest();
            hisTasksRequest.setProcessInstanceId(processInsStartResult.getCode());
            List<HisTasksResponse> data = wfTaskController.getHistoryByInstanceId(hisTasksRequest).getData().getData();
            List<HisTasksResponse> filteredTasks = data.stream()
                    .filter(task -> "工单指派".equals(task.getTaskName()))
                    .collect(Collectors.toList());
            HisTasksResponse hisTasksResponse = filteredTasks.get(0);
            CompleteTask completeTask = new CompleteTask();
            completeTask.setOrgId(tSafeHazardOrg.getOrgId());
            completeTask.setUserId(tSafeHazardOrg.getCreateBy());
            completeTask.setBizId(tSafeHazardOrg.getId());
            completeTask.setTaskId(hisTasksResponse.getTaskId());
            completeTask.setLocalScope(true);
            Map<String, Object> vars = new HashMap<>();
            vars.put("acceptance", tSafeHazardOrg.getAcceptance());
            SysUser acceptance = sysUserService.getById(tSafeHazardOrg.getAcceptance());
            vars.put("acceptanceDepartment", acceptance.getDeptId());
            vars.put("assigner", tSafeHazardOrg.getAssigner());
            vars.put("classify", tSafeHazardOrg.getClassify());
            vars.put("createBy", tSafeHazardOrg.getCreateBy());
            vars.put("guardAgainst", tSafeHazardOrg.getGuardAgainst());
            vars.put("level", tSafeHazardOrg.getLevel());
            vars.put("name", tSafeHazardOrg.getName());
            SysUser assigner = sysUserService.getById(tSafeHazardOrg.getAssigner());
            vars.put("openerName", assigner.getUserName());
            vars.put("openerUserId", tSafeHazardOrg.getAssigner());
            vars.put("openrTime", tSafeHazardOrg.getAssignedTime());
            vars.put("rectifyPeople", rectifyPeople);
            SysUser rectifyPeopleData = sysUserService.getById(rectifyPeople);
            vars.put("rectifyDepartment", rectifyPeopleData.getDeptId());
            vars.put("rectifyPeopleName", rectifyPeopleData.getUserName());
            vars.put("rectifyStartDate", tSafeHazardOrg.getRectifyStartDate());
            vars.put("rule", tSafeHazardOrg.getRule());
            vars.put("templateType", "assign");
            vars.put("type", tSafeHazardOrg.getType());
            vars.put("processStatus", "2");
            completeTask.setVars(vars);
            //完成指派任务
            wfTaskController.completeTask(completeTask);
            //设置待签收
            tSafeHazardOrg.setProcessStatus("2");
            this.updateById(tSafeHazardOrg);
        }

    }

    //这里就是已经获取到图片后的正常上传而已，获取到的图片信息为PictureData，转为MultipartFile进行的文件上传
    private String uploadFile(PictureData pictureData){
        if(null != pictureData && pictureData.getData().length > 0){
            InputStream inputStream = new ByteArrayInputStream(pictureData.getData());
            // 获取图片扩展名（例如 "jpg", "png" 等）
            String ext = pictureData.suggestFileExtension();
            FileDTO fileDTO = null;
            try {
                MultipartFile multipartFile = new MockMultipartFile(String.valueOf(pictureData),"hazardImage"+System.currentTimeMillis()+"."+ext, "image/" + ext, inputStream);
                fileDTO = minioUtil.upload(new MultipartFile[]{multipartFile}).get(0);
            } catch (IOException e) {
                log.error("字节流转文件失败："+ e.getMessage());
                throw new ServiceException(ResponseInfo.builder().code(400).msg("字节流转文件失败").build());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if(Objects.isNull(fileDTO) || StringUtils.isEmpty(fileDTO.getFilePath())){
                throw new ServiceException(ResponseInfo.builder().code(400).msg("未获取到上传文件的信息").build());
            }
            return fileDTO.getFilePath();
        }
        return null;
    }

    @SneakyThrows
    @Override
    public boolean exportTemplate(HttpServletResponse response, String planId) {
        String fileName = URLEncoder.encode("隐患台账导入模板", "utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download;charset=utf-8");
        response.setHeader("Content-disposition", URLEncoder.encode(fileName, "UTF-8"));
        //mime类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        response.setHeader("Pragma", "No-cache");
        ExcelWriter excelWriter = null;
        ServletOutputStream outputStream = null;
        List<String> orgIds = tSafeCheckOrgService.getListByPlanId(planId).stream().map(TSafeCheckOrg::getCheckOrgId).collect(Collectors.toList());
        //参考企业信息
        List<NewSysOrg> orgByIds = newSysOrgService.getOrgByIds(orgIds);
        //发现形式
        List<SysDictData> formOfIssuance = newSysDictDataService.getDictByType("safe_hazard_org_check_type");
        //隐患位置
        List<SysDictData> position = newSysDictDataService.getDictByType("safe_hazard_org_location");
        //隐患分类
        List<SysDictData> classify = newSysDictDataService.getDictByType("safe_hazard_org_classify");
        //隐患类型
        List<SysDictData> type = newSysDictDataService.getDictByType("safe_hazard_org_type");
        //参考人员信息
        List<SysUserInfo> sysUserInfos = orgByIds.stream()
                .flatMap(sysOrg -> sysUserService.list(new LambdaQueryWrapper<SysUser>()
                                .eq(SysUser::getOrgId, sysOrg.getOrgId()))
                        .stream()
                        .map(sysUser -> {
                            SysUserInfo sysUserInfo = new SysUserInfo();
                            sysUserInfo.setOrgName(sysOrg.getOrgName());
                            sysUserInfo.setOrgId(sysOrg.getOrgId());
                            NewSysOrg dept = newSysOrgService.getById(sysUser.getDeptId());
                            sysUserInfo.setUserName(sysUser.getUserName());
                            sysUserInfo.setLoginName(sysUser.getLoginName());
                            if (dept != null) {
                                sysUserInfo.setDeptName(dept.getOrgName());
                                sysUserInfo.setDeptId(dept.getOrgId());
                            }
                            return sysUserInfo;
                        })
                ).collect(Collectors.toList());
        List<CountVo> counts = new ArrayList<>();
        SysDictType safeHazardOrgCount = sysDictTypeService.getOne(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, "safe_hazard_org_count").ne(SysDictType::getStatus, "1"));
        if(safeHazardOrgCount != null){
            List<SysDictData> countType = sysDictDataService.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, safeHazardOrgCount.getDictId()).eq(SysDictData::getParentId,"0"));
            for (SysDictData sysDictData : countType) {
                List<SysDictData> count = sysDictDataService.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getParentId, sysDictData.getDictDataId()));
                for (SysDictData dictData : count) {
                    CountVo countVo = new CountVo();
                    countVo.setCode(dictData.getDictKey());
                    countVo.setType(sysDictData.getDictValue());
                    countVo.setCount(dictData.getDictValue());
                    counts.add(countVo);
                }
            }
        }
        try (InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/yhtzdrmb.xlsx")) {
            outputStream = response.getOutputStream();
            excelWriter = EasyExcel.write(outputStream).registerConverter(new LocalDateTimeConverter()).withTemplate(templatePathName).build();
            WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
            excelWriter.fill(orgByIds, writeSheet2);
            WriteSheet writeSheet3 = EasyExcel.writerSheet(3).build();
            excelWriter.fill(formOfIssuance, writeSheet3);
            WriteSheet writeSheet4 = EasyExcel.writerSheet(4).build();
            excelWriter.fill(position, writeSheet4);
            WriteSheet writeSheet5 = EasyExcel.writerSheet(5).build();
            excelWriter.fill(classify, writeSheet5);
            WriteSheet writeSheet6 = EasyExcel.writerSheet(6).build();
            excelWriter.fill(type, writeSheet6);
            WriteSheet writeSheet7 = EasyExcel.writerSheet(7).build();
            excelWriter.fill(sysUserInfos, writeSheet7);
            WriteSheet writeSheet8 = EasyExcel.writerSheet(8).build();
            excelWriter.fill(counts, writeSheet8);
        } catch (IOException e) {
            // 处理异常
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // 处理异常
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public TSafeHazardOrg getDetails(String id) {
        TSafeHazardOrg data = this.getById(id);
        TSafeHazardOrgVo tSafeHazardOrgVo = BeanHelper.beanToBean(data, TSafeHazardOrgVo.class);
        if (data != null) {
            //存放上报人
            if (data.getCreateBy() != null) {
                SysUser sysUser = sysUserService.getById(data.getCreateBy());
                if (sysUser != null) {
                    tSafeHazardOrgVo.setCreateName(sysUser.getUserName());
                }
            }
            //存放相关单位名称
            if (data.getOrgId() != null) {
                SysOrg sysOrg = sysOrgService.getById(data.getOrgId());
                if (sysOrg != null) {
                    tSafeHazardOrgVo.setOrgName(sysOrg.getOrgName());
                }
            }
            //设置验收人
            if (data.getAcceptance() != null) {
                SysUser sysUser = sysUserService.getById(data.getAcceptance());
                if (sysUser != null) {
                    tSafeHazardOrgVo.setAcceptanceName(sysUser.getUserName());
                }
            }
            //设置整改人
            if (data.getRectifyPeople() != null) {
                SysUser sysUser = sysUserService.getById(data.getRectifyPeople());
                if (sysUser != null) {
                    tSafeHazardOrgVo.setRectifyPeopleName(sysUser.getUserName());
                }
            }
            //发现形式
            String checkType = data.getCheckType();
            SysDictData sysDictData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_check_type", checkType);
            if (sysDictData != null) {
                tSafeHazardOrgVo.setCheckTypeName(sysDictData.getDictValue());
            }
            //存放位置
            String location = data.getLocation();

            SysDictData locationData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_location", location);
            //如果不存在就是旧数据，不做处理
            if (locationData != null) {
                location = locationData.getDictValue();
            }
            tSafeHazardOrgVo.setLocationName(location);
            //隐患级别
            String level = data.getLevel();
            SysDictData levelData =  newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_level", level);
            if (levelData != null) {
                tSafeHazardOrgVo.setLevelName(levelData.getDictValue());
            }
            String countDetail = tSafeHazardOrgVo.getCountDetail();
            if (StringUtils.isNotBlank(countDetail)) {
                List<String> dictKey = Arrays.asList(countDetail.split(","));
                //获取所有字典值
                SysDictType safeHazardOrgCount = sysDictTypeService.getOne(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, "safe_hazard_org_count").eq(SysDictType::getStatus, StatusEnum.USE.getCode()));
                String dictId = safeHazardOrgCount.getDictId();
                //查出所有父类
                List<SysDictData> dictDataList = sysDictDataService.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictId, dictId).eq(SysDictData::getStatus, StatusEnum.USE)
                        .eq(SysDictData::getParentId, "0"));

                Map<String, List<SysDictData>> dictDataMap = dictDataList.stream()
                        .collect(Collectors.toMap(
                                SysDictData::getDictDataId,
                                dictData -> new ArrayList<>()
                        ));

                // 确保所有的父节点都有一个空列表
                for (SysDictData parentData : dictDataList) {
                    dictDataMap.putIfAbsent(parentData.getDictDataId(), new ArrayList<>());
                }
                // 遍历 dictKey 获取每个子节点
                for (String key : dictKey) {
                    SysDictData keyData = newSysDictDataService.getDictTypeDetail(null, "safe_hazard_org_count", key);
                    String parentId = keyData.getParentId();

                    // 将子节点添加到其父节点的列表中
                    List<SysDictData> parentDataList = dictDataMap.get(parentId);
                    if (parentDataList != null) {
                        parentDataList.add(keyData);
                    } else {
                        // 如果 parentId 不在 dictDataMap 中，添加新条目
                        parentDataList = new ArrayList<>();
                        parentDataList.add(keyData);
                        dictDataMap.put(parentId, parentDataList);
                    }
                }
                tSafeHazardOrgVo.setCountDetailMap(dictDataMap);
            }

        }
        return tSafeHazardOrgVo;
    }

    @Override
    public boolean saveData(TSafeHazardOrgParam addRequest) {
        // TODO 按需求添加数据去重，特殊值设定，业务异常
        String id = IdHelper.getId32bit();
        TSafeHazardOrg data = BeanHelper.beanToBean(addRequest, TSafeHazardOrg.class);
        // TODO 编号随机（具体生成规则待定）
        data.setNumbering(String.valueOf(System.currentTimeMillis()));
        data.setId(id);

        //安全检查任务id不为空
        if (StringUtils.isNotBlank(addRequest.getTaskId())){
            //添加隐患记录
            TSafeCheckTaskRecord tSafeCheckTaskRecord = new TSafeCheckTaskRecord();
            tSafeCheckTaskRecord.setTaskId(addRequest.getTaskId());
            tSafeCheckTaskRecord.setPlanId(addRequest.getPlanId());
            tSafeCheckTaskRecord.setRefType(TSafeCheckTaskRecord.RefType.HIDDEN_TROUBLE.getCode());
            tSafeCheckTaskRecord.setRefId(id);
            tSafeCheckTaskRecordService.save(tSafeCheckTaskRecord);
        }
        return this.save(data);
    }

    @Override
    public List<HiddenStatisticsVo> hiddenTypeStatistics(TSafeHazardOrgParam param) {

        return Collections.emptyList();
    }

    @Override
    public List<TSafeHazardOrgStatisticsTypeVO> hiddenStatisticsByConditions(TSafeHazardOrgParam param) {
        String conditionType = param.getConditionType();
        String orgId = param.getOrgId();
        if (StringHelper.isEmpty(orgId)) {
            // 获取登录企业
            orgId = ContextUtils.getLoginUser().getOrgId();
        }
        List<String> orgIds = new ArrayList<>();
        if (param.getCondOrgIdList() != null && param.getCondOrgIdList().size() > 0) {
            orgIds = param.getCondOrgIdList();
        }else {
            //如果只查当前机构数据
            if (param.isThisOrg()) {
                orgIds.add(orgId);
            } else {
                String finalOrgId = orgId;
                orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.PARENT_IDS, finalOrgId).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0).orderByAsc("tree_sort")).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
                if (orgIds == null || orgIds.size() == 0) {
                    //存入当前机构
                    orgIds.add(finalOrgId);
                }
            }
        }
        param.setCondOrgIdList(orgIds);
        switch (conditionType) {
            //类型统计
            case "TYPE":
                 List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS = tSafeHazardOrgDao.hiddenDangerStatisticsByType(param);
                return tSafeHazardOrgStatisticsTypeVOS;
                //位置统计
            case "LOCATION":
                List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS1 = tSafeHazardOrgDao.hiddenDangerStatisticsLocation(param);
                return tSafeHazardOrgStatisticsTypeVOS1;
                //原因统计
            case "CAUSE":
                List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS2 = tSafeHazardOrgDao.hiddenDangerStatisticsCause(param);
                return tSafeHazardOrgStatisticsTypeVOS2;
            case "CLASSIFY":
                List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS3 = tSafeHazardOrgDao.hiddenDangerStatisticsClassify(param);
                return tSafeHazardOrgStatisticsTypeVOS3;
            case "ORG_TYPE":
                List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS4 = tSafeHazardOrgDao.hiddenDangerStatisticsOrgType(param);
                return tSafeHazardOrgStatisticsTypeVOS4;
            case "CHECK_TYPE":
                List<TSafeHazardOrgStatisticsTypeVO> tSafeHazardOrgStatisticsTypeVOS5 = tSafeHazardOrgDao.hiddenDangerStatisticsByCheckType(param);
                return tSafeHazardOrgStatisticsTypeVOS5;
        }
        return Collections.emptyList();
    }
}
