package com.njcn.supervision.service.plan.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.DateTime;
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.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.utils.PubUtils;
import com.njcn.db.constant.DbConstant;
import com.njcn.supervision.enums.SupervisionKeyEnum;
import com.njcn.supervision.mapper.plan.SupervisionPlanPOMapper;
import com.njcn.supervision.pojo.param.plan.SupervisionPlanParam;
import com.njcn.supervision.pojo.po.plan.SupervisionPlanPO;
import com.njcn.supervision.pojo.po.plan.SupervisionProblemPO;
import com.njcn.supervision.pojo.vo.plan.SupervisionPlanVO;
import com.njcn.supervision.service.plan.SupervisionPlanPOService;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.user.pojo.vo.UserVO;
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.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * Description:
 * Date: 2024/5/20  17:49【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class SupervisionPlanPOServiceImpl extends ServiceImpl<SupervisionPlanPOMapper, SupervisionPlanPO> implements SupervisionPlanPOService{
    private final UserFeignClient userFeignClient;
    private final DeptFeignClient deptFeignClient;
    private final BpmProcessFeignClient bpmProcessFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addPlan(SupervisionPlanParam supvPlanParam) {
        checkParam(supvPlanParam, false);
        SupervisionPlanPO supvPlan = new SupervisionPlanPO();
        BeanUtil.copyProperties(supvPlanParam, supvPlan);
        supvPlan.setPlanSupvDate(LocalDateTimeUtil.parse(supvPlanParam.getPlanSupvDate(), DatePattern.NORM_DATETIME_PATTERN));

        if(StrUtil.isNotBlank(supvPlanParam.getEffectEndTime())) {
            supvPlan.setEffectEndTime(PubUtils.localDateTimeFormat(supvPlanParam.getEffectEndTime()));
        }
        if(StrUtil.isNotBlank(supvPlanParam.getEffectStartTime())) {
            supvPlan.setEffectStartTime(PubUtils.localDateTimeFormat(supvPlanParam.getEffectStartTime()));
        }
        if(StrUtil.isNotBlank(supvPlanParam.getProblemOcTime())) {
            supvPlan.setProblemOcTime(PubUtils.localDateTimeFormat(supvPlanParam.getProblemOcTime()));
        }
        if(StrUtil.isNotBlank(supvPlanParam.getReportIssueTime())) {
            supvPlan.setReportIssueTime(PubUtils.localDateTimeFormat(supvPlanParam.getReportIssueTime()));
        }



        if(!"01".equals(supvPlan.getEffectStatus())){
            if(Objects.isNull(supvPlan.getEffectStartTime()) ){
                throw new BusinessException("开始实施时间不可为空！");
            }
        }

        if("04".equals(supvPlan.getEffectStatus())){
            if(Objects.isNull(supvPlan.getEffectEndTime()) ){
                throw new BusinessException("结束实施时间不可为空！");
            }
        }


        supvPlan.setIsUploadHead(0);
        if(StrUtil.isNotBlank(supvPlan.getEffectUserId())){
            List<User> userList = userFeignClient.getUserByIdList(Stream.of(supvPlan.getEffectUserId()).collect(Collectors.toList())).getData();
            if(CollUtil.isNotEmpty(userList)){
                supvPlan.setEffectUserName(userList.get(0).getName());
            }
        }
        supvPlan.setState(DataStateEnum.ENABLE.getCode());
        supvPlan.setIsUploadHead(0);
        supvPlan.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        this.save(supvPlan);
        return supvPlan.getPlanId();
    }

    @Override
    public String updatePlan(SupervisionPlanParam.UpdateSupvPlanParam supvPlanParam) {
        SupervisionPlanPO supervisionPlanPO = this.baseMapper.selectById(supvPlanParam.getPlanId());

        //判断是否有权限操作
        InstanceUtil.judgeUserPower(RequestUtil.getUserIndex(),supervisionPlanPO.getCreateBy());

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

        checkParam(supvPlanParam, true);

        BeanUtil.copyProperties(supvPlanParam, supervisionPlanPO);
        supervisionPlanPO.setPlanSupvDate(LocalDateTimeUtil.parse(supvPlanParam.getPlanSupvDate(), DatePattern.NORM_DATETIME_PATTERN));

        if(StrUtil.isNotBlank(supvPlanParam.getEffectEndTime())) {
            supervisionPlanPO.setEffectEndTime(PubUtils.localDateTimeFormat(supvPlanParam.getEffectEndTime()));
        }
        if(StrUtil.isNotBlank(supvPlanParam.getEffectStartTime())) {
            supervisionPlanPO.setEffectStartTime(PubUtils.localDateTimeFormat(supvPlanParam.getEffectStartTime()));
        }
        if(StrUtil.isNotBlank(supvPlanParam.getProblemOcTime())) {
            supervisionPlanPO.setProblemOcTime(PubUtils.localDateTimeFormat(supvPlanParam.getProblemOcTime()));
        }
        if(StrUtil.isNotBlank(supvPlanParam.getReportIssueTime())) {
            supervisionPlanPO.setReportIssueTime(PubUtils.localDateTimeFormat(supvPlanParam.getReportIssueTime()));
        }



        if(!"01".equals(supervisionPlanPO.getEffectStatus())){
            if(Objects.isNull(supervisionPlanPO.getEffectStartTime()) ){
                throw new BusinessException("开始实施时间不可为空！");
            }
        }

        if("04".equals(supervisionPlanPO.getEffectStatus())){
            if(Objects.isNull(supervisionPlanPO.getEffectEndTime()) ){
                throw new BusinessException("结束实施时间不可为空！");
            }
        }


        if(StrUtil.isNotBlank(supervisionPlanPO.getEffectUserId())){
            UserVO user = userFeignClient.getUserById(supervisionPlanPO.getEffectUserId()).getData();
            if(Objects.nonNull(user)){
                supervisionPlanPO.setEffectUserName(user.getName());
            }
        }
        supervisionPlanPO.setState(DataStateEnum.ENABLE.getCode());
        supervisionPlanPO.setIsUploadHead(0);
        supervisionPlanPO.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());



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

    }

    @Override
    public Page<SupervisionPlanVO> pagePlan(SupervisionPlanParam supvPlanParam) {
        LambdaQueryWrapper<SupervisionPlanPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(supvPlanParam.getSupvOrgId())) {
            List<String> deptIds = deptFeignClient.getDepSonSelfCodetByCode(supvPlanParam.getSupvOrgId()).getData();
            lambdaQueryWrapper.in(SupervisionPlanPO::getSupvOrgId, deptIds)
                    .between(SupervisionPlanPO::getPlanSupvDate, supvPlanParam.getSearchBeginTime(),supvPlanParam.getSearchEndTime())
                    .eq(StrUtil.isNotBlank(supvPlanParam.getSupvType()),SupervisionPlanPO::getSupvType,supvPlanParam.getSupvType());

        }

        if(StrUtil.isNotBlank(supvPlanParam.getSortBy())){
            if(DbConstant.DESC.equals(supvPlanParam.getOrderBy())){
                lambdaQueryWrapper.orderByDesc(SupervisionPlanPO::getPlanSupvDate);
            }else {
                lambdaQueryWrapper.orderByAsc(SupervisionPlanPO::getPlanSupvDate);

            }
        }else {
            lambdaQueryWrapper.orderByDesc(SupervisionPlanPO::getCreateTime);
        }

       lambdaQueryWrapper.eq(Objects.nonNull(supvPlanParam.getStatus()),SupervisionPlanPO::getStatus,supvPlanParam.getStatus());

        //获取当前用户部门所有同事的id，查看该部门下所有的数据
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        lambdaQueryWrapper.in(SupervisionPlanPO::getCreateBy,colleaguesIds);

        List<PvTerminalTreeVO> deptList = deptFeignClient.allDeptList().getData();
//        Map<String, PvTerminalTreeVO> mapCode = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getCode, Function.identity()));
        Map<String, PvTerminalTreeVO> mapList = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, Function.identity()));


        Page<SupervisionPlanPO> page = this.page(new Page<>(PageFactory.getPageNum(supvPlanParam), PageFactory.getPageSize(supvPlanParam)), lambdaQueryWrapper);
        List<SupervisionPlanVO> supvPlanVOList = BeanUtil.copyToList(page.getRecords(), SupervisionPlanVO.class);
        List<String> userIds = supvPlanVOList.stream().map(SupervisionPlanVO::getPlanUserId).distinct().collect(Collectors.toList());
        supvPlanVOList.forEach(item -> {
            PvTerminalTreeVO pvTerminalTreeVO ;
            if (mapList.containsKey(item.getSupvOrgId())) {
                pvTerminalTreeVO = mapList.get(item.getSupvOrgId());
                item.setSupvOrgName(pvTerminalTreeVO.getName());
                int deptLevel = pvTerminalTreeVO.getPids().split(StrUtil.COMMA).length;
                if (deptLevel == 2) {
                    //省
                    item.setProvince(pvTerminalTreeVO.getName());
                } else if (deptLevel == 3) {
                    //市
                    item.setCity(pvTerminalTreeVO.getName());
                    if (mapList.containsKey(pvTerminalTreeVO.getPid())) {
                        PvTerminalTreeVO pvTerminalTreeOne = mapList.get(pvTerminalTreeVO.getPid());
                        item.setProvince(pvTerminalTreeOne.getName());
                    }
                } else if (deptLevel == 4) {
                    //县
                    if (mapList.containsKey(pvTerminalTreeVO.getPid())) {
                        item.setCounty(pvTerminalTreeVO.getName());
                        PvTerminalTreeVO pvTerminalTreeOne = mapList.get(pvTerminalTreeVO.getPid());
                        if (Objects.nonNull(pvTerminalTreeOne)) {
                            item.setCity(pvTerminalTreeOne.getName());
                            if (mapList.containsKey(pvTerminalTreeOne.getPid())) {
                                PvTerminalTreeVO pvTerminalTreeTwo = mapList.get(pvTerminalTreeOne.getPid());
                                if (Objects.nonNull(pvTerminalTreeTwo)) {
                                    item.setProvince(pvTerminalTreeTwo.getName());
                                }
                            }
                        }
                    }
                }
            }

            if (mapList.containsKey(item.getPlanOrgId())) {
                item.setPlanOrgName(mapList.get(item.getPlanOrgId()).getName());
            }

//            SupvFile supvFile = supvFileMapper.selectOne(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId, item.getPlanId()).eq(SupvFile::getType, 0));
//            if (Objects.nonNull(supvFile)) {
//                item.setAttachmentName(supvFile.getAttachmentName());
//            }

            List<User> userList = userFeignClient.getUserByIdList(userIds).getData();
            Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

            if (map.containsKey(item.getPlanUserId())) {
                item.setPlanUserName(map.get(item.getPlanUserId()).getName());
            }


        });
        Page<SupervisionPlanVO> pageVo = new Page<>();
        pageVo.setTotal(page.getTotal());
        pageVo.setPages(page.getPages());
        pageVo.setSize(page.getSize());
        pageVo.setRecords(supvPlanVOList);
        return pageVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String initiateAudit(String id) {

        SupervisionPlanPO byId = this.getById(id);

//        List<SupervisionProblemPO> list = supervisionProblemPOService.lambdaQuery().eq(SupervisionProblemPO::getPlanId, id).list();
//        if (CollectionUtil.isEmpty(list)){
//            throw new BusinessException("请填写完实施问题提交审核");
//        }
        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.SUP_PLAN_ADD.getKey());
        bpmProcessInstanceCreateReqDTO.setBusinessKey(id);
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(new HashMap<> (16));
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(byId.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        byId.setProcessInstanceId(processInstanceId);
        this.baseMapper.updateById(byId);
        return processInstanceId;
    }

    @Override
    public SupervisionPlanVO getDetailPlan(String id) {
        SupervisionPlanVO supervisionPlanVO = new SupervisionPlanVO();
        List<PvTerminalTreeVO> deptList = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> mapList = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getId, Function.identity()));
        SupervisionPlanPO byId = this.getById(id);
        BeanUtils.copyProperties(byId,supervisionPlanVO);

        if (mapList.containsKey(supervisionPlanVO.getSupvOrgId())) {
            PvTerminalTreeVO pvTerminalTreeVO ;

            pvTerminalTreeVO = mapList.get(supervisionPlanVO.getSupvOrgId());
            supervisionPlanVO.setSupvOrgName(pvTerminalTreeVO.getName());
            int deptLevel = pvTerminalTreeVO.getPids().split(StrUtil.COMMA).length;
            if (deptLevel == 2) {
                //省
                supervisionPlanVO.setProvince(pvTerminalTreeVO.getName());
            } else if (deptLevel == 3) {
                //市
                supervisionPlanVO.setCity(pvTerminalTreeVO.getName());
                if (mapList.containsKey(pvTerminalTreeVO.getPid())) {
                    PvTerminalTreeVO pvTerminalTreeOne = mapList.get(pvTerminalTreeVO.getPid());
                    supervisionPlanVO.setProvince(pvTerminalTreeOne.getName());
                }
            } else if (deptLevel == 4) {
                //县
                if (mapList.containsKey(pvTerminalTreeVO.getPid())) {
                    supervisionPlanVO.setCounty(pvTerminalTreeVO.getName());
                    PvTerminalTreeVO pvTerminalTreeOne = mapList.get(pvTerminalTreeVO.getPid());
                    if (Objects.nonNull(pvTerminalTreeOne)) {
                        supervisionPlanVO.setCity(pvTerminalTreeOne.getName());
                        if (mapList.containsKey(pvTerminalTreeOne.getPid())) {
                            PvTerminalTreeVO pvTerminalTreeTwo = mapList.get(pvTerminalTreeOne.getPid());
                            if (Objects.nonNull(pvTerminalTreeTwo)) {
                                supervisionPlanVO.setProvince(pvTerminalTreeTwo.getName());
                            }
                        }
                    }
                }
            }
        }

        if (mapList.containsKey(supervisionPlanVO.getPlanOrgId())) {
            supervisionPlanVO.setPlanOrgName(mapList.get(supervisionPlanVO.getPlanOrgId()).getName());
        }

//            SupvFile supvFile = supvFileMapper.selectOne(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId, item.getPlanId()).eq(SupvFile::getType, 0));
//            if (Objects.nonNull(supvFile)) {
//                item.setAttachmentName(supvFile.getAttachmentName());
//            }

//        List<User> userList = userFeignClient.getUserByIdList(userIds).getData();
//        Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
//
//        if (map.containsKey(supervisionPlanVO.getPlanUserId())) {
//            supervisionPlanVO.setPlanUserName(map.get(supervisionPlanVO.getPlanUserId()).getName());
//        }

        return supervisionPlanVO;
    }

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

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

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

    @Override
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    public void initiateWarningLeaflet(String id) {
//        //获取数据源用于组装数据
//        List<SupervisionProblemPO> list = supervisionProblemPOService.lambdaQuery().eq(SupervisionProblemPO::getPlanId, id).list();
//
//        SupervisionPlanPO byId = this.getById(id);
//        if(byId.getStatus()!=2){
//            throw new BusinessException("该计划未审核通过无法发送预告警单");
//        }
//        /*
//         * 1、预告警单名称，此处暂时用计算监督计划名称
//         * 2、预告警编号暂时随机by yxb
//         * 3、问题类型：1：技术监督管理；2：在线监测超标问题；3：用户投诉；4：现场测试超标，此处是现场测试超标
//         * 4、对应问题源id，用于查询详细数据
//         * 5、单子类型：1：预警单；2：告警单
//         * 6、问题详细描述
//         * */
//        warningLeafletService.createLeaflet(
//                byId.getWorkPlanName(),
//                IdWorker.get32UUID(),
//                id,
//                ProblemTypeEnum.PLAN.getCode(),
//                LeafletTypeEnum.ALARM.getCode(),
//                assembleIssueDetail(list,byId)
//        );
//        //将当前的问题记录是否告警修改为已告警
//        this.lambdaUpdate().eq(SupervisionPlanPO::getPlanId,id).set(SupervisionPlanPO::getIsUploadHead,1).update();

    }

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

    /**
     * 组装谐波普测的问题
     * 格式：planCreateTime发起的planName普测计划，由负责人leader测试后，于planComplateTime完成，其中subName在本次普测计划测试中存在电能质量问题，详细请查看附件
     */
    private String assembleIssueDetail(List<SupervisionProblemPO> supervisionProblemPOList, SupervisionPlanPO supervisionPlanPO) {
        String join = supervisionProblemPOList.stream().map(SupervisionProblemPO::getRemark).collect(Collectors.joining(","));
        return "于"
                .concat(LocalDateTimeUtil.format(supervisionPlanPO.getCreateTime(), DatePattern.CHINESE_DATE_PATTERN))
                .concat("发起的")
                .concat(supervisionPlanPO.getWorkPlanName())
                .concat("技术监督计划，由负责人")
                .concat(supervisionPlanPO.getEffectUserName())
                .concat("实施，于")
                .concat(LocalDateTimeUtil.format(supervisionPlanPO.getEffectEndTime(), DatePattern.CHINESE_DATE_PATTERN))
                .concat("完成，其中存在问题")
                .concat(join)
                .concat("在本次技术监督计划测试中存在电能质量问题，详细请查看问题附件");
    }



    private void checkParam(SupervisionPlanParam supvPlanParam, Boolean updateFlag) {

        LambdaQueryWrapper<SupervisionPlanPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SupervisionPlanPO::getWorkPlanName, supvPlanParam.getWorkPlanName());

        if (updateFlag) {
            if (supvPlanParam instanceof SupervisionPlanParam.UpdateSupvPlanParam) {
                //修改
                lambdaQueryWrapper.ne(SupervisionPlanPO::getPlanId, ((SupervisionPlanParam.UpdateSupvPlanParam) supvPlanParam).getPlanId());
            }
        }

        int count = this.count(lambdaQueryWrapper);
        if (count > 0) {
            throw new BusinessException("监督计划名称已存在");
        }

        //判断监督对象类型
   /*     if (StrUtil.isNotBlank(supvPlanParam.getSupvObjType())) {
            DictData dictData = dicDataFeignClient.getDicDataById(supvPlanParam.getSupvType()).getData();
            if (dictData.getCode().equals(DicDataEnum.New_Energy.getCode())) {
                if (StrUtil.isBlank(supvPlanParam.getSupvObjType())) {
                    throw new BusinessException("监督对象类型不可为空");
                }
                if (StrUtil.isBlank(supvPlanParam.getObjType())) {
                    throw new BusinessException("监督对象属性名称不可为空");
                }
                if (Objects.isNull(supvPlanParam.getObjCapacity())) {
                    throw new BusinessException("监督对象协议容量不可为空");
                }
            } else if (!dictData.getCode().equals(DicDataEnum.Technical_Super.getCode())) {
                if (StrUtil.isBlank(supvPlanParam.getSupvObjName())) {
                    throw new BusinessException("监督对象名称不可为空");
                }
                if (StrUtil.isBlank(supvPlanParam.getObjVoltageLevel())) {
                    throw new BusinessException("监督对象电压等级不可为空");
                }

            } else if (!dictData.getCode().equals(DicDataEnum.POWER_QUALITY.getCode())) {
                if (Objects.isNull(supvPlanParam.getObjCapacity())) {
                    throw new BusinessException("监督对象协议容量不可为空");
                }
            }
        }*/
        //判断时间范围
        if(StrUtil.isAllNotBlank(supvPlanParam.getEffectStartTime(),supvPlanParam.getEffectEndTime())||
                StrUtil.isAllNotBlank(supvPlanParam.getEffectStartTime(),supvPlanParam.getReportIssueTime())
        ){
            String problemOcTime1 = supvPlanParam.getProblemOcTime();
            if(StrUtil.isNotBlank(problemOcTime1)){
                //实施开始时间
                DateTime effectStartTime = DateUtil.parse(supvPlanParam.getEffectStartTime(), "yyyy-MM-dd HH:mm:ss");
                //问题发现时间
                DateTime problemOcTime = DateUtil.parse(problemOcTime1, "yyyy-MM-dd HH:mm:ss");
                boolean fly = false;
                if(StrUtil.isNotBlank(supvPlanParam.getEffectEndTime())){
                    //实施结束时间
                    DateTime effectEndTime = DateUtil.parse(supvPlanParam.getEffectEndTime(), "yyyy-MM-dd HH:mm:ss");
                    if (DateUtil.isIn(problemOcTime, effectStartTime, effectEndTime)) {
                        fly = true;
                    }
                }
                if(StrUtil.isNotBlank(supvPlanParam.getReportIssueTime())){
                    //报告出具时间
                    DateTime reportIssueTime = DateUtil.parse(supvPlanParam.getReportIssueTime(), "yyyy-MM-dd HH:mm:ss");
                    if (DateUtil.isIn(problemOcTime, effectStartTime, reportIssueTime)) {
                        fly = true;
                    }
                }
                if (!fly) {
                    throw new BusinessException("问题发现时时间，不在实施开始时间到（实施结束时间/报告出具时间）范围内");
                }
            }
        }
    }
}
