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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.StrPool;
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.core.toolkit.IdWorker;
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.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.dto.PollutionSubstationDTO;
import com.njcn.supervision.enums.*;
import com.njcn.supervision.mapper.survey.SurveyTestMapper;
import com.njcn.supervision.pojo.param.leaflet.WarningAddParam;
import com.njcn.supervision.pojo.param.survey.SurveyTestParam;
import com.njcn.supervision.pojo.po.leaflet.WarningLeaflet;
import com.njcn.supervision.pojo.po.survey.SurveyPlan;
import com.njcn.supervision.pojo.po.survey.SurveyTest;
import com.njcn.supervision.pojo.vo.survey.SurveyTestVO;
import com.njcn.supervision.service.leaflet.IWarningLeafletService;
import com.njcn.supervision.service.survey.ISurveyPlanService;
import com.njcn.supervision.service.survey.ISurveyTestService;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.vo.UserVO;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 普测测试的管理表 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2024-05-30
 */
@Service
public class SurveyTestServiceImpl extends ServiceImpl<SurveyTestMapper, SurveyTest> implements ISurveyTestService {

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private BpmProcessFeignClient bpmProcessFeignClient;

    @Resource
    private DeptFeignClient deptFeignClient;

    @Resource
    private LineFeignClient lineFeignClient;

    @Resource
    private ISurveyPlanService surveyPlanService;
    @Resource
    private IWarningLeafletService warningLeafletService;

    @Resource
    private DicDataFeignClient dicDataFeignClient;


    @Override
    public Page<SurveyTestVO> surveyTestPage(SurveyTestParam.SurveyTestQueryParam surveyTestQueryParam) {
        QueryWrapper<SurveyTestVO> surveyTestVOQueryWrapper = new QueryWrapper<>();
        List<String> deptIds =   new ArrayList<>();
        if (Objects.nonNull(surveyTestQueryParam)) {
            if (Objects.nonNull(surveyTestQueryParam.getSearchBeginTime()) && Objects.nonNull(surveyTestQueryParam.getSearchEndTime())) {
                //添加上时间范围
                surveyTestVOQueryWrapper.and(wrapper ->
                        wrapper.between("supervision_survey_plan.plan_start_time",
                                        DateUtil.beginOfDay(DateUtil.parse(surveyTestQueryParam.getSearchBeginTime())),
                                        DateUtil.endOfDay(DateUtil.parse(surveyTestQueryParam.getSearchEndTime())))
                                .or(x->
                                        //未完成的技术监督计划，也要展示出来，不受时间限制
                                        x.isNull("supervision_survey_test.complete_time")
                                                .le("supervision_survey_plan.plan_start_time", surveyTestQueryParam.getSearchBeginTime())
                                )
                                .or(x->
                                        x.between("supervision_survey_test.complete_time",
                                                DateUtil.beginOfDay(DateUtil.parse(surveyTestQueryParam.getSearchBeginTime())),
                                                DateUtil.endOfDay(DateUtil.parse(surveyTestQueryParam.getSearchEndTime())))
                                )
                );
            }
            //根据工程名称模糊搜索
            if (Objects.nonNull(surveyTestQueryParam.getSearchValue())) {
                LambdaQueryWrapper<SurveyPlan> surveyPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
                surveyPlanLambdaQueryWrapper.eq(SurveyPlan::getState, DataStateEnum.ENABLE.getCode())
                        .eq(StringUtils.isNotBlank(surveyTestQueryParam.getSupvType()), SurveyPlan::getSupvType, surveyTestQueryParam.getSupvType())
                        .like(SurveyPlan::getPlanName, surveyTestQueryParam.getSearchValue());
                List<SurveyPlan> surveyPlans = surveyPlanService.getBaseMapper().selectList(surveyPlanLambdaQueryWrapper);
                if (CollectionUtil.isNotEmpty(surveyPlans)) {
                    List<String> planIds = surveyPlans.stream().map(SurveyPlan::getId).collect(Collectors.toList());
                    surveyTestVOQueryWrapper.in("supervision_survey_test.plan_id", planIds);
                } else {
                    //没有匹配的。直接返回
                    return new Page<>();
                }
            }
        }//筛选普测负责单位
        if (StrUtil.isNotBlank(surveyTestQueryParam.getDeptIndex())) {
            deptIds = deptFeignClient.getDepSonIdtByDeptId(surveyTestQueryParam.getDeptIndex()).getData();
        }
        surveyTestVOQueryWrapper.in(CollUtil.isNotEmpty(deptIds), "supervision_survey_test.dept_id", deptIds);
        if (Objects.nonNull(surveyTestQueryParam.getStatus())) {
            surveyTestVOQueryWrapper.eq("supervision_survey_test.status", surveyTestQueryParam.getStatus());
        }
        surveyTestVOQueryWrapper.eq(StringUtils.isNotBlank(surveyTestQueryParam.getSupvType()),"supervision_survey_plan.supv_type",surveyTestQueryParam.getSupvType());
        surveyTestVOQueryWrapper
                .eq("supervision_survey_test.state", DataStateEnum.ENABLE.getCode())
                .orderByDesc("supervision_survey_test.Update_Time");
        Page<SurveyTestVO> surveyTestVOPage = this.baseMapper.surveyTestPage(new Page<>(PageFactory.getPageNum(surveyTestQueryParam), PageFactory.getPageSize(surveyTestQueryParam)), surveyTestVOQueryWrapper);
        List<SurveyTestVO> records = surveyTestVOPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            for (SurveyTestVO record : records) {
                //回显部门名称
                record.setDeptName(deptFeignClient.getDeptById(record.getDeptId()).getData().getName());
                //回显变电站名称
                if (record.getCustomSubstationFlag() == 0) {
                    //关联台账内的变电站名称
                    String substation = record.getSubstation();
                    if (StringUtils.isNotEmpty(substation)) {
                        PollutionSubstationDTO data = lineFeignClient.getSubstationInfo(substation).getData();
                        if(ObjectUtil.isNotNull(data)){
                            record.setSubstationName(data.getName());
                        }
                    }
                } else {
                    record.setSubstationName(record.getSubstation());
                }
            }
        }
        return surveyTestVOPage;
    }

    @Override
    public Page<SurveyTestVO> pageProblemSurvey(SurveyTestParam.SurveyTestQueryParam surveyTestQueryParam) {
        QueryWrapper<SurveyTestVO> surveyTestVOQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(surveyTestQueryParam)) {
            //如果不是只查询已处理的，时间无效
            if (Objects.nonNull(surveyTestQueryParam.getSearchBeginTime())&& StringUtils.equals(surveyTestQueryParam.getDealState(),"1")){
                //添加上时间范围
                surveyTestVOQueryWrapper.between("supervision_survey_test.Create_Time",
                        DateUtil.beginOfDay(DateUtil.parse(surveyTestQueryParam.getSearchBeginTime())),
                        DateUtil.endOfDay(DateUtil.parse(surveyTestQueryParam.getSearchEndTime())));
            }
            //根据工程名称模糊搜索
            if (StrUtil.isNotBlank(surveyTestQueryParam.getSearchValue())) {
                LambdaQueryWrapper<SurveyPlan> surveyPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
                surveyPlanLambdaQueryWrapper.eq(SurveyPlan::getState, DataStateEnum.ENABLE.getCode())
                        .like(SurveyPlan::getPlanName, surveyTestQueryParam.getSearchValue());
                List<SurveyPlan> surveyPlans = surveyPlanService.getBaseMapper().selectList(surveyPlanLambdaQueryWrapper);
                if (CollectionUtil.isNotEmpty(surveyPlans)) {
                    List<String> planIds = surveyPlans.stream().map(SurveyPlan::getId).collect(Collectors.toList());
                    surveyTestVOQueryWrapper.in("supervision_survey_test.plan_id", planIds);
                } else {
                    //没有匹配的。直接返回
                    return new Page<>();
                }
            }
            //筛选普测负责单位
            if (StrUtil.isNotBlank(surveyTestQueryParam.getDeptIndex())) {
                List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(surveyTestQueryParam.getDeptIndex()).getData();
                surveyTestVOQueryWrapper.in("supervision_survey_test.dept_id", deptIds);
            }
        }
        surveyTestVOQueryWrapper
                //未解决查未解决，已解决查未解决+已解决，反正未解决的都要查
                .eq(StringUtils.equals(surveyTestQueryParam.getDealState(),"0"),"supervision_survey_test.deal_state",0)
                .eq("supervision_survey_test.problem_flag", 1)
                .eq("supervision_survey_test.status", FlowStatusEnum.APPROVE.getCode())
                .eq("supervision_survey_test.state", DataStateEnum.ENABLE.getCode())
                .orderByDesc("supervision_survey_test.Update_Time");
        Page<SurveyTestVO> surveyTestVOPage = this.baseMapper.surveyTestPage(new Page<>(PageFactory.getPageNum(surveyTestQueryParam), PageFactory.getPageSize(surveyTestQueryParam)), surveyTestVOQueryWrapper);
        List<SurveyTestVO> records = surveyTestVOPage.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            for (SurveyTestVO record : records) {
                //回显部门名称
                record.setDeptName(deptFeignClient.getDeptById(record.getDeptId()).getData().getName());
                //回显变电站名称
                if (record.getCustomSubstationFlag() == 0) {
                    //关联台账内的变电站名称
                    String substation = record.getSubstation();
                    if(StringUtils.isNotEmpty(substation)){
                        record.setSubstationName(lineFeignClient.getSubstationInfo(substation).getData().getName());
                    }
                } else {
                    record.setSubstationName(record.getSubstation());
                }
            }
        }
        return surveyTestVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addSurveyTest(SurveyTestParam surveyTestParam) {
        SurveyTest surveyTest = this.getById(surveyTestParam.getId());
        //没有copy前端所有的字段，仅赋值了test表中需要的几个字段

        surveyTest.setCompleteTime(surveyTestParam.getCompleteTime());
        surveyTest.setCompleteBy(surveyTestParam.getCompleteBy());
        surveyTest.setTestReport(surveyTestParam.getTestReport());
        surveyTest.setSupervisionReport(surveyTestParam.getSupervisionReport());
        surveyTest.setProblemFlag(surveyTestParam.getProblemFlag());
        surveyTest.setProblemDetail(surveyTestParam.getProblemDetail());
        surveyTest.setOtherReport(surveyTestParam.getOtherReport());
        //设置状态
        if(Objects.equals(surveyTestParam.getSaveOrCheckflag(),"1")){
            surveyTest.setStatus(BpmTaskStatusEnum.WAIT.getStatus());

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

        }
        surveyTest.setState(DataStateEnum.ENABLE.getCode());
        surveyTest.setDealState(DealStateEnum.UNSOLVED.getCode());
        surveyTest.setCreateBy(RequestUtil.getUserIndex());
        this.updateById(surveyTest);
        // 发起 BPM 流程
        if(Objects.equals(surveyTestParam.getSaveOrCheckflag(),"2")) {
            Map<String, Object> processInstanceVariables = new HashMap<>(16);
            BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
            bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.SURVEY_TEST.getKey());
            bpmProcessInstanceCreateReqDTO.setBusinessKey(surveyTest.getId());
            bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(new HashMap<>(8));
            bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
            String processInstanceId = bpmProcessFeignClient.createProcessInstance(surveyTest.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
            // 将工作流的编号，更新到流程单中
            surveyTest.setProcessInstanceId(processInstanceId);
            this.baseMapper.updateById(surveyTest);
        }
        return surveyTest.getId();
    }

    @Override
    public String updateSurveyTest(SurveyTestParam.SurveyTestUpdateParam surveyTestUpdateParam) {
        SurveyTest surveyTest = this.baseMapper.selectById(surveyTestUpdateParam.getId());
        //判断是否有权限操作
        InstanceUtil.judgeUserDeptPower(RequestUtil.getDeptIndex(), surveyTest.getDeptId());
        surveyTestUpdateParam.setStatus(surveyTest.getStatus());
        surveyTestUpdateParam.setProcessInstanceId(surveyTest.getProcessInstanceId());
        surveyTestUpdateParam.setHistoryInstanceId(surveyTest.getHistoryInstanceId());
        BeanUtils.copyProperties(surveyTestUpdateParam, surveyTest);
        surveyTest.setState(DataStateEnum.ENABLE.getCode());
        surveyTest.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        //处理历史流程id列表
        String historyInstanceIds = InstanceUtil.dealHistoryId(surveyTest.getProcessInstanceId(), surveyTest.getHistoryInstanceId());
        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.SURVEY_TEST.getKey());
        bpmProcessInstanceCreateReqDTO.setBusinessKey(surveyTest.getId());
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(new HashMap<>(8));
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(RequestUtil.getUserIndex(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        surveyTest.setProcessInstanceId(processInstanceId);
        //保存历史流程id列表
        surveyTest.setHistoryInstanceId(historyInstanceIds);
        surveyTest.setCreateBy(RequestUtil.getUserIndex());
        surveyTest.setUpdateBy(RequestUtil.getUserIndex());
        surveyTest.setUpdateTime(LocalDateTimeUtil.now());
        this.baseMapper.updateById(surveyTest);
        return surveyTest.getId();
    }

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

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

    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        BpmInstanceInfo bpmInstanceInfo = new BpmInstanceInfo();
        SurveyTestVO surveyTestVO = this.getVOById(businessId);
        if(Objects.isNull(surveyTestVO)){
            return null;
        }
        bpmInstanceInfo.setHistoryInstanceId(surveyTestVO.getHistoryInstanceId());
        DictData data = dicDataFeignClient.getDicDataById(surveyTestVO.getSupvType()).getData();
        String name = "未知监督类型";
        if(Objects.nonNull(data)){
            name = data.getName();
        }
        String  sign = name.concat("->")
                .concat(surveyTestVO.getSupvObjectName());
        bpmInstanceInfo.setInstanceSign(sign);
        return bpmInstanceInfo;
    }

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

    @Override
    public SurveyTestVO getVOById(String id) {
        SurveyTestVO surveyTestVO = new SurveyTestVO();
        SurveyTest surveyTest = this.baseMapper.selectById(id);
        if(Objects.isNull(surveyTest)){
            return null;
        }
        BeanUtils.copyProperties(surveyTest, surveyTestVO);
        String planId = surveyTest.getPlanId();
        SurveyPlan surveyPlan = surveyPlanService.getById(planId);
        surveyTestVO.setPlanStartTime(surveyPlan.getPlanStartTime());
        surveyTestVO.setPlanEndTime(surveyPlan.getPlanEndTime());
        surveyTestVO.setPlanName(surveyPlan.getPlanName());
        surveyTestVO.setSupvType(surveyPlan.getSupvType());
        surveyTestVO.setSupvObjectName(surveyPlan.getSupvObjectName());
        WarningLeaflet one = warningLeafletService.lambdaQuery().eq(WarningLeaflet::getProblemId, id).one();
        if(Objects.nonNull(one)){
            surveyTestVO.setReformAdvice(one.getReformAdvice());
            surveyTestVO.setTakeStep(one.getTakeStep());
            surveyTestVO.setReportPath(one.getReportPath());
        }
        //负责单位
        surveyTestVO.setDeptName(deptFeignClient.getDeptById(surveyTestVO.getDeptId()).getData().getName());
        //变电站名称
        if (surveyTestVO.getCustomSubstationFlag() == 0) {
            //关联台账内的变电站名称
            String substation = surveyTestVO.getSubstation();
            if(StringUtils.isNotEmpty(substation)){
                PollutionSubstationDTO data = lineFeignClient.getSubstationInfo(substation).getData();
                surveyTestVO.setSubstationName(data.getName());
                surveyTestVO.setVoltageLevel(data.getVoltageLevel());
            }

        } else {
            surveyTestVO.setSubstationName(surveyTestVO.getSubstation());
            surveyTestVO.setVoltageLevel("/");
        }
        return surveyTestVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initiateWarningLeaflet(WarningAddParam warningAddParam) {
        SurveyTestVO surveyTestVO = this.getVOById(warningAddParam.getId());
        /*
         * 1、预告警单名称，此处暂时用普测计划名称+变电站名称组成预告警单名
         * 2、预告警编号暂时随机by yxb
         * 3、问题类型：1：技术监督管理；2：在线监测超标问题；3：用户投诉；4：现场测试超标，此处是现场测试超标
         * 4、对应问题源id，用于查询详细数据
         * 5、单子类型：1：预警单；2：告警单
         * 6、问题详细描述
         * */
        warningLeafletService.createLeaflet(
                surveyTestVO.getPlanName().concat(StrPool.UNDERLINE).concat(surveyTestVO.getSubstationName()),
                surveyTestVO.getDeptId(),
                IdWorker.get32UUID(),
                warningAddParam.getId(),
                ProblemTypeEnum.PLAN.getCode(),
                LeafletTypeEnum.ALARM.getCode(),
                surveyTestVO.getProblemDetail(),
                warningAddParam.getReformAdvice(),
                null
        );
        //将当前的测试数据改为已告警
        this.lambdaUpdate().eq(SurveyTest::getId,warningAddParam.getId()).set(SurveyTest::getInitiateWarningFlag,1).update();
    }

    @Override
    public Boolean deleteSurveyPlanTest(List<String> supervisionId) {
        List<SurveyTest> surveyTests = this.listByIds(supervisionId);
        if(CollUtil.isEmpty(surveyTests)){
            throw new BusinessException(SupervisionResponseEnum.EXISTENCE_OR_NOT);
        }
        //判断是否有权限操作
        List<String> collect = surveyTests.stream().map(SurveyTest::getCreateBy).distinct().collect(Collectors.toList());
        long count = surveyTests.stream().filter(x -> !BpmTaskStatusEnum.WAIT.getStatus().equals(x.getStatus())).count();
        InstanceUtil.deleteRole(RequestUtil.getUserIndex(), collect, count);
        return this.update(new LambdaUpdateWrapper<SurveyTest>().set(SurveyTest::getState, DataStateEnum.DELETED.getCode())
                    .in(SurveyTest::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<SurveyTestVO> queryWrapper = new QueryWrapper<>();
        List<String> deptIds = deptFeignClient.getDepSonIdtByDeptId(RequestUtil.getDeptIndex()).getData();
        if(CollectionUtil.isEmpty(deptIds)){
            return todoVOList;
        }
        queryWrapper.in("supervision_survey_test.dept_id", deptIds)
                .le("supervision_survey_plan.plan_start_time", LocalDateTimeUtil.now())
                .eq("supervision_survey_test.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_survey_test.status", BpmProcessInstanceStatusEnum.AWAIT.getStatus())
                .orderByDesc("supervision_survey_test.Update_Time");
        List<SurveyTestVO> surveyTestVOList = this.baseMapper.getTodoBusiness(queryWrapper);
        if(CollectionUtil.isNotEmpty(surveyTestVOList)){
            todoVOList = surveyTestVOList.stream().map(item -> {
                if (item.getCustomSubstationFlag() == 0) {
                    //关联台账内的变电站名称
                    String substation = item.getSubstation();
                    if(StringUtils.isNotEmpty(substation)){
                        item.setSubstationName(lineFeignClient.getSubstationInfo(substation).getData().getName());
                    }
                } else {
                    item.setSubstationName(item.getSubstation());
                }
                TodoVO todoVO = new TodoVO();
                todoVO.setTaskName("技术监督测试");
                todoVO.setTaskContent(item.getSubstationName());
                todoVO.setStartUser(item.getCreateBy());
                todoVO.setId(item.getId());
                todoVO.setTaskCreateTime(item.getCreateTime());
                todoVO.setSource(3);
                todoVO.setRoutePath("supervision/harmonicmanagement");
                todoVO.setTabValue(2);
                return todoVO;

            }).collect(Collectors.toList());
        }
        return todoVOList;
    }


}
