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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.StrPool;
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.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.SubGetBase;
import com.njcn.device.biz.pojo.param.SubstationParam;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.device.pq.pojo.vo.LineDetailDataVO;
import com.njcn.supervision.enums.FlowStatusEnum;
import com.njcn.supervision.enums.LeafletTypeEnum;
import com.njcn.supervision.enums.ProblemTypeEnum;
import com.njcn.supervision.mapper.survey.SupervisionGeneralSurveyPlanPOMapper;
import com.njcn.supervision.pojo.param.survey.SupervisionGeneralSurveyPlanParm;
import com.njcn.supervision.pojo.po.survey.SupervisionGeneralSurveyPlanDetailPO;
import com.njcn.supervision.pojo.po.survey.SupervisionGeneralSurveyPlanPO;
import com.njcn.supervision.pojo.vo.survey.DeptSubstationVO;
import com.njcn.supervision.pojo.vo.survey.SupervisionGeneralSurveyPlanDetailVO;
import com.njcn.supervision.pojo.vo.survey.SupervisionGeneralSurveyPlanVO;
import com.njcn.supervision.service.leaflet.IWarningLeafletService;
import com.njcn.supervision.service.survey.SupervisionGeneralSurveyPlanDetailPOService;
import com.njcn.supervision.service.survey.SupervisionGeneralSurveyPlanPOService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * Description:
 * Date: 2024/5/13  18:35【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@Deprecated
@RequiredArgsConstructor
public class SupervisionGeneralSurveyPlanPOServiceImpl extends ServiceImpl<SupervisionGeneralSurveyPlanPOMapper, SupervisionGeneralSurveyPlanPO> implements SupervisionGeneralSurveyPlanPOService {
    /**
     * 用户信息建档对应的流程定义 KEY todo 修改成普测的key
     */
    public static final String PROCESS_KEY = "harmonic_survey";

    private final CommTerminalGeneralClient commTerminalGeneralClient;
    private final SupervisionGeneralSurveyPlanDetailPOService supervisionGeneralSurveyPlanDetailPOService;
    private final BpmProcessFeignClient bpmProcessFeignClient;
    private final DeptFeignClient deptFeignClient;
    private final LineFeignClient lineFeignClient;
    private final UserFeignClient userFeignClient;
    private final IWarningLeafletService warningLeafletService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addDevReport(SupervisionGeneralSurveyPlanParm supervisionGeneralSurveyPlanParm) {
        //判断工程名称是否有重复的
        checkPlanName(supervisionGeneralSurveyPlanParm, false);
        //保存普测计划主表
        SupervisionGeneralSurveyPlanPO supervisionGeneralSurveyPlanPO = new SupervisionGeneralSurveyPlanPO();
        BeanUtils.copyProperties(supervisionGeneralSurveyPlanParm, supervisionGeneralSurveyPlanPO);
        supervisionGeneralSurveyPlanPO.setState(DataStateEnum.ENABLE.getCode());
        supervisionGeneralSurveyPlanPO.setPlanCreateTime(LocalDate.now());
        supervisionGeneralSurveyPlanPO.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        this.save(supervisionGeneralSurveyPlanPO);
        String planNo = supervisionGeneralSurveyPlanPO.getPlanNo();
        //保存普测计划电站表
        if (CollectionUtil.isNotEmpty(supervisionGeneralSurveyPlanParm.getSubIds())) {
            SubstationParam param = new SubstationParam();
            param.setPowerIds(supervisionGeneralSurveyPlanParm.getSubIds());
            List<SubGetBase> stationList = commTerminalGeneralClient.tagOrIdGetSub(param).getData();
            List<SupervisionGeneralSurveyPlanDetailPO> supervisionGeneralSurveyPlanDetailPOS = new ArrayList<>();
            for (SubGetBase stat : stationList) {
                SupervisionGeneralSurveyPlanDetailPO supervisionGeneralSurveyPlanDetailPO = new SupervisionGeneralSurveyPlanDetailPO();
                supervisionGeneralSurveyPlanDetailPO.setPlanNo(planNo);

                supervisionGeneralSurveyPlanDetailPO.setSubId(stat.getId());
                supervisionGeneralSurveyPlanDetailPO.setSubName(stat.getName());
                /*目前时间与计划开始时间，结束时间一致*/
                supervisionGeneralSurveyPlanDetailPO.setVoltageLevel(stat.getVoltageLevel());
                List<Line> lines = lineFeignClient.getSubIndexLineDetail(stat.getId()).getData();
                if (CollectionUtil.isEmpty(lines)) {
                    supervisionGeneralSurveyPlanDetailPO.setMeasurementPointId("");
                    supervisionGeneralSurveyPlanDetailPO.setIsSurvey(0);
                } else {
                    String subList = lines.stream().map(Line::getName).collect(Collectors.joining(","));
                    supervisionGeneralSurveyPlanDetailPO.setMeasurementPointId(subList);
                    supervisionGeneralSurveyPlanDetailPO.setIsSurvey(1);
                }
                supervisionGeneralSurveyPlanDetailPO.setState(DataStateEnum.ENABLE.getCode());
                supervisionGeneralSurveyPlanDetailPOS.add(supervisionGeneralSurveyPlanDetailPO);
            }
            supervisionGeneralSurveyPlanDetailPOService.saveOrUpdateBatchByMultiId(supervisionGeneralSurveyPlanDetailPOS, 500);
            // 发起 BPM 流程
            Map<String, Object> processInstanceVariables = new HashMap<>();
            BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
            bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(PROCESS_KEY);
            bpmProcessInstanceCreateReqDTO.setBusinessKey(planNo);
            bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(supervisionGeneralSurveyPlanParm.getStartUserSelectAssignees());
            bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
            String processInstanceId = bpmProcessFeignClient.createProcessInstance(supervisionGeneralSurveyPlanPO.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
            // 将工作流的编号，更新到流程单中
            supervisionGeneralSurveyPlanPO.setProcessInstanceId(processInstanceId);
            this.baseMapper.updateById(supervisionGeneralSurveyPlanPO);
            return planNo;
        }
        {
            throw new BusinessException("请选择电站");
        }


    }

    @Override
    public boolean auditSurvey(SupervisionGeneralSurveyPlanParm.SupervisionGeneralSurveyPlanUpdate supervisionGeneralSurveyPlanUpdate) {
        //判断计划名称是否有重复的
        checkPlanName(supervisionGeneralSurveyPlanUpdate, true);

        String planNo = supervisionGeneralSurveyPlanUpdate.getPlanNo();
        SupervisionGeneralSurveyPlanPO byId = this.getById(planNo);
        BeanUtils.copyProperties(supervisionGeneralSurveyPlanUpdate, byId);
        byId.setState(DataStateEnum.ENABLE.getCode());
        byId.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        SubstationParam param = new SubstationParam();
        param.setPowerIds(supervisionGeneralSurveyPlanUpdate.getSubIds());
        List<SubGetBase> stationList = commTerminalGeneralClient.tagOrIdGetSub(param).getData();
        List<SupervisionGeneralSurveyPlanDetailPO> supervisionGeneralSurveyPlanDetailPOS = new ArrayList<>();
        for (SubGetBase stat : stationList) {
            SupervisionGeneralSurveyPlanDetailPO supervisionGeneralSurveyPlanDetailPO = new SupervisionGeneralSurveyPlanDetailPO();
            supervisionGeneralSurveyPlanDetailPO.setPlanNo(planNo);

            supervisionGeneralSurveyPlanDetailPO.setSubId(stat.getId());
            supervisionGeneralSurveyPlanDetailPO.setSubName(stat.getName());
            /*目前时间与计划开始时间，结束时间一致*/
            supervisionGeneralSurveyPlanDetailPO.setVoltageLevel(stat.getVoltageLevel());
            List<String> unitChildrenList = stat.getUnitChildrenList();
            if (CollectionUtil.isEmpty(unitChildrenList)) {
                supervisionGeneralSurveyPlanDetailPO.setMeasurementPointId("");
                supervisionGeneralSurveyPlanDetailPO.setIsSurvey(0);
            } else {
                List<LineDetailDataVO> data = lineFeignClient.getLineDetailList(unitChildrenList).getData();

                String subList = data.stream().map(LineDetailDataVO::getLineName).collect(Collectors.joining(","));
                supervisionGeneralSurveyPlanDetailPO.setMeasurementPointId(subList);
                supervisionGeneralSurveyPlanDetailPO.setIsSurvey(1);
            }
            supervisionGeneralSurveyPlanDetailPO.setState(DataStateEnum.ENABLE.getCode());
            supervisionGeneralSurveyPlanDetailPOS.add(supervisionGeneralSurveyPlanDetailPO);
        }
        //清除原有的
        supervisionGeneralSurveyPlanDetailPOService.remove(new QueryWrapper<SupervisionGeneralSurveyPlanDetailPO>().lambda().eq(SupervisionGeneralSurveyPlanDetailPO::getPlanNo, planNo));
        supervisionGeneralSurveyPlanDetailPOService.saveOrUpdateBatchByMultiId(supervisionGeneralSurveyPlanDetailPOS, 500);
        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>();
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(PROCESS_KEY);
        bpmProcessInstanceCreateReqDTO.setBusinessKey(planNo);
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(supervisionGeneralSurveyPlanUpdate.getStartUserSelectAssignees());
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(RequestUtil.getUserIndex(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        byId.setProcessInstanceId(processInstanceId);
        this.baseMapper.updateById(byId);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSurvey(List<String> ids) {
        this.lambdaUpdate().set(SupervisionGeneralSurveyPlanPO::getState, 0).in(SupervisionGeneralSurveyPlanPO::getPlanNo, ids).update();
        supervisionGeneralSurveyPlanDetailPOService.remove(new QueryWrapper<SupervisionGeneralSurveyPlanDetailPO>().
                lambda().in(SupervisionGeneralSurveyPlanDetailPO::getPlanNo, ids));

        return true;
    }

    @Override
    public Page<SupervisionGeneralSurveyPlanVO> getSurvey(SupervisionGeneralSurveyPlanParm.GeneralSurveyPlanQueryParam generalSurveyPlanQueryParam) {
        String userIndex = RequestUtil.getUserIndex();
        QueryWrapper<SupervisionGeneralSurveyPlanVO> queryWrapper = new QueryWrapper<>();

        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();

        queryWrapper.in("supervision_general_survey_plan.create_by", colleaguesIds)
                .eq("supervision_general_survey_plan.state", DataStateEnum.ENABLE.getCode());
        /*获取直接下属子单位*/
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(generalSurveyPlanQueryParam.getOrgNo()).getData();

        if (Objects.nonNull(generalSurveyPlanQueryParam)) {
            if (StrUtil.isNotBlank(generalSurveyPlanQueryParam.getOrgNo())) {
                //查询所有区域下的数据
                queryWrapper.in("supervision_general_survey_plan.org_no", data);
            }
        }
        //添加上时间范围
        queryWrapper.between("supervision_general_survey_plan.Create_Time",
                DateUtil.beginOfDay(DateUtil.parse(generalSurveyPlanQueryParam.getSearchBeginTime())),
                DateUtil.endOfDay(DateUtil.parse(generalSurveyPlanQueryParam.getSearchEndTime())));
        queryWrapper.orderByDesc("supervision_general_survey_plan.create_time");
        Page<SupervisionGeneralSurveyPlanVO> page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(generalSurveyPlanQueryParam), PageFactory.getPageSize(generalSurveyPlanQueryParam)), queryWrapper);

        page.getRecords().stream().forEach(temp -> {
            temp.setOrgName((deptFeignClient.getDeptById(temp.getOrgNo()).getData().getName()));
            //获取普测下电站详情
            List<SupervisionGeneralSurveyPlanDetailPO> list = supervisionGeneralSurveyPlanDetailPOService.lambdaQuery().eq(SupervisionGeneralSurveyPlanDetailPO::getPlanNo, temp.getPlanNo()).list();
            temp.setSupervisionGeneralSurveyPlanDetailPOS(list);
            temp.setSubIds(list.stream().map(SupervisionGeneralSurveyPlanDetailPO::getSubId).collect(Collectors.toList()));
        });

        return page;

    }

    @Override
    public Page<SupervisionGeneralSurveyPlanDetailVO> pageProblemSubstationBySurvey(SupervisionGeneralSurveyPlanParm.GeneralSurveyPlanQueryParam generalSurveyPlanQueryParam) {
        QueryWrapper<SupervisionGeneralSurveyPlanDetailVO> supervisionGeneralSurveyPlanDetailVOQueryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(generalSurveyPlanQueryParam)) {
            //添加上时间范围
            supervisionGeneralSurveyPlanDetailVOQueryWrapper.between("supervision_general_survey_plan_detail.Create_Time",
                    DateUtil.beginOfDay(DateUtil.parse(generalSurveyPlanQueryParam.getSearchBeginTime())),
                    DateUtil.endOfDay(DateUtil.parse(generalSurveyPlanQueryParam.getSearchEndTime())));
        }
        //获取当前用户部门所有同事的id，查看该部门下所有的数据
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        supervisionGeneralSurveyPlanDetailVOQueryWrapper.in("supervision_general_survey_plan_detail.Create_By", colleaguesIds)
                .eq("supervision_general_survey_plan.status", BpmProcessInstanceStatusEnum.APPROVE.getStatus())
                .orderByDesc("supervision_general_survey_plan_detail.Update_Time");
        Page<SupervisionGeneralSurveyPlanDetailVO> page = this.baseMapper.pageProblemSubstationBySurvey(new Page<>(PageFactory.getPageNum(generalSurveyPlanQueryParam), PageFactory.getPageSize(generalSurveyPlanQueryParam)), supervisionGeneralSurveyPlanDetailVOQueryWrapper);
        //填充部门名称
        page.getRecords().forEach(temp -> temp.setOrgName((deptFeignClient.getDeptById(temp.getOrgNo()).getData().getName())));
        return page;
    }

    @Override
    public SupervisionGeneralSurveyPlanVO querySurveyDetail(String id) {
        SupervisionGeneralSurveyPlanVO supervisionGeneralSurveyPlanVO = new SupervisionGeneralSurveyPlanVO();
        SupervisionGeneralSurveyPlanPO byId = this.getById(id);
        BeanUtils.copyProperties(byId, supervisionGeneralSurveyPlanVO);
        //获取普测下电站详情
        List<SupervisionGeneralSurveyPlanDetailPO> list = supervisionGeneralSurveyPlanDetailPOService.lambdaQuery().eq(SupervisionGeneralSurveyPlanDetailPO::getPlanNo, id).list();
        supervisionGeneralSurveyPlanVO.setSupervisionGeneralSurveyPlanDetailPOS(list);
        return supervisionGeneralSurveyPlanVO;
    }

    @Override
    public List<DeptSubstationVO> initDetpStataionTree(String orgId) {
        List<PvTerminalTreeVO> data = deptFeignClient.allDeptList().getData();
        List<DeptSubstationVO> deptSubstationVOList = data.stream().map(temp -> {
            DeptSubstationVO deptSubstationVO = new DeptSubstationVO();
            BeanUtils.copyProperties(temp, deptSubstationVO);
            deptSubstationVO.setDisabled(true);
            deptSubstationVO.setFlag(true);
            SubstationParam param = new SubstationParam();
            param.setOrgIds(Arrays.asList(temp.getId()));
            List<SubGetBase> list1 = commTerminalGeneralClient.tagOrIdGetSub(param).getData();
            List<DeptSubstationVO> children = deptSubstationVO.getChildren();
            List<DeptSubstationVO> collect = list1.stream().map(statationStat -> {
                DeptSubstationVO deptSubstationVO1 = new DeptSubstationVO();
                deptSubstationVO1.setId(statationStat.getId());
                deptSubstationVO1.setPid(temp.getId());
                deptSubstationVO1.setName(statationStat.getName());
//                if (finalSubIds.contains(statationStat.getId())) {
//                    deptSubstationVO1.setDisabled(true);
//                }
                deptSubstationVO1.setFlag(true);
                return deptSubstationVO1;
            }).collect(Collectors.toList());
            children.addAll(collect);

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

        // 遍历两次data来组装带有children关联性的对象，如果找到子级就删除result的数据
        List<DeptSubstationVO> result = new ArrayList<>(deptSubstationVOList);
        for (DeptSubstationVO pv : deptSubstationVOList) {
            for (DeptSubstationVO pv2 : deptSubstationVOList) {

                /*如果本级id与数据的父id相同，就说明是子父级关系*/
                if (pv.getId().equals(pv2.getPid())) {
                    pv.getChildren().add(pv2);
                    result.remove(pv2);
                }
            }
        }

        result = recursion(result.get(0), orgId);
        return result;
    }

    @Override
    public void updateProcessStatus(String businessKey, Integer status) {
        this.lambdaUpdate().set(SupervisionGeneralSurveyPlanPO::getStatus, status).eq(SupervisionGeneralSurveyPlanPO::getPlanNo, businessKey).update();
    }

    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        return null;
    }

    /**
     * 该流程暂时没有在页面体现出来
     */
    @Override
    public Set<String> getAllRejectInstanceIds() {
        return new HashSet<>();
    }

    @Override
    public String cancelGeneralSurvey(BpmProcessInstanceCancelParam cancelReqVO) {
        //准备取消该流程，需要远程调用接口
        SupervisionGeneralSurveyPlanPO supervisionGeneralSurveyPlanPO = this.baseMapper.selectById(cancelReqVO.getId());
        //取消流程
        bpmProcessFeignClient.cancelProcessInstanceByStartUser(cancelReqVO);
        //更新状态
        supervisionGeneralSurveyPlanPO.setStatus(BpmProcessInstanceStatusEnum.CANCEL.getStatus());
        this.updateById(supervisionGeneralSurveyPlanPO);
        return supervisionGeneralSurveyPlanPO.getPlanNo();
    }

    @Override
    public void initiateWarningLeaflet(String id, String subId) {
//        //获取数据源用于组装数据
//        LambdaQueryWrapper<SupervisionGeneralSurveyPlanDetailPO> detailPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        detailPOLambdaQueryWrapper.eq(SupervisionGeneralSurveyPlanDetailPO::getPlanNo, id)
//                .eq(SupervisionGeneralSurveyPlanDetailPO::getSubId, subId);
//        SupervisionGeneralSurveyPlanDetailPO detailPlan = supervisionGeneralSurveyPlanDetailPOService.getOne(detailPOLambdaQueryWrapper);
//        SupervisionGeneralSurveyPlanPO generalSurveyPlan = this.getById(id);
//        /*
//         * 1、预告警单名称，此处暂时用普测计划名称+变电站名称组成预告警单名
//         * 2、预告警编号暂时随机by yxb
//         * 3、问题类型：1：技术监督管理；2：在线监测超标问题；3：用户投诉；4：现场测试超标，此处是现场测试超标
//         * 4、对应问题源id，用于查询详细数据
//         * 5、单子类型：1：预警单；2：告警单
//         * 6、问题详细描述
//         * */
//        warningLeafletService.createLeaflet(
//                generalSurveyPlan.getPlanName().concat(StrPool.UNDERLINE).concat(detailPlan.getSubName()),
//                IdWorker.get32UUID(),
//                id,
//                ProblemTypeEnum.SITE_TEST.getCode(),
//                LeafletTypeEnum.ALARM.getCode(),
//                assembleIssueDetail(detailPlan,generalSurveyPlan)
//        );
//        //将当前的问题记录是否告警修改为已告警
//        LambdaUpdateWrapper<SupervisionGeneralSurveyPlanDetailPO> detailPOLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//        detailPOLambdaUpdateWrapper.set(SupervisionGeneralSurveyPlanDetailPO::getInitiateWarningFlag, 1)
//                .eq(SupervisionGeneralSurveyPlanDetailPO::getPlanNo, id)
//                .eq(SupervisionGeneralSurveyPlanDetailPO::getSubId, subId);
//        supervisionGeneralSurveyPlanDetailPOService.update(detailPOLambdaUpdateWrapper);
    }

    /**
     * 组装谐波普测的问题
     * 格式：planCreateTime发起的planName普测计划，由负责人leader测试后，于planComplateTime完成，其中subName在本次普测计划测试中存在电能质量问题，详细请查看附件
     */
    private String assembleIssueDetail(SupervisionGeneralSurveyPlanDetailPO detailPlan, SupervisionGeneralSurveyPlanPO generalSurveyPlan) {
        String issueDetail = "于"
                .concat(LocalDateTimeUtil.format(generalSurveyPlan.getPlanCreateTime(), DatePattern.CHINESE_DATE_PATTERN))
                .concat("发起的")
                .concat(generalSurveyPlan.getPlanName())
                .concat("普测计划，由负责人")
                .concat(generalSurveyPlan.getLeader())
                .concat("测试后，于")
                .concat(LocalDateTimeUtil.format(generalSurveyPlan.getPlanComplateTime(), DatePattern.CHINESE_DATE_PATTERN))
                .concat("完成，其中")
                .concat(detailPlan.getSubName())
                .concat("在本次普测计划测试中存在电能质量问题，详细请查看问题附件");
        return issueDetail;
    }


    public List<DeptSubstationVO> recursion(DeptSubstationVO result, String orgdid) {
        List<DeptSubstationVO> deptSubstationVOList = new ArrayList<>();
        if (Objects.equals(result.getId(), orgdid)) {
            deptSubstationVOList.add(result);
            return deptSubstationVOList;

        } else {
            for (DeptSubstationVO deptSubstationVO : result.getChildren()) {

                List<DeptSubstationVO> recursion = recursion(deptSubstationVO, orgdid);
                if (recursion.size() > 0) {
                    return recursion;
                }

            }
        }
        return deptSubstationVOList;
    }

    /**
     * @Description: 校验计划名称是否存在
     * @Param: * @param userReportParam 用户申请数据
     * * @param isExcludeSelf   是否排除自己，一般新增不排除，更新时需要排除自己
     * @return: void
     * @Author: clam
     * @Date: 2024/5/13
     */
    private void checkPlanName(SupervisionGeneralSurveyPlanParm supervisionGeneralSurveyPlanParm, boolean isExcludeSelf) {
        LambdaQueryWrapper<SupervisionGeneralSurveyPlanPO> userReportPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userReportPOLambdaQueryWrapper
                .eq(SupervisionGeneralSurveyPlanPO::getPlanName, supervisionGeneralSurveyPlanParm.getPlanName())
                .eq(SupervisionGeneralSurveyPlanPO::getState, DataStateEnum.ENABLE.getCode());
        //更新的时候，需排除当前记录
        if (isExcludeSelf) {
            if (supervisionGeneralSurveyPlanParm instanceof SupervisionGeneralSurveyPlanParm.SupervisionGeneralSurveyPlanUpdate) {
                userReportPOLambdaQueryWrapper.ne(SupervisionGeneralSurveyPlanPO::getPlanNo, ((SupervisionGeneralSurveyPlanParm.SupervisionGeneralSurveyPlanUpdate) supervisionGeneralSurveyPlanParm).getPlanNo());
            }
        }
        List<SupervisionGeneralSurveyPlanPO> list = this.baseMapper.selectList(userReportPOLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            //过滤已取消的申请
            list = list.stream()
                    .filter(temp -> !temp.getStatus().equals(FlowStatusEnum.CANCEL.getCode()))
                    .collect(Collectors.toList());
            //如果还存在，则说明有人申请过了
            if (CollectionUtil.isNotEmpty(list)) {
                throw new BusinessException(supervisionGeneralSurveyPlanParm.getPlanName().concat(",该计划已被").concat(list.get(0).getCreateBy()).concat("申请"));
            }
        }
    }
}
