package com.njcn.supervision.service.user.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.bpm.api.BpmProcessFeignClient;
import com.njcn.bpm.enums.BpmProcessInstanceStatusEnum;
import com.njcn.bpm.enums.BpmTaskStatusEnum;
import com.njcn.bpm.pojo.dto.BpmInstanceInfo;
import com.njcn.bpm.pojo.dto.BpmProcessInstanceCreateReqDTO;
import com.njcn.bpm.pojo.param.instance.BpmProcessInstanceCancelParam;
import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.FileUtil;
import com.njcn.device.pms.utils.PubUtil;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.poi.excel.ExcelUtil;
import com.njcn.poi.excel.PullDown;
import com.njcn.poi.util.PoiUtil;
import com.njcn.supervision.enums.FlowStatusEnum;
import com.njcn.supervision.enums.SupervisionKeyEnum;
import com.njcn.supervision.enums.SupervisionResponseEnum;
import com.njcn.supervision.enums.UserNatureEnum;
import com.njcn.supervision.mapper.device.SupervisionTempLineReportMapper;
import com.njcn.supervision.mapper.user.UserReportNormalMapper;
import com.njcn.supervision.mapper.user.UserReportPOMapper;
import com.njcn.supervision.pojo.dto.SensitiveReportExcel;
import com.njcn.supervision.pojo.dto.SensitiveUserSExcel;
import com.njcn.supervision.pojo.param.SensitiveUserParam;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineReport;
import com.njcn.supervision.pojo.po.user.*;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.supervision.pojo.vo.user.UserReportVO;
import com.njcn.supervision.service.user.*;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.user.pojo.vo.UserVO;
import com.njcn.web.constant.ValidMessage;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import com.njcn.web.utils.WebUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description:
 * Date: 2024/4/25  10:07【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserReportPOServiceImpl extends ServiceImpl<UserReportPOMapper, UserReportPO> implements UserReportPOService {

    private final UserReportProjectPOService userReportProjectPOService;
    private final UserReportSubstationPOService userReportSubstationPOService;
    private final UserReportSensitivePOService userReportSensitivePOService;
    private final BpmProcessFeignClient bpmProcessFeignClient;
    private final UserFeignClient userFeignClient;
    private final DeptFeignClient deptFeignClient;
    private final SupervisionTempLineReportMapper supervisionTempLineReportMapper;
    private final LineFeignClient lineFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final DictTreeFeignClient dictTreeFeignClient;
    private final UserReportNormalMapper userReportNormalMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUserReport(UserReportParam userReportParam) {
        UserReportPO userReportPO = new UserReportPO();
        BeanUtils.copyProperties(userReportParam, userReportPO);
        userReportPO.setState(DataStateEnum.ENABLE.getCode());
        if (Objects.equals(userReportParam.getSaveOrCheckflag(), "2")) {
            checkProjectName(userReportParam, !StringUtils.isEmpty(userReportParam.getId()));
        }
        //判断工程名称是否有重复的
        if (Objects.equals(userReportParam.getSaveOrCheckflag(), "1")) {
            userReportPO.setStatus(BpmTaskStatusEnum.WAIT.getStatus());
            checkProjectName(userReportParam, !StringUtils.isEmpty(userReportParam.getId()));
        } else {
            //常态化干扰源用户信息更新的用的
            if (!Objects.equals(userReportParam.getSaveOrCheckflag(), "0")) {
                userReportPO.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
            }
        }
        if (ObjectUtil.isNotNull(userReportParam.getDataType())) {
            userReportPO.setDataType(userReportParam.getDataType());
            if (userReportParam.getDataType() == 1) {
                if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportParam.getUserType())) {
                    userReportPO.setStatus(BpmTaskStatusEnum.APPROVE.getStatus());
                }
            }
        } else {
            userReportPO.setDataType(0);
        }
        this.saveOrUpdate(userReportPO);
        userReportPO = this.getById(userReportPO.getId());
        if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_POWER_GRID.getCode(),
                        UserNatureEnum.EXTEND_POWER_GRID.getCode()
                ).contains(userReportPO.getUserType())) {
            //电网工程类用户额外数据
            UserReportProjectPO userReportProjectPO = userReportParam.getUserReportProjectPO();
            userReportProjectPO.setId(userReportPO.getId());
            userReportProjectPO.setState(DataStateEnum.ENABLE.getCode());
            userReportProjectPOService.saveOrUpdate(userReportProjectPO);
        } else if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                        UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                ).contains(userReportPO.getUserType())) {
            //非线性负荷用户 & 新能源发电站用户
            UserReportSubstationPO userReportSubstationPO = userReportParam.getUserReportSubstationPO();
            userReportSubstationPO.setId(userReportPO.getId());
            userReportSubstationPO.setState(DataStateEnum.ENABLE.getCode());
            userReportSubstationPOService.saveOrUpdate(userReportSubstationPO);
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportPO.getUserType())) {
            // 敏感及重要用户
            UserReportSensitivePO userReportSensitivePO = userReportParam.getUserReportSensitivePO();
            userReportSensitivePO.setId(userReportPO.getId());
            userReportSensitivePO.setState(DataStateEnum.ENABLE.getCode());
            userReportSensitivePOService.saveOrUpdate(userReportSensitivePO);
        }

        // 如何未提交审则不需要发起 BPM 流程
        if (Objects.equals(userReportParam.getSaveOrCheckflag(), "2")) {
            Map<String, Object> processInstanceVariables = new HashMap<>(16);
            BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
            //干扰源用户台账和敏感用户审核流程
            if (ObjectUtil.isNotNull(userReportParam.getDataType())) {
                if (userReportParam.getDataType() == 1) {
                    bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.BUILD_USER_INFO_ARCHIVIST.getKey());
                }
            } else {
                bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.BUILD_USER_INFO.getKey());
            }
            bpmProcessInstanceCreateReqDTO.setBusinessKey(userReportPO.getId());
            bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(userReportParam.getStartUserSelectAssignees());
            bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
            String processInstanceId = bpmProcessFeignClient.createProcessInstance(userReportPO.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
            // 将工作流的编号，更新到流程单中
            userReportPO.setProcessInstanceId(processInstanceId);
            this.baseMapper.updateById(userReportPO);
        }
        return userReportPO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateUserReport(UserReportParam.UserReportUpdate userReportParam) {
        //判断工程名称是否有重复的
        if (Objects.equals(userReportParam.getSaveOrCheckflag(), "2")) {
            checkProjectName(userReportParam, !StringUtils.isEmpty(userReportParam.getId()));
        }

        UserReportPO userReportPO = this.baseMapper.selectById(userReportParam.getId());
        //判断是否有权限操作
        InstanceUtil.judgeUserPower(RequestUtil.getUserIndex(), userReportPO.getCreateBy());
        if (Objects.equals(userReportPO.getStatus(), BpmTaskStatusEnum.APPROVE.getStatus())) {
            throw new BusinessException("当前流程以完成审批,无法重新发起");
        }

        //处理历史流程id列表
        String historyInstanceIds = InstanceUtil.dealHistoryId(userReportPO.getProcessInstanceId(), userReportPO.getHistoryInstanceId());

        BeanUtil.copyProperties(userReportParam, userReportPO);

        if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_POWER_GRID.getCode(),
                        UserNatureEnum.EXTEND_POWER_GRID.getCode()
                ).contains(userReportPO.getUserType())) {
            //电网工程类用户额外数据
            UserReportProjectPO userReportProjectPO = userReportParam.getUserReportProjectPO();
            userReportProjectPO.setId(userReportPO.getId());
            userReportProjectPO.setState(DataStateEnum.ENABLE.getCode());
            userReportProjectPOService.updateById(userReportProjectPO);
        } else if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                        UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                ).contains(userReportPO.getUserType())) {
            //非线性负荷用户 & 新能源发电站用户
            UserReportSubstationPO userReportSubstationPO = userReportParam.getUserReportSubstationPO();
            userReportSubstationPO.setId(userReportPO.getId());
            userReportSubstationPO.setState(DataStateEnum.ENABLE.getCode());
            userReportSubstationPOService.updateById(userReportSubstationPO);
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportPO.getUserType())) {
            // 敏感及重要用户
            UserReportSensitivePO userReportSensitivePO = userReportParam.getUserReportSensitivePO();
            userReportSensitivePO.setId(userReportPO.getId());
            userReportSensitivePO.setState(DataStateEnum.ENABLE.getCode());
            userReportSensitivePOService.updateById(userReportSensitivePO);
        }


        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        String key = SupervisionKeyEnum.BUILD_USER_INFO.getKey();
        if (ObjectUtil.isNotNull(userReportPO.getDataType())) {
            //干扰源用户台账和敏感用户审核流程
            if (userReportPO.getDataType() == 1) {
                key = SupervisionKeyEnum.BUILD_USER_INFO_ARCHIVIST.getKey();
            }
        }
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(key);
        bpmProcessInstanceCreateReqDTO.setBusinessKey(userReportPO.getId());
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(userReportParam.getStartUserSelectAssignees());
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(userReportPO.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        userReportPO.setProcessInstanceId(processInstanceId);
        userReportPO.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        userReportPO.setState(DataStateEnum.ENABLE.getCode());
        //保存历史流程id列表
        userReportPO.setHistoryInstanceId(historyInstanceIds);
        this.baseMapper.updateById(userReportPO);
        return userReportPO.getId();

    }


    @Override
    public boolean auditUserReport(UserReportParam.UserReportUpdate userReportUpdate) {
        String id = userReportUpdate.getId();
        UserReportPO byId = this.getById(id);
        //判断是否有权限操作
        InstanceUtil.judgeUserPower(RequestUtil.getUserIndex(), byId.getCreateBy());
        //判断工程名称是否有重复的
        checkProjectName(userReportUpdate, true);
        BeanUtils.copyProperties(userReportUpdate, byId);
        this.updateById(byId);
        if (CollectionUtil.newArrayList(
                UserNatureEnum.BUILD_POWER_GRID.getCode(),
                UserNatureEnum.EXTEND_POWER_GRID.getCode()
        ).contains(byId.getUserType())) {
            //电网工程类用户额外数据
            UserReportProjectPO userReportProjectPO = userReportProjectPOService.getById(id);
            BeanUtils.copyProperties(userReportUpdate.getUserReportProjectPO(), userReportProjectPO, getNullPropertyNames(userReportUpdate.getUserReportProjectPO()));
            userReportProjectPOService.updateById(userReportProjectPO);
        } else if (CollectionUtil.newArrayList(
                UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
        ).contains(byId.getUserType())) {
            UserReportSubstationPO userReportSubstationPO = userReportSubstationPOService.getById(id);
            BeanUtils.copyProperties(userReportUpdate.getUserReportSubstationPO(), userReportSubstationPO, getNullPropertyNames(userReportUpdate.getUserReportSubstationPO()));
            userReportSubstationPOService.updateById(userReportSubstationPO);
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(byId.getUserType())) {
            UserReportSensitivePO userReportSensitivePO = userReportSensitivePOService.getById(id);
            BeanUtils.copyProperties(userReportUpdate.getUserReportSensitivePO(), userReportSensitivePO, getNullPropertyNames(userReportUpdate.getUserReportSensitivePO()));
            userReportSensitivePOService.updateById(userReportSensitivePO);
        }

        return true;
    }

    /**
     * 数据权限：填报人的同部门及上级部门的所有用户都能看到该填报人的申请信息
     */
    @Override
    public Page<UserReportVO> getUserReport(UserReportParam.UserReportQueryParam userReportQueryParam) {
        //正则校验
        Pattern pattern = Pattern.compile(PatternRegex.DES32_REGEX);
        Matcher matcher = pattern.matcher(userReportQueryParam.getProjectName());
        if (StringUtils.isNotBlank(userReportQueryParam.getProjectName()) && !matcher.matches()) {
            throw new BusinessException(ValidMessage.SEARCH_DATA_ERROR);
        }
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        userReportVOQueryWrapper.in("supervision_user_report.create_by", colleaguesIds)
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_user_report.data_type", 0);
        if (Objects.nonNull(userReportQueryParam)) {
            if (StrUtil.isNotBlank(userReportQueryParam.getCity())) {
                //查询所有区域下的数据
                userReportVOQueryWrapper.in("supervision_user_report.city", userReportQueryParam.getCity());
            }
            userReportVOQueryWrapper
                    .and(CollUtil.isNotEmpty(InstanceUtil.filterTaskStatus()), w -> w.in("supervision_user_report.status", InstanceUtil.filterTaskStatus())
                            .or()
                            .eq("supervision_user_report.create_by", RequestUtil.getUserIndex())
                    );
            if (ObjectUtil.isNotNull(userReportQueryParam.getStatus())) {
                userReportVOQueryWrapper.eq("supervision_user_report.status", userReportQueryParam.getStatus());
            }
            userReportVOQueryWrapper.like(StringUtils.isNotBlank(userReportQueryParam.getProjectName()), "supervision_user_report.project_name", userReportQueryParam.getProjectName());
            //添加上时间范围
            if (StrUtil.isNotBlank(userReportQueryParam.getSearchBeginTime()) && StrUtil.isNotBlank(userReportQueryParam.getSearchEndTime())) {

                userReportVOQueryWrapper.and(x -> x.between("supervision_user_report.report_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                        .or()
                        .isNull("supervision_user_report.expected_production_date")
                        .or()
                        .between("supervision_user_report.expected_production_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                );
            }
            userReportVOQueryWrapper.orderByDesc("supervision_user_report.Update_Time");
        }
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        return this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
    }

    @Override
    public UserReportVO getUserReportById(String id) {
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();
        userReportVOQueryWrapper.eq("supervision_user_report.id", id);
        return this.baseMapper.getUserReportById(userReportVOQueryWrapper);

    }

    @Override
    public Boolean removeUserReport(List<String> ids) {
        this.lambdaUpdate().set(UserReportPO::getState, 0).in(UserReportPO::getId, ids).update();
        userReportProjectPOService.lambdaUpdate().set(UserReportProjectPO::getState, 0).in(UserReportProjectPO::getId, ids).update();
        userReportSubstationPOService.lambdaUpdate().set(UserReportSubstationPO::getState, 0).in(UserReportSubstationPO::getId, ids).update();
        userReportSensitivePOService.lambdaUpdate().set(UserReportSensitivePO::getState, 0).in(UserReportSensitivePO::getId, ids).update();
        return true;
    }

    @Override
    public UserReportVO.UserReportListVO getVOById(String id) {
        UserReportVO.UserReportListVO userReportVO = new UserReportVO.UserReportListVO();
        UserReportPO userReportPO = this.baseMapper.selectById(id);
        //复制基础信息
        BeanUtil.copyProperties(userReportPO, userReportVO);
        //处理特殊字段，用户名、部门名
        UserVO userVO = userFeignClient.getUserById(userReportPO.getReporter()).getData();
        userReportVO.setReporter(userVO.getName());
        userReportVO.setOrgName(deptFeignClient.getDeptById(userReportPO.getOrgId()).getData().getName());
        /*
            根据用户性质获取自己特有的字段，此处需要特殊处理
            1、每个附件需要返回文件名称以及可以预览的url
            todo...by黄正剑
         */
        if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_POWER_GRID.getCode(),
                        UserNatureEnum.EXTEND_POWER_GRID.getCode()
                ).contains(userReportPO.getUserType())) {
            //电网工程类用户额外数据
            UserReportProjectPO byId = userReportProjectPOService.getById(id);
            userReportVO.setUserReportProjectPO(byId);

        } else if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                        UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                ).contains(userReportPO.getUserType())) {
            //非线性负荷用户 & 新能源发电站用户
            UserReportSubstationPO byId = userReportSubstationPOService.getById(id);
            userReportSubstationPOService.saveOrUpdate(byId);
            userReportVO.setUserReportSubstationPO(byId);
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportPO.getUserType())) {
            // 敏感及重要用户
            UserReportSensitivePO byId = userReportSensitivePOService.getById(id);
            userReportVO.setUserReportSensitivePO(byId);
        }
        List<UserReportNormalPO> list = userReportNormalMapper.selectList(new LambdaQueryWrapper<UserReportNormalPO>()
                .eq(UserReportNormalPO::getUserReportId, id)
                .eq(UserReportNormalPO::getStatus, BpmTaskStatusEnum.APPROVE.getStatus())
                .eq(UserReportNormalPO::getState, DataStateEnum.ENABLE.getCode())
                .orderByDesc(UserReportNormalPO::getCreateTime)
        );
        Optional<String> netInReport = list.stream().filter(x -> 0 == x.getType()).map(UserReportNormalPO::getReportUrl).findFirst();
        Optional<String> governReport = list.stream().filter(x -> 1 == x.getType()).map(UserReportNormalPO::getReportUrl).findFirst();
        Optional<String> simulationReport = list.stream().filter(x -> 1 == x.getType()).map(UserReportNormalPO::getSimulationReportUrl).findFirst();
        userReportVO.setNetInReport(Collections.singletonList(netInReport.orElse(null)));
        userReportVO.setGovernReport(Collections.singletonList(governReport.orElse(null)));
        userReportVO.setSimulationReport(Collections.singletonList(simulationReport.orElse(null)));
        return userReportVO;
    }

    @Override
    public void updateProcessStatus(String businessKey, Integer status) {
        UserReportPO userReportPO = this.baseMapper.selectById(businessKey);
        userReportPO.setStatus(status);
        this.updateById(userReportPO);
    }

    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        BpmInstanceInfo bpmInstanceInfo = new BpmInstanceInfo();
        UserReportPO userReportPO = this.getById(businessId);
        if (Objects.isNull(userReportPO)) {
            return null;
        }
        bpmInstanceInfo.setHistoryInstanceId(userReportPO.getHistoryInstanceId());
        bpmInstanceInfo.setInstanceSign(userReportPO.getProjectName());
        return bpmInstanceInfo;
    }

    @Override
    public Set<String> getAllRejectInstanceIds() {
        Set<String> rejectInstanceIds = new HashSet<>();
        // 查询所有走了流程，但是流程状态为不通过的流程实例id
        LambdaQueryWrapper<UserReportPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserReportPO::getCreateBy, RequestUtil.getUserIndex())
                .eq(UserReportPO::getStatus, BpmProcessInstanceStatusEnum.REJECT.getStatus())
                .eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode())
                .select(UserReportPO::getProcessInstanceId);
        List<UserReportPO> userReportPOList = this.baseMapper.selectList(lambdaQueryWrapper);
        List<String> result = userReportPOList.stream().map(UserReportPO::getProcessInstanceId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(result)) {
            rejectInstanceIds.addAll(result);
        }
        return rejectInstanceIds;
    }

    @Override
    public List<UserReportVO> getUserReportList() {
        String deptIndex = RequestUtil.getDeptIndex();
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(deptIndex).getData();

        List<UserReportPO> list = this.lambdaQuery()
                .eq(UserReportPO::getStatus, 2)
                .eq(UserReportPO::getDataType, 0)
                .in(CollectionUtil.isNotEmpty(data), UserReportPO::getOrgId, data)
                .list();
        return list.stream().map(temp -> {
            UserReportVO vo = new UserReportVO();
            BeanUtils.copyProperties(temp, vo);
            UserVO userVO = userFeignClient.getUserById(temp.getReporter()).getData();
            vo.setReporter(temp.getReporter());
            vo.setReporterName(userVO.getName());
            vo.setOrgName(deptFeignClient.getDeptById(temp.getOrgId()).getData().getName());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public Page<UserReportVO> getInterferenceUserPage(UserReportParam.UserReportQueryParam userReportQueryParam, Boolean allDataFlag) {
        //正则校验
        Pattern pattern = Pattern.compile(PatternRegex.ALL_CHAR_1_20);
        Matcher matcher = pattern.matcher(userReportQueryParam.getProjectName());
        if (StringUtils.isNotBlank(userReportQueryParam.getProjectName()) && !matcher.matches()) {
            throw new BusinessException(ValidMessage.SEARCH_DATA_ERROR);
        }
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(userReportQueryParam.getOrgId()).getData();
        //此处仅查询敏感及重要用户
        userReportVOQueryWrapper.and(wrapper ->
                        wrapper.in("supervision_user_report.create_by", colleaguesIds)
                                .or()
                                .in("supervision_user_report.org_id", data)
                )
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode());
        if (!allDataFlag) {
            //台账不查询全部数据，需要排除敏感及重要用户
            userReportVOQueryWrapper.ne("supervision_user_report.user_type", UserNatureEnum.SENSITIVE_USER.getCode())
                    .and(CollUtil.isNotEmpty(InstanceUtil.filterTaskStatus()), w -> w.in("supervision_user_report.status", InstanceUtil.filterTaskStatus())
                            .or()
                            .eq("supervision_user_report.create_by", RequestUtil.getUserIndex())
                    );
        } else {
            userReportVOQueryWrapper.eq("supervision_user_report.status", FlowStatusEnum.APPROVE.getCode());
        }
        if (Objects.nonNull(userReportQueryParam)) {
            if (StrUtil.isNotBlank(userReportQueryParam.getCity())) {
                //查询所有区域下的数据
                userReportVOQueryWrapper.in("supervision_user_report.city", userReportQueryParam.getCity());
            }
            if (Objects.nonNull(userReportQueryParam.getDataType())) {
                userReportVOQueryWrapper.eq("data_type", userReportQueryParam.getDataType());
            }
            userReportVOQueryWrapper.like(StringUtils.isNotBlank(userReportQueryParam.getProjectName()), "supervision_user_report.project_name", userReportQueryParam.getProjectName());
            if (StrUtil.isNotBlank(userReportQueryParam.getSearchBeginTime()) && StrUtil.isNotBlank(userReportQueryParam.getSearchEndTime())) {
                userReportVOQueryWrapper.and(wrapper -> wrapper.between("supervision_user_report.report_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                        .or()
                        .between("supervision_user_report.expected_production_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                );
            }
            userReportVOQueryWrapper.orderByDesc("supervision_user_report.Update_Time");
        }
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        Page<UserReportVO> page;
        if (!allDataFlag) {
            page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
        } else {
            page = this.baseMapper.pageUpdate(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
        }
        page.getRecords().forEach(temp -> {
            Integer needGovernance = 0;
            if (
                    CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_POWER_GRID.getCode(),
                            UserNatureEnum.EXTEND_POWER_GRID.getCode()
                    ).contains(temp.getUserType())) {
                //电网工程类用户额外数据
                needGovernance = userReportProjectPOService.getById(temp.getId()).getNeedGovernance();
            } else if (
                    CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                            UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                    ).contains(temp.getUserType())) {
                //非线性负荷用户 & 新能源发电站用户

                needGovernance = userReportSubstationPOService.getById(temp.getId()).getNeedGovernance();
            } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(temp.getUserType())) {
                // 敏感及重要用户
                needGovernance = userReportSensitivePOService.getById(temp.getId()).getNeedGovernance();
            }
            temp.setNeedGovernance(needGovernance);
            //添加治理评估文件，需先判断入网评估是否审核通过
            boolean type = true;
            if (1 == temp.getNeedGovernance()) {
                List<UserReportNormalPO> list = userReportNormalMapper.selectList(new LambdaQueryWrapper<UserReportNormalPO>()
                        .eq(UserReportNormalPO::getUserReportId, temp.getId())
                        .eq(UserReportNormalPO::getState, DataStateEnum.ENABLE.getCode())
                        .ne(UserReportNormalPO::getStatus, BpmTaskStatusEnum.CANCEL.getStatus())
                        .eq(UserReportNormalPO::getType, 0)
                        .orderByDesc(UserReportNormalPO::getCreateTime)
                );
                if (CollUtil.isNotEmpty(list)) {
                    List<String> collect = list.stream().filter(x -> !Objects.equals(x.getStatus(), BpmTaskStatusEnum.APPROVE.getStatus()))
                            .map(UserReportNormalPO::getId)
                            .collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        type = false;
                    }
                } else {
                    type = false;
                }
            }
            temp.setType(type);
        });
        return page;
    }

    @Override
    public String cancelUserReport(BpmProcessInstanceCancelParam cancelReqVO) {
        //准备取消该流程，需要远程调用接口
        UserReportPO userReportPO = this.baseMapper.selectById(cancelReqVO.getId());
        //判断是否有权限操作
        InstanceUtil.judgeUserPower(RequestUtil.getUserIndex(), userReportPO.getCreateBy());
        //取消流程
        bpmProcessFeignClient.cancelProcessInstanceByStartUser(cancelReqVO);
        //更新状态
        userReportPO.setStatus(BpmProcessInstanceStatusEnum.CANCEL.getStatus());
        this.updateById(userReportPO);
        return userReportPO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserStatus(String lineId, Integer userStatus) {
        SupervisionTempLineReport supervisionTempLineReport = supervisionTempLineReportMapper.selectById(lineId);
        if (Objects.nonNull(supervisionTempLineReport)) {
            String userId = supervisionTempLineReport.getUserId();
            UserReportPO userReportPO = this.baseMapper.selectById(userId);
            //如果目前的干扰源用户状态>userStatus则不修改，如果将干扰源用户状态改为3退运，则必须其下的监测点都退运才能修改
            if (userReportPO.getUserStatus() < userStatus) {
                if (userStatus == 3) {
                    List<SupervisionTempLineReport> supervisionTempLineReports = supervisionTempLineReportMapper.selectList(new QueryWrapper<SupervisionTempLineReport>().lambda().eq(SupervisionTempLineReport::getUserId, userId));
                    List<String> lineIds = supervisionTempLineReports.stream().map(SupervisionTempLineReport::getId).collect(Collectors.toList());
                    List<LineDetail> data = lineFeignClient.getLineDetail(lineIds).getData();
                    List<Integer> collect1 = data.stream().filter(temp -> !Objects.equals(temp.getId(), lineId))
                            .map(LineDetail::getRunFlag)
                            .filter(temp -> !Objects.equals(temp, 2))
                            .collect(Collectors.toList());
                    if (CollectionUtil.isEmpty(collect1)) {
                        userReportPO.setUserStatus(userStatus);
                    }
                } else {
                    userReportPO.setUserStatus(userStatus);

                }
            }
            this.updateById(userReportPO);
        }
    }

    @Override
    public Page<UserReportVO> getSensitiveUserPage(UserReportParam.UserReportQueryParam userReportQueryParam) {
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(userReportQueryParam.getOrgId()).getData();
        //此处仅查询敏感及重要用户
        userReportVOQueryWrapper.and(wrapper ->
                        wrapper.in("supervision_user_report.create_by", colleaguesIds)
                                .or()
                                .in("supervision_user_report.org_id", data)
                )
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_user_report.user_type", UserNatureEnum.SENSITIVE_USER.getCode())
                .in("supervision_user_report.status", Arrays.asList(FlowStatusEnum.AUDIT.getCode(), FlowStatusEnum.APPROVE.getCode()));
        if (Objects.nonNull(userReportQueryParam)) {
            if (StrUtil.isNotBlank(userReportQueryParam.getCity())) {
                //查询所有区域下的数据
                userReportVOQueryWrapper.in("supervision_user_report.city", userReportQueryParam.getCity());
            }
            if (Objects.nonNull(userReportQueryParam.getDataType())) {
                userReportVOQueryWrapper.eq("data_type", userReportQueryParam.getDataType());
            }
            userReportVOQueryWrapper.like(StringUtils.isNotBlank(userReportQueryParam.getProjectName()), "supervision_user_report.project_name", userReportQueryParam.getProjectName());

        }
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        Page<UserReportVO> userReportVOPage = this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
        List<UserReportVO> records = userReportVOPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            //将详细信息也查出
            for (UserReportVO record : records) {
                UserReportSensitivePO userReportSensitivePO = userReportSensitivePOService.getById(record.getId());
                record.setUserReportSensitivePO(userReportSensitivePO);
            }
        }
        return userReportVOPage;
    }

    @Override
    public void downloadSensitiveUserTemplate() {
        ExportParams exportParams = new ExportParams("敏感及重要用户数据模板（带*字段均是必填,请严格按照模板标准填入数据）", "敏感及重要用户数据信息");
        //所属地市
        List<DictData> jiBeiArea = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.JIBEI_AREA.getCode()).getData();
        //电压等级
        List<DictData> devVoltage = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()).getData();
        //评估单位
        List<DictData> evaluationDept;
        evaluationDept = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVALUATION_DEPT.getCode()).getData();
        //评估类型
        List<DictData> evaluationType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVALUATION_TYPE.getCode()).getData();
        //指标类型
        List<DictData> indicatorType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.PROBLEM_INDICATORS.getCode()).getData();
        //行业类型
        List<DictData> industryType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INDUSTRY_TYPE_JB.getCode()).getData();
        //负荷级别
        List<DictData> loadLevel = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LOAD_LEVEL.getCode()).getData();
        //供电电源情况
        List<DictData> supplyCondition = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SUPPLY_CONDITION.getCode()).getData();

        List<PullDown> pullDowns = new ArrayList<>();


        PullDown pullDown;
        pullDown = new PullDown();
        pullDown.setFirstCol(1);
        pullDown.setLastCol(1);
        pullDown.setStrings(jiBeiArea.stream().filter(x -> !"风光储".equals(x.getName()) && !"超高压".equals(x.getName())).map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(3);
        pullDown.setLastCol(3);
        pullDown.setStrings(Stream.of("可研", "建设", "运行", "退运").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(7);
        pullDown.setLastCol(7);
        pullDown.setIsText(true);
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(5);
        pullDown.setLastCol(5);
        pullDown.setStrings(loadLevel.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(6);
        pullDown.setLastCol(6);
        pullDown.setStrings(supplyCondition.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);


        pullDown = new PullDown();
        pullDown.setFirstCol(8);
        pullDown.setLastCol(8);
        pullDown.setStrings(devVoltage.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(9);
        pullDown.setLastCol(9);
        pullDown.setStrings(evaluationDept.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(12);
        pullDown.setLastCol(12);
        pullDown.setStrings(Stream.of("否", "是").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(13);
        pullDown.setLastCol(13);
        pullDown.setStrings(Stream.of("否", "是").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(14);
        pullDown.setLastCol(14);
        pullDown.setStrings(evaluationType.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(15);
        pullDown.setLastCol(15);
        pullDown.setStrings(industryType.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(18);
        pullDown.setLastCol(18);
        pullDown.setStrings(indicatorType.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(19);
        pullDown.setLastCol(19);
        pullDown.setStrings(Stream.of("否", "是").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(22);
        pullDown.setLastCol(22);
        pullDown.setStrings(devVoltage.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);
        ExcelUtil.exportExcelPullDown(exportParams, "敏感及重要用户模板.xlsx", pullDowns, SensitiveUserSExcel.class, new ArrayList<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSensitiveUserData(MultipartFile file, HttpServletResponse response) {
        boolean fileType = FileUtil.judgeFileIsExcel(file.getOriginalFilename());
        if (!fileType) {
            throw new BusinessException(CommonResponseEnum.FILE_XLSX_ERROR);
        }
        ImportParams params = new ImportParams();
        //表头
        params.setHeadRows(1);
        //标题
        params.setTitleRows(1);
        params.setNeedVerify(false);
        params.setStartSheetIndex(0);
        params.setReadRows(100);  // 最多读取100行数据
        params.setSheetNum(1);
        List<SensitiveUserSExcel> sensitiveUserExcels;
        try {
            List<SensitiveUserSExcel> sensitiveUserExcelExcelImportResult = ExcelImportUtil.importExcel(file.getInputStream(), SensitiveUserSExcel.class, params);
            sensitiveUserExcels = sensitiveUserExcelExcelImportResult.stream().filter(x -> StringUtils.isNotBlank(x.getCity())).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(sensitiveUserExcels)) {
                throw new BusinessException(SupervisionResponseEnum.IMPORT_DEV_DATA_ERROR);
            }
            //如果存在非法数据，将不合格的数据导出
//            if (sensitiveUserExcelExcelImportResult.isVerifyFail()) {
//                PoiUtil.exportFileByWorkbook(sensitiveUserExcelExcelImportResult.getFailWorkbook(), "非法用户数据.xlsx", response);
//            } else {
//                sensitiveUserExcels = sensitiveUserExcelExcelImportResult.getList();
//            }
        } catch (Exception e) {
            throw new BusinessException(SupervisionResponseEnum.IMPORT_SENSITIVE_USER_ERROR);
        }
        //电压等级
        List<DictData> devVoltage = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()).getData();
        //指标类型
        List<DictData> indicatorType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INDICATOR_TYPE.getCode()).getData();
        //问题指标
        List<DictData> problemIndicators = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.PROBLEM_INDICATORS.getCode()).getData();
        //评估类型
        List<DictData> evaluationType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVALUATION_TYPE.getCode()).getData();
        //行业类型
        List<DictData> industryType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INDUSTRY_TYPE_JB.getCode()).getData();
        //负荷级别
        List<DictData> loadLevel = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LOAD_LEVEL.getCode()).getData();
        //供电电源情况
        List<DictData> supplyCondition = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.SUPPLY_CONDITION.getCode()).getData();

        //解决填报部门问题
        List<DeptDTO> data = deptFeignClient.getDeptDescendantIndexes(RequestUtil.getDeptIndex(), WebUtil.filterDeptType()).getData();


        //执行批量导入敏感及重要用户，入库过程中会进行数据校验
        List<SensitiveUserSExcel.SensitiveUserExcelMsg> sensitiveUserExcelMsgs = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sensitiveUserExcels)) {
            for (SensitiveUserSExcel userExcel : sensitiveUserExcels) {
                //先判断当前用户是否已经存在
                LambdaQueryWrapper<UserReportPO> userReportPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userReportPOLambdaQueryWrapper.eq(UserReportPO::getProjectName, userExcel.getProjectName())
                        .eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
                int count = this.count(userReportPOLambdaQueryWrapper);
                if (count > 0) {
                    //该用户已经录入
                    SensitiveUserSExcel.SensitiveUserExcelMsg sensitiveUserExcelMsg = new SensitiveUserSExcel.SensitiveUserExcelMsg();
                    BeanUtils.copyProperties(userExcel, sensitiveUserExcelMsg);
                    sensitiveUserExcelMsg.setMsg("该用户已录入!");
                    sensitiveUserExcelMsgs.add(sensitiveUserExcelMsg);
                } else {
                    //处理通用信息
                    UserReportPO userReportPO = new UserReportPO();
                    userReportPO.setReporter(RequestUtil.getUserIndex());
                    userReportPO.setReportDate(LocalDate.now());
                    //解决导入部门问题
                    List<String> DeptIds = data.stream().filter(x -> x.getName().equals(userExcel.getCity())).map(DeptDTO::getId).collect(Collectors.toList());
                    userReportPO.setOrgId(CollUtil.isNotEmpty(DeptIds) ? DeptIds.get(0) : RequestUtil.getDeptIndex());

                    userReportPO.setExpectedProductionDate(DateUtil.parseDate(userExcel.getExpectedProductionDate()).toLocalDateTime().toLocalDate());
                    userReportPO.setUserType(UserNatureEnum.SENSITIVE_USER.getCode());
                    //所属地市
                    userReportPO.setCity(userExcel.getCity());
                    userReportPO.setResponsibleDepartment(userExcel.getResponsibleDepartment());
                    userReportPO.setUserStatus(userExcel.getUserStatus());
                    userReportPO.setSubstation(userExcel.getSubstation());
                    userReportPO.setVoltageLevel(PubUtil.getDicById(userExcel.getVoltageLevel(), devVoltage));
                    userReportPO.setProjectName(userExcel.getProjectName());
                    userReportPO.setEvaluationDept(userExcel.getEvaluationDept());
                    userReportPO.setEvaluationConclusion(userExcel.getEvaluationConclusion());
                    userReportPO.setDataType(1);
                    userReportPO.setStatus(BpmTaskStatusEnum.APPROVE.getStatus());
                    userReportPO.setState(DataStateEnum.ENABLE.getCode());
                    this.baseMapper.insert(userReportPO);
                    //处理敏感用户的信息
                    List<String> indexList = new ArrayList<>();
                    UserReportSensitivePO userReportSensitivePO = new UserReportSensitivePO();
                    userReportSensitivePO.setId(userReportPO.getId());
                    userReportSensitivePO.setPccPoint(userExcel.getPccPoint());
                    userReportSensitivePO.setDeviceName(userExcel.getDeviceName());
                    userReportSensitivePO.setPowerSupplyCount(userExcel.getPowerSupplyCount());
                    //处理多指标数据
//                    String[] indexArr = userExcel.getEnergyQualityIndex().split(",");
//                    for (String s : indexArr) {
//                        indexList.add(PubUtil.getDicById(s, problemIndicators));
//                    }
                    userReportSensitivePO.setEnergyQualityIndex(PubUtil.getDicById(userExcel.getEnergyQualityIndex(), problemIndicators));
                    userReportSensitivePO.setEvaluationType(PubUtil.getDicById(userExcel.getEvaluationType(), evaluationType));
                    userReportSensitivePO.setAntiInterferenceTest(userExcel.getAntiInterferenceTest() + "");
                    userReportSensitivePO.setEvaluationChekDept(userExcel.getEvaluationChekDept());
                    userReportSensitivePO.setNeedGovernance(userExcel.getNeedGovernance());
                    userReportSensitivePO.setBackgroundTestPerformed(userExcel.getBackgroundTestPerformed());
//                    userReportSensitivePO.setSubstationMainWiringDiagram();
//                    userReportSensitivePO.setSensitiveDevices();
//                    userReportSensitivePO.setAntiInterferenceReport();
//                    userReportSensitivePO.setPowerQualityReport();
//                    userReportSensitivePO.setFeasibilityReport();
//                    userReportSensitivePO.setPreliminaryDesignDescription();
//                    userReportSensitivePO.setPredictionEvaluationReport();
//                    userReportSensitivePO.setPredictionEvaluationReviewOpinions();
//                    userReportSensitivePO.setAdditionalAttachments();
                    if (StrUtil.isNotBlank(userExcel.getIndustry())) {
                        userReportSensitivePO.setIndustry(PubUtil.getDicById(userExcel.getIndustry(), industryType));
                    }
                    userReportSensitivePO.setMaintenanceUnit(userExcel.getMaintenanceUnit());
                    userReportSensitivePO.setPowerSupply(userExcel.getPowerSupply());
                    if (StrUtil.isNotBlank(userExcel.getSupplyVoltageLevel())) {
                        userReportSensitivePO.setSupplyVoltageLevel(PubUtil.getDicById(userExcel.getSupplyVoltageLevel(), devVoltage));
                    }
                    if (StrUtil.isNotBlank(userExcel.getLoadLevel())) {
                        userReportSensitivePO.setLoadLevel(PubUtil.getDicById(userExcel.getLoadLevel(), loadLevel));
                    }
                    if (StrUtil.isNotBlank(userExcel.getPowerSupplyInfo())) {
                        userReportSensitivePO.setPowerSupplyInfo(PubUtil.getDicById(userExcel.getPowerSupplyInfo(), supplyCondition));
                    }
                    userReportSensitivePO.setState(DataStateEnum.ENABLE.getCode());
                    userReportSensitivePOService.save(userReportSensitivePO);
                }
            }
        }
        //判断有没有错误信息
        if (CollectionUtil.isNotEmpty(sensitiveUserExcelMsgs)) {
            ExcelUtil.exportExcel("失败列表.xlsx", SensitiveUserSExcel.SensitiveUserExcelMsg.class, sensitiveUserExcelMsgs);
        }
    }

    @Override
    public void downloadSensitiveReportTemplate() {
        ExportParams exportParams = new ExportParams("干扰源用户数据模板（带*字段均是必填,请严格按照模板标准填入数据）", "干扰源用户数据信息");
        //所属地市
        List<DictData> jiBeiArea = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.JIBEI_AREA.getCode()).getData();
        //主要非线性设备类型-冀北
        List<SysDicTreePO> treeVOS = dictTreeFeignClient.queryByCodeList(DicDataTypeEnum.Major_Nonlinear_Device.getCode()).getData();
        //电压等级
        List<DictData> devVoltage = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()).getData();
        //评估单位
        List<DictData> evaluationDept = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVALUATION_DEPT.getCode()).getData();
        //评估类型
        List<DictData> evaluationType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVALUATION_TYPE.getCode()).getData();

        Map<String, String> treeString = getTreeString("", treeVOS.get(0).getChildren());

        List<PullDown> pullDowns = new ArrayList<>();
        PullDown pullDown;
        pullDown = new PullDown();
        pullDown.setFirstCol(1);
        pullDown.setLastCol(1);
        pullDown.setStrings(Stream.of("新建电网工程", "扩建电网工程", "新建非线性负荷用户", "扩建非线性负荷用户", "新建新能源发电站", "扩建新能源发电站").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(2);
        pullDown.setLastCol(2);
        pullDown.setStrings(jiBeiArea.stream().filter(x -> !"风光储".equals(x.getName()) && !"超高压".equals(x.getName())).map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(6);
        pullDown.setLastCol(6);
        pullDown.setIsText(true);
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(4);
        pullDown.setLastCol(4);
        pullDown.setStrings(Stream.of("可研", "建设", "运行", "退运").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(7);
        pullDown.setLastCol(7);
        pullDown.setStrings(devVoltage.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(8);
        pullDown.setLastCol(8);
        pullDown.setStrings(evaluationDept.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);


        pullDown = new PullDown();
        pullDown.setFirstCol(15);
        pullDown.setLastCol(15);
        pullDown.setStrings(evaluationType.stream().map(DictData::getName).collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(16);
        pullDown.setLastCol(16);
        pullDown.setStrings(new ArrayList<>(treeString.keySet()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(18);
        pullDown.setLastCol(18);
        pullDown.setStrings(Stream.of("否", "是").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        pullDown = new PullDown();
        pullDown.setFirstCol(19);
        pullDown.setLastCol(19);
        pullDown.setStrings(Stream.of("否", "是").collect(Collectors.toList()));
        pullDowns.add(pullDown);

        ExcelUtil.exportExcelPullDown(exportParams, "干扰源用户用户模板.xlsx", pullDowns, SensitiveReportExcel.class, new ArrayList<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSensitiveReportData(MultipartFile file, HttpServletResponse response) {
        boolean fileType = FileUtil.judgeFileIsExcel(file.getOriginalFilename());
        if (!fileType) {
            throw new BusinessException(CommonResponseEnum.FILE_XLSX_ERROR);
        }
        ImportParams params = new ImportParams();
        //表头
        params.setHeadRows(1);
        //标题
        params.setTitleRows(1);
        params.setNeedVerify(false);  // 关闭校验，避免校验导致的性能问题
        params.setStartSheetIndex(0);
        params.setReadRows(100);  // 最多读取100行数据
        params.setSheetNum(1);
        // 限制最大读取行数，防止Excel模板带下拉列表导致读取大量空行
        // 如果实际数据超过此限制，需要分批导入或调整此参数
        params.setReadRows(100);  // 最多读取100行数据
        List<SensitiveReportExcel> sensitiveUserExcels;
        try {
            log.info("开始解析 Excel，文件名：{}", file.getOriginalFilename());
            ExcelImportResult<SensitiveReportExcel> sensitiveUserExcelExcelImportResult = ExcelImportUtil.importExcelMore(file.getInputStream(), SensitiveReportExcel.class, params);
            log.info("Excel 解析完成，原始数据行数：{}", sensitiveUserExcelExcelImportResult.getList().size());
            //如果存在非法数据，将不合格的数据导出
//            if (sensitiveUserExcelExcelImportResult.isVerifyFail()) {
//                log.warn("存在校验失败的数据");
//                PoiUtil.exportFileByWorkbook(sensitiveUserExcelExcelImportResult.getFailWorkbook(), "非法用户数据.xlsx", response);
//                return;  // 校验失败直接返回
//            } else {
                // 过滤掉空行数据（projectName 为空的行）
                sensitiveUserExcels = sensitiveUserExcelExcelImportResult.getList().stream()
                        .filter(x -> StringUtils.isNotBlank(x.getProjectName()))
                        .collect(Collectors.toList());
                log.info("过滤后有效数据：{} 条", sensitiveUserExcels.size());

                if (CollectionUtil.isEmpty(sensitiveUserExcels)) {
                    throw new BusinessException(SupervisionResponseEnum.IMPORT_DEV_DATA_ERROR);
                }
//            }
        } catch (Exception e) {
            log.error("导入失败，文件：{}", file.getOriginalFilename(), e);
            throw new BusinessException(SupervisionResponseEnum.IMPORT_SENSITIVE_REPORT_ERROR);
        }
        //主要非线性设备类型-冀北
        List<SysDicTreePO> treeVOS = dictTreeFeignClient.queryByCodeList(DicDataTypeEnum.Major_Nonlinear_Device.getCode()).getData();
        //电压等级
        List<DictData> devVoltage = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE_STAND.getCode()).getData();
        Map<String, String> treeString = getTreeString("", treeVOS.get(0).getChildren());
        //评估类型
        List<DictData> evaluationType = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVALUATION_TYPE.getCode()).getData();
        //解决填报部门问题
        List<DeptDTO> data = deptFeignClient.getDeptDescendantIndexes(RequestUtil.getDeptIndex(), WebUtil.filterDeptType()).getData();

        //执行批量导入敏感及重要用户，入库过程中会进行数据校验
        List<SensitiveReportExcel.SensitiveReportExcelMsg> sensitiveUserExcelMsgs = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(sensitiveUserExcels)) {
            for (SensitiveReportExcel reportExcel : sensitiveUserExcels) {
                //先判断当前用户是否已经存在
                LambdaQueryWrapper<UserReportPO> userReportPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userReportPOLambdaQueryWrapper.eq(UserReportPO::getProjectName, reportExcel.getProjectName())
                        .eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
                int count = this.count(userReportPOLambdaQueryWrapper);
                if (count > 0) {
                    //该用户已经录入
                    SensitiveReportExcel.SensitiveReportExcelMsg sensitiveUserExcelMsg = new SensitiveReportExcel.SensitiveReportExcelMsg();
                    BeanUtils.copyProperties(reportExcel, sensitiveUserExcelMsg);
                    sensitiveUserExcelMsg.setMsg("该用户已录入!");
                    sensitiveUserExcelMsgs.add(sensitiveUserExcelMsg);
                } else {
                    //处理通用信息
                    UserReportPO userReportPO = new UserReportPO();
                    userReportPO.setReporter(RequestUtil.getUserIndex());
                    userReportPO.setReportDate(LocalDate.now());

                    //解决导入部门问题
                    List<String> DeptIds = data.stream().filter(x -> x.getName().equals(reportExcel.getCity())).map(DeptDTO::getId).collect(Collectors.toList());
                    userReportPO.setOrgId(CollUtil.isNotEmpty(DeptIds) ? DeptIds.get(0) : RequestUtil.getDeptIndex());

                    userReportPO.setExpectedProductionDate(DateUtil.parseDate(reportExcel.getExpectedProductionDate()).toLocalDateTime().toLocalDate());
                    userReportPO.setUserType(reportExcel.getUserType());
                    //所属地市
                    userReportPO.setCity(reportExcel.getCity());
                    userReportPO.setResponsibleDepartment(reportExcel.getResponsibleDepartment());
                    userReportPO.setUserStatus(reportExcel.getUserStatus());
                    userReportPO.setSubstation(reportExcel.getSubstation());
                    userReportPO.setVoltageLevel(PubUtil.getDicById(reportExcel.getVoltageLevel(), devVoltage));
                    userReportPO.setProjectName(reportExcel.getProjectName());
                    userReportPO.setEvaluationDept(reportExcel.getEvaluationDept());
                    userReportPO.setEvaluationConclusion(reportExcel.getEvaluationConclusion());
                    userReportPO.setDataType(1);
                    userReportPO.setStatus(BpmTaskStatusEnum.WAIT.getStatus());
                    userReportPO.setState(DataStateEnum.ENABLE.getCode());
                    this.baseMapper.insert(userReportPO);
                    if (CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_POWER_GRID.getCode(),
                            UserNatureEnum.EXTEND_POWER_GRID.getCode()
                    ).contains(userReportPO.getUserType())) {
                        //电网工程类用户额外数据
                        UserReportProjectPO userReportProjectPO = new UserReportProjectPO();
                        userReportProjectPO.setId(userReportPO.getId());
                        if (ObjectUtil.isNotEmpty(reportExcel.getNonlinearLoadType())) {
                            userReportProjectPO.setAgreementCapacity(reportExcel.getUserAgreementCapacity().doubleValue());
                        }
                        if (StrUtil.isNotBlank(reportExcel.getNonlinearLoadType())) {
                            userReportProjectPO.setNonlinearDeviceType(treeString.getOrDefault(reportExcel.getNonlinearLoadType(), null));
                        }

                        userReportProjectPO.setNeedGovernance(reportExcel.getNeedGovernance());
                        userReportProjectPO.setBackgroundTestPerformed(reportExcel.getBackgroundTestPerformed());
//                        userReportProjectPO.setFeasibilityReport();
//                        userReportProjectPO.setPreliminaryDesignDescription();
//                        userReportProjectPO.setPredictionEvaluationReport();
//                        userReportProjectPO.setPredictionEvaluationReviewOpinions();
//                        userReportProjectPO.setAdditionalAttachments();
                        userReportProjectPO.setState(DataStateEnum.ENABLE.getCode());
                        userReportProjectPOService.saveOrUpdate(userReportProjectPO);
                    }
                    if (CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                            UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                    ).contains(userReportPO.getUserType())) {
                        //非线性负荷用户 & 新能源发电站用户
                        UserReportSubstationPO userReportSubstationPO = new UserReportSubstationPO();
                        userReportSubstationPO.setId(userReportPO.getId());
                        userReportSubstationPO.setPccPoint(reportExcel.getPccPoint());
                        userReportSubstationPO.setBaseShortCircuitCapacity(reportExcel.getBaseShortCircuitCapacity());
                        userReportSubstationPO.setMinShortCircuitCapacity(reportExcel.getMinShortCircuitCapacity());
                        userReportSubstationPO.setPccEquipmentCapacity(reportExcel.getPccEquipmentCapacity());
                        userReportSubstationPO.setUserAgreementCapacity(reportExcel.getUserAgreementCapacity());
                        userReportSubstationPO.setEvaluationType(PubUtil.getDicById(reportExcel.getEvaluationType(), evaluationType));
                        if (StrUtil.isNotBlank(reportExcel.getNonlinearLoadType())) {
                            userReportSubstationPO.setNonlinearLoadType(treeString.containsKey(reportExcel.getNonlinearLoadType()) ? treeString.get(reportExcel.getNonlinearLoadType()) : null);
                        }
                        userReportSubstationPO.setEvaluationChekDept(reportExcel.getEvaluationChekDept());
                        userReportSubstationPO.setNeedGovernance(reportExcel.getNeedGovernance());
                        userReportSubstationPO.setBackgroundTestPerformed(reportExcel.getBackgroundTestPerformed());
//                        userReportSubstationPO.setSubstationMainWiringDiagram();
//                        userReportSubstationPO.setFeasibilityReport();
//                        userReportSubstationPO.setPreliminaryDesignDescription();
//                        userReportSubstationPO.setPredictionEvaluationReport();
//                        userReportSubstationPO.setPredictionEvaluationReviewOpinions();
//                        userReportSubstationPO.setAdditionalAttachments();
                        userReportSubstationPO.setState(DataStateEnum.ENABLE.getCode());
                        userReportSubstationPOService.saveOrUpdate(userReportSubstationPO);
                    }
                }
            }
        }
        //判断有没有错误信息
        if (CollectionUtil.isNotEmpty(sensitiveUserExcelMsgs)) {
            ExcelUtil.exportExcel("失败列表.xlsx", SensitiveReportExcel.SensitiveReportExcelMsg.class, sensitiveUserExcelMsgs);
        }
    }

    @Override
    public Boolean deleteUserReport(List<String> supervisionId) {
        List<UserReportPO> userReportPOS = this.listByIds(supervisionId);
        if (CollUtil.isEmpty(userReportPOS)) {
            throw new BusinessException(SupervisionResponseEnum.EXISTENCE_OR_NOT);
        }
        //判断是否有权限操作
        List<String> collect = userReportPOS.stream().map(UserReportPO::getCreateBy).distinct().collect(Collectors.toList());
        long count = userReportPOS.stream().filter(x -> !BpmTaskStatusEnum.WAIT.getStatus().equals(x.getStatus())).count();
        //判断是否有权限操作
        InstanceUtil.deleteRole(RequestUtil.getUserIndex(), collect, count);
        return this.update(new LambdaUpdateWrapper<UserReportPO>().set(UserReportPO::getState, DataStateEnum.DELETED.getCode())
                .in(UserReportPO::getId, supervisionId));
    }

    @Override
    public List<UserLedgerVO> selectUserList(UserReportParam userReportParam) {
        LambdaQueryWrapper<UserReportPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (StrUtil.isNotBlank(userReportParam.getCity())) {
            lambdaQueryWrapper.in(UserReportPO::getCity, Stream.of(userReportParam.getCity()).collect(Collectors.toList()));
        }
        if (StrUtil.isNotBlank(userReportParam.getStationId())) {
            lambdaQueryWrapper.eq(UserReportPO::getStationId, userReportParam.getStationId());
        }
        if (ObjectUtil.isNotNull(userReportParam.getUserType())) {
            lambdaQueryWrapper.eq(UserReportPO::getUserType, userReportParam.getUserType());
        }

        lambdaQueryWrapper.eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());

        List<UserReportPO> list = this.list(lambdaQueryWrapper);
        return BeanUtil.copyToList(list, UserLedgerVO.class);
    }

    @Override
    public UserLedgerVO selectUserInfo(String id) {
        LambdaQueryWrapper<UserReportPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserReportPO::getId, id).eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
        UserReportPO userReportPO = this.getById(id);
        if (Objects.nonNull(userReportPO)) {
            return BeanUtil.copyProperties(userReportPO, UserLedgerVO.class);
        }
        return null;
    }

    @Override
    public Boolean bindUserStation(String userId, String stationId) {
        UserReportPO userReportPO = new UserReportPO();
        userReportPO.setId(userId);
        userReportPO.setStationId(stationId);
        return this.updateById(userReportPO);
    }

    @Override
    public Page<UserReportVO> getUserLedgerPage(UserReportParam.UserReportQueryParam userReportQueryParam) {
        //正则校验
        Pattern pattern = Pattern.compile(PatternRegex.ALL_CHAR_1_20);
        Matcher matcher = pattern.matcher(userReportQueryParam.getProjectName());
        if (StringUtils.isNotBlank(userReportQueryParam.getProjectName()) && !matcher.matches()) {
            throw new BusinessException(ValidMessage.SEARCH_DATA_ERROR);
        }
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();

        //此处仅查询敏感及重要用户
        userReportVOQueryWrapper
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode());

        if (Objects.nonNull(userReportQueryParam)) {
            if (StrUtil.isNotBlank(userReportQueryParam.getCity())) {
                //查询所有区域下的数据
                userReportVOQueryWrapper.in("supervision_user_report.city", userReportQueryParam.getCity());
            }
            if (Objects.nonNull(userReportQueryParam.getDataType())) {
                userReportVOQueryWrapper.eq("data_type", userReportQueryParam.getDataType());
            }
            userReportVOQueryWrapper.like(StringUtils.isNotBlank(userReportQueryParam.getProjectName()), "supervision_user_report.project_name", userReportQueryParam.getProjectName());
            if (StrUtil.isNotBlank(userReportQueryParam.getSearchBeginTime()) && StrUtil.isNotBlank(userReportQueryParam.getSearchEndTime())) {
                userReportVOQueryWrapper.and(wrapper -> wrapper.between("supervision_user_report.report_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                        .or()
                        .between("supervision_user_report.expected_production_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                );
            }
            userReportVOQueryWrapper.orderByDesc("supervision_user_report.Update_Time");
        }
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        Page<UserReportVO> page;
        page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
        page.getRecords().forEach(temp -> {
            Integer needGovernance = 0;
            if (
                    CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_POWER_GRID.getCode(),
                            UserNatureEnum.EXTEND_POWER_GRID.getCode()
                    ).contains(temp.getUserType())) {
                //电网工程类用户额外数据
                needGovernance = userReportProjectPOService.getById(temp.getId()).getNeedGovernance();
            } else if (
                    CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                            UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                    ).contains(temp.getUserType())) {
                //非线性负荷用户 & 新能源发电站用户

                needGovernance = userReportSubstationPOService.getById(temp.getId()).getNeedGovernance();
            } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(temp.getUserType())) {
                // 敏感及重要用户
                needGovernance = userReportSensitivePOService.getById(temp.getId()).getNeedGovernance();
            }
            temp.setNeedGovernance(needGovernance);
            //添加治理评估文件，需先判断入网评估是否审核通过
            boolean type = true;
            if (1 == temp.getNeedGovernance()) {
                List<UserReportNormalPO> list = userReportNormalMapper.selectList(new LambdaQueryWrapper<UserReportNormalPO>()
                        .eq(UserReportNormalPO::getUserReportId, temp.getId())
                        .eq(UserReportNormalPO::getState, DataStateEnum.ENABLE.getCode())
                        .ne(UserReportNormalPO::getStatus, BpmTaskStatusEnum.CANCEL.getStatus())
                        .eq(UserReportNormalPO::getType, 0)
                        .orderByDesc(UserReportNormalPO::getCreateTime)
                );
                if (CollUtil.isNotEmpty(list)) {
                    List<String> collect = list.stream().filter(x -> !Objects.equals(x.getStatus(), BpmTaskStatusEnum.APPROVE.getStatus()))
                            .map(UserReportNormalPO::getId)
                            .collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        type = false;
                    }
                } else {
                    type = false;
                }
            }
            temp.setType(type);
        });
        return page;
    }

    @Override
    public List<UserReportPO> getSensitiveUserByDept(SensitiveUserParam param) {
        QueryWrapper<UserReportPO> userReportVOQueryWrapper = new QueryWrapper<>();
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(param.getDeptId()).getData();
        //此处仅查询敏感及重要用户
        userReportVOQueryWrapper.and(wrapper ->
                        wrapper.in("supervision_user_report.org_id", data)
                )
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_user_report.user_type", UserNatureEnum.SENSITIVE_USER.getCode())
                .in("supervision_user_report.status", Arrays.asList(FlowStatusEnum.AUDIT.getCode(), FlowStatusEnum.APPROVE.getCode()));
        userReportVOQueryWrapper.like(StringUtils.isNotBlank(param.getProjectName()), "supervision_user_report.project_name", param.getProjectName());
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        return this.baseMapper.selectList(userReportVOQueryWrapper);
    }

    @Override
    public Boolean bindAssessmentId(String userReportId, String assessMentId) {
        if (StrUtil.isBlank(assessMentId)||"null".equals(assessMentId)) {
            assessMentId = null;
        }
        return this.update(new LambdaUpdateWrapper<UserReportPO>()
                .set(UserReportPO::getSecondAssessmentId, assessMentId)
                .eq(UserReportPO::getId, userReportId));
    }

    @Override
    public List<UserLedgerVO.AssessMent> selectUserAssessMentList(UserReportParam userReportParam) {
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(userReportParam.getOrgId()).getData();
        LambdaQueryWrapper<UserReportPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(UserReportPO::getOrgId, data);
        lambdaQueryWrapper.and(x -> x.isNull(UserReportPO::getSecondAssessmentId)
                .or()
                .eq(UserReportPO::getSecondAssessmentId, userReportParam.getSecondAssessmentId()));
        lambdaQueryWrapper.eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
        return BeanUtil.copyToList(this.list(lambdaQueryWrapper), UserLedgerVO.AssessMent.class);
    }

    public Map<String, String> getTreeString(String name, List<SysDicTreePO> treeVOS) {
        Map<String, String> info = new LinkedHashMap<>();
        for (SysDicTreePO sysMenuDtoChild : treeVOS) {
            if (sysMenuDtoChild.getLevel() == 3) {
                name = sysMenuDtoChild.getId() + "-" + sysMenuDtoChild.getName();
            }
            if (CollUtil.isNotEmpty(sysMenuDtoChild.getChildren())) {
                info.putAll(getTreeString(name, sysMenuDtoChild.getChildren()));
            } else {
                info.put(name.split("-")[1], name.split("-")[0]);
            }
        }
        return info;
    }

    /**
     * 获取所有字段为null的属性名
     */
    public String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);

    }

    /**
     * 判断工程名称是否重复，如果重复则提示用户XXX已经创建该工程
     *
     * @param userReportParam 用户申请数据
     * @param isExcludeSelf   是否排除自己，一般新增不排除，更新时需要排除自己
     */
    protected void checkProjectName(UserReportParam userReportParam, boolean isExcludeSelf) {
        if (!StringUtils.isEmpty(userReportParam.getProjectName())) {
            LambdaQueryWrapper<UserReportPO> userReportPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userReportPOLambdaQueryWrapper
                    .eq(UserReportPO::getProjectName, userReportParam.getProjectName())
                    .in(UserReportPO::getStatus, CollectionUtil.newArrayList(BpmProcessInstanceStatusEnum.AWAIT.getStatus(), BpmProcessInstanceStatusEnum.RUNNING.getStatus(), BpmProcessInstanceStatusEnum.APPROVE.getStatus()))
                    .eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
            //更新的时候，需排除当前记录
            if (isExcludeSelf) {
                if (userReportParam instanceof UserReportParam.UserReportUpdate) {
                    userReportPOLambdaQueryWrapper.ne(UserReportPO::getId, ((UserReportParam.UserReportUpdate) userReportParam).getId());
                } else {
                    userReportPOLambdaQueryWrapper.ne(UserReportPO::getId, (userReportParam).getId());
                }
            }
            List<UserReportPO> userReportPOList = this.baseMapper.selectList(userReportPOLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(userReportPOList)) {
                //过滤已取消的申请
                userReportPOList = userReportPOList.stream()
                        .filter(userReportPO -> !userReportPO.getStatus().equals(FlowStatusEnum.CANCEL.getCode()))
                        .collect(Collectors.toList());
                //如果还存在，则说明有人申请过了
                if (CollectionUtil.isNotEmpty(userReportPOList)) {
                    UserVO userVO = userFeignClient.getUserById(userReportPOList.get(0).getReporter()).getData();
                    throw new BusinessException(userReportParam.getProjectName().concat(",该工程已被:").concat(userVO.getName()).concat("申请"));
                }
            }
        }

    }


}
