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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
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.core.toolkit.StringUtils;
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.bpm.pojo.vo.TodoVO;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.common.DealStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.harmonic.pojo.dto.RMpPartHarmonicDetailDTO;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.supervision.enums.*;
import com.njcn.supervision.mapper.leaflet.WarningLeafletMapper;
import com.njcn.supervision.pojo.param.leaflet.WarningLeafletParam;
import com.njcn.supervision.pojo.po.device.TempLineRunTestWarning;
import com.njcn.supervision.pojo.po.leaflet.WarningLeaflet;
import com.njcn.supervision.pojo.po.problem.SupervisionUserComplaintPO;
import com.njcn.supervision.pojo.po.survey.SurveyTest;
import com.njcn.supervision.pojo.vo.leaflet.WarningLeafletVO;
import com.njcn.supervision.service.device.TempLineRunTestWarningService;
import com.njcn.supervision.service.leaflet.IWarningLeafletService;
import com.njcn.supervision.service.problem.SupervisionUserComplaintPOService;
import com.njcn.supervision.service.survey.ISurveyTestService;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.vo.UserVO;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 预告警单表 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2024-05-21
 */
@Service
public class WarningLeafletServiceImpl extends ServiceImpl<WarningLeafletMapper, WarningLeaflet> implements IWarningLeafletService {
    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private DicDataFeignClient dicDataFeignClient;
    @Resource
    private BpmProcessFeignClient bpmProcessFeignClient;

    @Resource
    private DeptFeignClient deptFeignClient;

    @Resource
    private FileStorageUtil fileStorageUtil;

    @Resource
    private TempLineRunTestWarningService lineRunTestWarningService;

    @Resource
    private ISurveyTestService surveyTestService;

    @Resource
    private SupervisionUserComplaintPOService supervisionUserComplaintService;


    /**
     * 不创建工作流，只是创建一个告警单，需要待用户反馈后才会进入流程
     */
    @Override
    public String createLeaflet(String name, String deptId, String code, String id, Integer problemType, Integer leaflet, String issueDetail, String reformAdvice, String filePath) {
        WarningLeaflet one = this.lambdaQuery().eq(WarningLeaflet::getProblemId, id).one();
        if (Objects.isNull(one)) {
            WarningLeaflet warningLeaflet = new WarningLeaflet();
            warningLeaflet.setLeafletName(name);
            warningLeaflet.setDeptId(deptId);
            warningLeaflet.setLeafletNo(code);
            warningLeaflet.setProblemType(problemType);
            warningLeaflet.setProblemId(id);
            warningLeaflet.setLeafletType(leaflet);
            warningLeaflet.setIssueDetail(issueDetail);
            //新增字段整改意见
            warningLeaflet.setReformAdvice(reformAdvice);
            warningLeaflet.setState(DataStateEnum.ENABLE.getCode());
            warningLeaflet.setStatus(FlowStatusEnum.NO_FEEDBACK.getCode());
            warningLeaflet.setDealState(DealStateEnum.UNSOLVED.getCode());
            warningLeaflet.setFilePath(filePath);
            this.baseMapper.insert(warningLeaflet);
            return warningLeaflet.getId();
        } else {
            //新增字段整改意见
            one.setReformAdvice(reformAdvice);
            one.setDealState(DealStateEnum.UNSOLVED.getCode());
            one.setCreateTime(LocalDateTime.now());
            this.updateById(one);
            return one.getId();
        }


    }

    @Override
    public Page<WarningLeafletVO> warningPageData(WarningLeafletParam.WarningLeafletQueryParam warningLeafletQueryParam) {
        QueryWrapper<WarningLeafletVO> warningLeafletVOQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(warningLeafletQueryParam)) {
            if (Objects.nonNull(warningLeafletQueryParam.getSearchBeginTime()) && Objects.nonNull(warningLeafletQueryParam.getSearchEndTime())) {
                //添加上时间范围
                warningLeafletVOQueryWrapper.between("supervision_warning_leaflet.Create_Time",
                        DateUtil.beginOfDay(DateUtil.parse(warningLeafletQueryParam.getSearchBeginTime())),
                        DateUtil.endOfDay(DateUtil.parse(warningLeafletQueryParam.getSearchEndTime())));
            }
        }

        //筛选负责单位
        if (StrUtil.isNotBlank(warningLeafletQueryParam.getDeptIndex())) {
            List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(warningLeafletQueryParam.getDeptIndex()).getData();
            warningLeafletVOQueryWrapper.in("supervision_warning_leaflet.dept_id", deptIds);
        }
        warningLeafletVOQueryWrapper
                .eq("supervision_warning_leaflet.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_warning_leaflet.leaflet_type", LeafletTypeEnum.WARNING.getCode())
                .orderByDesc("supervision_warning_leaflet.Update_Time");
        Page<WarningLeafletVO> warningLeafletVOPage = this.baseMapper.warningPageData(new Page<>(PageFactory.getPageNum(warningLeafletQueryParam), PageFactory.getPageSize(warningLeafletQueryParam)), warningLeafletVOQueryWrapper);
        extracted(warningLeafletVOPage);
        return warningLeafletVOPage;
    }

    private void extracted(Page<WarningLeafletVO> warningLeafletVOPage) {
        if (CollUtil.isNotEmpty(warningLeafletVOPage.getRecords())) {
            List<String> deptIds = warningLeafletVOPage.getRecords().stream().distinct().map(WarningLeafletVO::getDutyOrgId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(deptIds)) {
                List<Dept> data = deptFeignClient.getDeptInfoListByIds(deptIds).getData();
                Map<String, String> deptMap = data.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
                warningLeafletVOPage.getRecords().forEach(x -> {
                    if (deptMap.containsKey(x.getDutyOrgId())) {
                        x.setDutyOrgName(deptMap.get(x.getDutyOrgId()));
                    }
                    if (!Objects.isNull(x.getFilePath())) {
                        x.setAbsFilePath(x.getFilePath());
                        x.setFilePath(fileStorageUtil.getFileUrl(x.getFilePath()));

                    }
                });
            }
        }

    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addFeedback(WarningLeafletParam.WarningLeafletUpdateParam warningLeafletUpdateParam) {
        WarningLeaflet warningLeaflet = this.baseMapper.selectById(warningLeafletUpdateParam.getId());
        warningLeaflet.setTakeStep(warningLeafletUpdateParam.getTakeStep());
        warningLeaflet.setReportPath(warningLeafletUpdateParam.getReportPath());
        //设置状态
        if (Objects.equals(warningLeafletUpdateParam.getSaveOrCheckflag(), "1")) {
            warningLeaflet.setStatus(BpmTaskStatusEnum.WAIT.getStatus());

        } else {
            warningLeaflet.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());

        }
        if (Objects.equals(warningLeafletUpdateParam.getSaveOrCheckflag(), "2")) {
            // 发起 BPM 流程
            Map<String, Object> processInstanceVariables = new HashMap<>(16);
            BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
            bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.WARN_LEAFLET.getKey());
            bpmProcessInstanceCreateReqDTO.setBusinessKey(warningLeaflet.getId());
            bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(warningLeafletUpdateParam.getStartUserSelectAssignees());
            bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
            String processInstanceId = bpmProcessFeignClient.createProcessInstance(RequestUtil.getUserIndex(), bpmProcessInstanceCreateReqDTO).getData();
            // 将工作流的编号，更新到流程单中
            warningLeaflet.setProcessInstanceId(processInstanceId);
        }
        warningLeaflet.setCreateBy(RequestUtil.getUserIndex());
        this.baseMapper.updateById(warningLeaflet);
    }

    @Override
    public String updateFeedback(WarningLeafletParam.WarningLeafletUpdateParam warningLeafletUpdateParam) {
        WarningLeaflet warningLeaflet = this.baseMapper.selectById(warningLeafletUpdateParam.getId());
        //判断是否有权限操作
        InstanceUtil.judgeUserPower(RequestUtil.getUserIndex(), warningLeaflet.getCreateBy());

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


        BeanUtils.copyProperties(warningLeafletUpdateParam, warningLeaflet);
        warningLeaflet.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        warningLeaflet.setState(DataStateEnum.ENABLE.getCode());

        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.WARN_LEAFLET.getKey());
        bpmProcessInstanceCreateReqDTO.setBusinessKey(warningLeaflet.getId());
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(warningLeafletUpdateParam.getStartUserSelectAssignees());
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(warningLeaflet.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        warningLeaflet.setProcessInstanceId(processInstanceId);
        //保存历史流程id列表
        warningLeaflet.setHistoryInstanceId(historyInstanceIds);
        warningLeaflet.setCreateBy(RequestUtil.getUserIndex());
        this.baseMapper.updateById(warningLeaflet);
        return warningLeaflet.getId();
    }

    @Override
    public WarningLeafletVO getVOById(String id) {
        WarningLeaflet warningLeaflet = this.getById(id);
        WarningLeafletVO warningLeafletVO = new WarningLeafletVO();
        if (!Objects.isNull(warningLeaflet)) {
            BeanUtil.copyProperties(warningLeaflet, warningLeafletVO);
            if (StrUtil.isNotBlank(warningLeaflet.getDeptId())) {
                Dept dept = deptFeignClient.getDeptById(warningLeaflet.getDeptId()).getData();
                if (Objects.nonNull(dept)) {
                    warningLeafletVO.setDeptName(dept.getName());
                }
            }
            if (warningLeaflet.getProblemType().equals(ProblemTypeEnum.SITE_TEST.getCode())) {
                String problemId = warningLeaflet.getProblemId();
                //查询谐波普测，获取该普测计划上传的文件
                //查询到现场测试超标附件地址
                TempLineRunTestWarning byId = lineRunTestWarningService.getById(problemId);
                if (Objects.nonNull(byId)) {
                    warningLeafletVO.setProblemPath(byId.getTestRunReport());
                }
            }
        }
        return warningLeafletVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcessStatus(String businessKey, Integer status) {
        this.lambdaUpdate().set(WarningLeaflet::getStatus, status).eq(WarningLeaflet::getId, businessKey).update();
        WarningLeaflet one = this.lambdaQuery().eq(WarningLeaflet::getId, businessKey).one();
        //如果审核通过且problem_type不是在线监测的（1：技术监督管理；2：在线监测超标问题；3：用户投诉；4：现场测试超标）,将对应能质量问题改成已解决，所有的预告警单改成已解决
        if (status == 2 ) {
            //多次的预告警单是删除
            this.lambdaUpdate().set(WarningLeaflet::getDealState, DealStateEnum.RESOLVED.getCode())
                    .eq(WarningLeaflet::getId, businessKey)
                    .eq(WarningLeaflet::getProblemId, one.getProblemId()).update();
            if(one.getProblemType() == 2){
                this.lambdaUpdate().set(WarningLeaflet::getDealState, DealStateEnum.RESOLVED.getCode())
                        .eq(WarningLeaflet::getId, businessKey)
                        .update();
            }
            if(one.getProblemType() != 2){
                updatePowerProblem(one.getProblemType(), one.getProblemId());
            }
        }
    }

    private void updatePowerProblem(Integer problemType, String problemId) {
        switch (problemType) {
            //技术监督计划
            case 1:
                surveyTestService.lambdaUpdate().set(SurveyTest::getDealState, DealStateEnum.RESOLVED.getCode())
                        .eq(SurveyTest::getId, problemId).update();
                break;
            //用户投诉问题
            case 3:
                supervisionUserComplaintService.lambdaUpdate().set(SupervisionUserComplaintPO::getDealState, DealStateEnum.RESOLVED.getCode())
                        .eq(SupervisionUserComplaintPO::getId, problemId).update();
                break;
            //试运行监测点问题
            case 4:
                lineRunTestWarningService.lambdaUpdate().set(TempLineRunTestWarning::getDealState, DealStateEnum.RESOLVED.getCode())
                        .eq(TempLineRunTestWarning::getId, problemId).update();
                break;
            default:
                break;
        }
    }


    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        BpmInstanceInfo bpmInstanceInfo = new BpmInstanceInfo();
        WarningLeafletVO warningLeafletVO = this.getVOById(businessId);
        if (Objects.nonNull(warningLeafletVO.getId())) {
            bpmInstanceInfo.setHistoryInstanceId(warningLeafletVO.getHistoryInstanceId());
            String type = "告警单";
            if (warningLeafletVO.getLeafletType() == 1) {
                type = "预警单";
            }
            String sign = "问题来源于".concat(ProblemTypeEnum.getNameByCode(warningLeafletVO.getProblemType()))
                    .concat(",由单位")
                    .concat(StrUtil.isBlank(warningLeafletVO.getDeptName()) ? "" : warningLeafletVO.getDeptName())
                    .concat("负责的")
                    .concat(warningLeafletVO.getLeafletName())
                    .concat(type);
            bpmInstanceInfo.setInstanceSign(sign);
            return bpmInstanceInfo;
        }
        return null;
    }

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

    @Override
    public Page<WarningLeafletVO> alarmPageData(WarningLeafletParam.WarningLeafletQueryParam warningLeafletQueryParam) {
        QueryWrapper<WarningLeafletVO> warningLeafletVOQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(warningLeafletQueryParam)) {
            if (Objects.nonNull(warningLeafletQueryParam.getSearchBeginTime()) && Objects.nonNull(warningLeafletQueryParam.getSearchEndTime())) {
                //添加上时间范围
                warningLeafletVOQueryWrapper.between("supervision_warning_leaflet.Create_Time",
                        DateUtil.beginOfDay(DateUtil.parse(warningLeafletQueryParam.getSearchBeginTime())),
                        DateUtil.endOfDay(DateUtil.parse(warningLeafletQueryParam.getSearchEndTime())));
            }
        }
        warningLeafletVOQueryWrapper
                .and(w -> w.in("supervision_warning_leaflet.status", Arrays.asList(BpmTaskStatusEnum.RUNNING.getStatus(),
                                        BpmTaskStatusEnum.APPROVE.getStatus(),
                                        BpmTaskStatusEnum.RETURN.getStatus()
                                ))
                                .or()
                                .eq("supervision_warning_leaflet.dept_id", RequestUtil.getDeptIndex())
                );
        //筛选负责单位
        if (StrUtil.isNotBlank(warningLeafletQueryParam.getDeptIndex())) {
            List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(warningLeafletQueryParam.getDeptIndex()).getData();
            warningLeafletVOQueryWrapper.in("supervision_warning_leaflet.dept_id", deptIds);
        }
        warningLeafletVOQueryWrapper
                .eq("supervision_warning_leaflet.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_warning_leaflet.leaflet_type", LeafletTypeEnum.ALARM.getCode())
                .eq(StringUtils.equals(warningLeafletQueryParam.getDealState(), "0"), "supervision_warning_leaflet.deal_state", 0)
                .eq(Objects.nonNull(warningLeafletQueryParam.getStatus()), "supervision_warning_leaflet.status", warningLeafletQueryParam.getStatus())
                .orderByDesc("supervision_warning_leaflet.Update_Time");
        Page<WarningLeafletVO> warningLeafletVOPage = this.baseMapper.alarmPageData(new Page<>(PageFactory.getPageNum(warningLeafletQueryParam), PageFactory.getPageSize(warningLeafletQueryParam)), warningLeafletVOQueryWrapper);
        //目前仅知道现场测试超标会有附件
        List<WarningLeafletVO> records = warningLeafletVOPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<String> deptIds = records.stream().distinct().map(WarningLeafletVO::getDutyOrgId).collect(Collectors.toList());
            Map<String, String> deptMap = new HashMap<>(16);
            if (CollUtil.isNotEmpty(deptIds)) {
                List<Dept> data = deptFeignClient.getDeptInfoListByIds(deptIds).getData();
                deptMap.putAll(data.stream().collect(Collectors.toMap(Dept::getId, Dept::getName)));
            }
            for (WarningLeafletVO record : records) {
                if (record.getProblemType().equals(ProblemTypeEnum.SITE_TEST.getCode()) && StrUtil.isNotBlank(record.getProblemId())) {
                    //查询到现场测试超标附件地址
                    TempLineRunTestWarning byId = lineRunTestWarningService.getById(record.getProblemId());
                    if (Objects.nonNull(byId)) {
                        record.setProblemPath(byId.getTestRunReport());
                    }
                }
                if (deptMap.containsKey(record.getDutyOrgId())) {
                    record.setDutyOrgName(deptMap.get(record.getDutyOrgId()));
                }
                if (!Objects.isNull(record.getFilePath())) {
                    record.setAbsFilePath(record.getFilePath());

                    record.setFilePath(fileStorageUtil.getFileUrl(record.getFilePath()));
                }
            }
        }
        return warningLeafletVOPage;
    }

    @Override
    public String addLineOverLimitData(RMpPartHarmonicDetailDTO rMpPartHarmonicDetailDTO) {
//        //组装预警告警信息
//        String info = assembleOverLimitInfo(rMpPartHarmonicDetailDTO);
//        //检查是否存在该预警单
//        List<WarningLeaflet> list = this.lambdaQuery().eq(WarningLeaflet::getIssueDetail, info).list();
//        if(CollectionUtil.isNotEmpty(list)){
//            throw new BusinessException("该预/告警单已发布");
//        }
//        this.createLeaflet(
//                rMpPartHarmonicDetailDTO.getMeasurementPointName(),
//                IdWorker.get32UUID(),
//                rMpPartHarmonicDetailDTO.getMeasurementPointId(),
//                ProblemTypeEnum.ONLINE.getCode(),
//                Objects.equals(rMpPartHarmonicDetailDTO.getAlarmFlag(),1) ? LeafletTypeEnum.ALARM.getCode(): LeafletTypeEnum.WARNING.getCode(),
//                assembleOverLimitInfo(rMpPartHarmonicDetailDTO)
//        );

        return null;
    }

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

    @Override
    public Page<WarningLeafletVO> allPageData(WarningLeafletParam.WarningLeafletQueryParam warningLeafletQueryParam) {
        QueryWrapper<WarningLeafletVO> warningLeafletVOQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(warningLeafletQueryParam)) {
            //添加上时间范围
            warningLeafletVOQueryWrapper.between("supervision_warning_leaflet.Create_Time",
                    DateUtil.beginOfDay(DateUtil.parse(warningLeafletQueryParam.getSearchBeginTime())),
                    DateUtil.endOfDay(DateUtil.parse(warningLeafletQueryParam.getSearchEndTime())));
        }

        //筛选负责单位
        if (StrUtil.isNotBlank(warningLeafletQueryParam.getDeptIndex())) {
            List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(warningLeafletQueryParam.getDeptIndex()).getData();
            warningLeafletVOQueryWrapper.in("supervision_warning_leaflet.dept_id", deptIds);
        }
        warningLeafletVOQueryWrapper
                .eq("supervision_warning_leaflet.state", DataStateEnum.ENABLE.getCode())
                .ne("supervision_warning_leaflet.status", 2)
                .orderByDesc("supervision_warning_leaflet.Update_Time");
        Page<WarningLeafletVO> warningLeafletVOPage = this.baseMapper.alarmPageData(new Page<>(PageFactory.getPageNum(warningLeafletQueryParam), PageFactory.getPageSize(warningLeafletQueryParam)), warningLeafletVOQueryWrapper);
        //目前仅知道现场测试超标会有附件
        List<WarningLeafletVO> records = warningLeafletVOPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<String> deptIds = records.stream().distinct().map(WarningLeafletVO::getDutyOrgId).collect(Collectors.toList());
            Map<String, String> deptMap = new HashMap<>(16);
            if (CollUtil.isNotEmpty(deptIds)) {
                List<Dept> data = deptFeignClient.getDeptInfoListByIds(deptIds).getData();
                deptMap.putAll(data.stream().collect(Collectors.toMap(Dept::getId, Dept::getName)));
            }
            for (WarningLeafletVO record : records) {
                if (record.getProblemType().equals(ProblemTypeEnum.SITE_TEST.getCode()) && StrUtil.isNotBlank(record.getProblemId())) {
                    //查询到现场测试超标附件地址
                    TempLineRunTestWarning byId = lineRunTestWarningService.getById(record.getProblemId());
                    if (Objects.nonNull(byId)) {
                        record.setProblemPath(byId.getTestRunReport());
                    }
                }
                if (deptMap.containsKey(record.getDutyOrgId())) {
                    record.setDutyOrgName(deptMap.get(record.getDutyOrgId()));
                }
                if (!Objects.isNull(record.getFilePath())) {
                    record.setFilePath(fileStorageUtil.getFileUrl(record.getFilePath()));
                }
            }
        }
        return warningLeafletVOPage;
    }

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

    @Override
    public List<TodoVO> getTodoBusiness() {
        List<TodoVO> todoVOList = new ArrayList<>();
        //如果用户为管理员则不查
        UserVO userVO = userFeignClient.getUserById(RequestUtil.getUserIndex()).getData();
        if (Objects.nonNull(userVO) && userVO.getType() == 1) {
            return todoVOList;
        }
        QueryWrapper<WarningLeafletVO> queryWrapper = new QueryWrapper<>();
        List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(RequestUtil.getDeptIndex()).getData();
        if (CollectionUtil.isEmpty(deptIds)) {
            return todoVOList;
        }
        queryWrapper.in("supervision_warning_leaflet.dept_id", deptIds)
                .eq("supervision_warning_leaflet.status", 5)
                .eq("supervision_warning_leaflet.state", DataStateEnum.ENABLE.getCode())
                .orderByDesc("supervision_warning_leaflet.Update_Time");
        List<WarningLeafletVO> warningLeafletVOList = this.baseMapper.getTodoBusiness(queryWrapper);
        if (CollectionUtil.isNotEmpty(warningLeafletVOList)) {
            todoVOList = warningLeafletVOList.stream().map(item -> {
                TodoVO todoVO = new TodoVO();
                String title = "预警单";
                int tabValue = 3;
                if (item.getLeafletType() == 2) {
                    title = "告警单";
                    tabValue = 4;
                }
                todoVO.setTaskName(title);
                String problemType = ProblemTypeEnum.getNameByCode(item.getProblemType());
                todoVO.setTaskContent(item.getLeafletName());
                todoVO.setStartUser(problemType);
                todoVO.setId(item.getId());
                todoVO.setTaskCreateTime(item.getCreateTime());
                todoVO.setSource(3);
                todoVO.setRoutePath("supervision/supervision/manage");
                todoVO.setTabValue(tabValue);
                return todoVO;
            }).collect(Collectors.toList());
        }
        return todoVOList;
    }


    private String assembleOverLimitInfo(RMpPartHarmonicDetailDTO rMpPartHarmonicDetailDTO) {
        String info;
        String leafletType = Objects.equals(rMpPartHarmonicDetailDTO.getAlarmFlag(), 1) ? "告警单" : "预警单";
        /*获取稳态统计指标*/
        List<DictData> steadyStatis = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INDICATOR_TYPE.getCode()).getData();
        List<String> harmonicTypes = steadyStatis.stream().filter(temp -> rMpPartHarmonicDetailDTO.getHarmonicTypes().contains(temp.getId())).map(DictData::getName).collect(Collectors.toList());

        info = "预警/告警单类型：" + "监测点超标" + leafletType + "    " +
                "预警/告警单生成时间：" + LocalDateTimeUtil.format(LocalDate.now(), DatePattern.CHINESE_DATE_PATTERN) + "\n" +
                "超标电站名称：" + rMpPartHarmonicDetailDTO.getSustationName() + "    " + "超标母线名称：" + rMpPartHarmonicDetailDTO.getBarName() + "    " + "超标监测点名称：" + rMpPartHarmonicDetailDTO.getMeasurementPointName() + "\n" +
                "统计超标指标：" + String.join(",", harmonicTypes) + "\n" +
                "当月累计超标天数：" + rMpPartHarmonicDetailDTO.getOverLimitDay() + "天" + "    " + "当月累计连续天数：" + rMpPartHarmonicDetailDTO.getOverLimitContinuous() + "天" + "\n" +
                "超标天数详情：" + rMpPartHarmonicDetailDTO.getDateList();
        log.warn(info);

        return info;
    }
}
