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

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.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.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.device.pq.api.DeptLineFeignClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.api.TerminalBaseClient;
import com.njcn.device.pq.pojo.param.*;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.supervision.enums.SupervisionKeyEnum;
import com.njcn.supervision.enums.SupervisionResponseEnum;
import com.njcn.supervision.enums.UserNatureEnum;
import com.njcn.supervision.mapper.device.SupervisionTempLineDebugPOMapper;
import com.njcn.supervision.mapper.user.UserReportNormalMapper;
import com.njcn.supervision.pojo.param.device.SupervisionTempLineDebugParam;
import com.njcn.supervision.pojo.po.device.SupervisionTempDeviceReport;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineDebugPO;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineReport;
import com.njcn.supervision.pojo.po.user.UserReportNormalPO;
import com.njcn.supervision.pojo.po.user.UserReportPO;
import com.njcn.supervision.pojo.vo.device.SupervisionDevMainReportVO;
import com.njcn.supervision.pojo.vo.device.SupervisionTempLineDebugVO;
import com.njcn.supervision.service.device.SupervisionTempDeviceReportService;
import com.njcn.supervision.service.device.SupervisionTempLineDebugPOService;
import com.njcn.supervision.service.device.SupervisionTempLineReportService;
import com.njcn.supervision.service.user.UserReportPOService;
import com.njcn.supervision.service.user.UserReportProjectPOService;
import com.njcn.supervision.service.user.UserReportSensitivePOService;
import com.njcn.supervision.service.user.UserReportSubstationPOService;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.SysDicTreePO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.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.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description:
 * Date: 2024/5/17  15:26【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class SupervisionTempLineDebugPOServiceImpl extends ServiceImpl<SupervisionTempLineDebugPOMapper, SupervisionTempLineDebugPO> implements SupervisionTempLineDebugPOService {

    private final BpmProcessFeignClient bpmProcessFeignClient;
    private final DeptFeignClient deptFeignClient;
    private final SupervisionTempLineReportService supervisionTempLineReportService;
    private final SupervisionTempDeviceReportService supervisionTempDeviceReportService;
    private final LineFeignClient lineFeignClient;
    private final DictTreeFeignClient dictTreeFeignClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final DeptLineFeignClient deptLineFeignClient;
    private final UserFeignClient userFeignClient;
    private final UserReportPOService userReportPOService;
    private final UserReportProjectPOService userReportProjectPOService;
    private final UserReportSubstationPOService userReportSubstationPOService;
    private final UserReportSensitivePOService userReportSensitivePOService;
    private final UserReportNormalMapper userReportNormalMapper;
    private final TerminalBaseClient terminalBaseClient;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTempLineDebug(SupervisionTempLineDebugParam supervisionTempLineReportParam) {
        //获取临时监测点详情
        SupervisionTempLineReport tempLine = supervisionTempLineReportService.getById(supervisionTempLineReportParam.getId());
        //需要审核报告是否审核通过
        UserReportPO temp = userReportPOService.getById(tempLine.getUserId());
        //是否存在治理方案
        Integer needGovernance = 0;
        if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_POWER_GRID.getCode(),
                        UserNatureEnum.EXTEND_POWER_GRID.getCode()
                ).contains(temp.getUserType())) {
            //电网工程类用户额外数据
            needGovernance = userReportProjectPOService.getById(temp.getId()).getNeedGovernance();
        } else if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                        UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                ).contains(temp.getUserType())) {
            //非线性负荷用户 & 新能源发电站用户

            needGovernance = userReportSubstationPOService.getById(temp.getId()).getNeedGovernance();
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(temp.getUserType())) {
            // 敏感及重要用户
            needGovernance = userReportSensitivePOService.getById(temp.getId()).getNeedGovernance();
        }
        //添加治理评估文件，需先判断入网评估是否审核通过
        List<UserReportNormalPO> list = userReportNormalMapper.selectList(new LambdaQueryWrapper<UserReportNormalPO>()
                .eq(UserReportNormalPO::getUserReportId, temp.getId())
                .eq(UserReportNormalPO::getState, DataStateEnum.ENABLE.getCode())
                .ne(UserReportNormalPO::getStatus, BpmTaskStatusEnum.CANCEL.getStatus())
                .orderByDesc(UserReportNormalPO::getCreateTime)
        );
        if (CollUtil.isNotEmpty(list)) {
            Optional<UserReportNormalPO> netInReport = list.stream().filter(x -> 0 == x.getType()).findFirst();
            if (netInReport.isPresent()) {
                if (netInReport.get().getStatus() != 2) {
                    throw new BusinessException("最新入网验收方案流程,暂未审核通过!");
                }
            } else {
                throw new BusinessException("请填写入网验收方案流程,审核通过后方可操作!");
            }
            if (needGovernance == 1) {
                Optional<UserReportNormalPO> governReport = list.stream().filter(x -> 1 == x.getType()).findFirst();
                if (governReport.isPresent()) {
                    if (governReport.get().getStatus() != 2) {
                        throw new BusinessException("最新治理工程验收方案流程,暂未审核通过!");
                    }
                } else {
                    throw new BusinessException("请填写治理工程验收方案流程,审核通过后方可操作!");
                }
            }
        } else {
            throw new BusinessException("请上传，入网设计方案或者治理工程验收方案");
        }

        SupervisionTempLineDebugPO supervisionTempLineDebugPO = new SupervisionTempLineDebugPO();
        BeanUtils.copyProperties(supervisionTempLineReportParam, supervisionTempLineDebugPO);
        //设置状态
        if (Objects.equals(supervisionTempLineReportParam.getSaveOrCheckflag(), "1")) {
            supervisionTempLineDebugPO.setStatus(BpmTaskStatusEnum.WAIT.getStatus());

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

        }
        supervisionTempLineDebugPO.setState(DataStateEnum.ENABLE.getCode());
        this.saveOrUpdate(supervisionTempLineDebugPO);
        String id = supervisionTempLineDebugPO.getId();
        supervisionTempLineDebugPO = this.baseMapper.selectById(id);
        if (Objects.equals(supervisionTempLineReportParam.getSaveOrCheckflag(), "2")) {
            // 发起 BPM 流程
            Map<String, Object> processInstanceVariables = new HashMap<>(16);
            BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
            bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.TEMP_LINE_DEBUG.getKey());
            bpmProcessInstanceCreateReqDTO.setBusinessKey(id);
            bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(supervisionTempLineReportParam.getStartUserSelectAssignees());
            bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
            //fixme 这边supervisionTempLineDebugPO.getUpdateBy()为null，先改成当前用户
            String processInstanceId = bpmProcessFeignClient.createProcessInstance(RequestUtil.getUserIndex(), bpmProcessInstanceCreateReqDTO).getData();
            // 将工作流的编号，更新到流程单中
            supervisionTempLineDebugPO.setProcessInstanceId(processInstanceId);
            this.updateById(supervisionTempLineDebugPO);
        }
        return id;
    }

    @Override
    public String updateTempLineDebug(SupervisionTempLineDebugParam.SupervisionTempLineDebugUpdateParam supervisionTempLineReportParam) {
        SupervisionTempLineDebugPO supervisionTempLineDebugPO = this.baseMapper.selectById(supervisionTempLineReportParam.getId());
        //判断是否有权限操作
        InstanceUtil.judgeUserPower(RequestUtil.getUserIndex(), supervisionTempLineDebugPO.getCreateBy());
        supervisionTempLineReportParam.setProcessInstanceId(supervisionTempLineDebugPO.getProcessInstanceId());
        supervisionTempLineReportParam.setHistoryInstanceId(supervisionTempLineDebugPO.getHistoryInstanceId());
        BeanUtils.copyProperties(supervisionTempLineReportParam, supervisionTempLineDebugPO);
        supervisionTempLineDebugPO.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        supervisionTempLineDebugPO.setState(DataStateEnum.ENABLE.getCode());
        //处理历史流程id列表
        String historyInstanceIds = InstanceUtil.dealHistoryId(supervisionTempLineDebugPO.getProcessInstanceId(), supervisionTempLineDebugPO.getHistoryInstanceId());
        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.TEMP_LINE_DEBUG.getKey());
        bpmProcessInstanceCreateReqDTO.setBusinessKey(supervisionTempLineDebugPO.getId());
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(supervisionTempLineReportParam.getStartUserSelectAssignees());
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(supervisionTempLineDebugPO.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        supervisionTempLineDebugPO.setProcessInstanceId(processInstanceId);
        //保存历史流程id列表
        supervisionTempLineDebugPO.setHistoryInstanceId(historyInstanceIds);
        this.baseMapper.updateById(supervisionTempLineDebugPO);
        return supervisionTempLineDebugPO.getId();
    }

    @Override
    public Page<SupervisionTempLineDebugVO> getTempLineDeug(SupervisionTempLineDebugParam.SupervisionTempLineDebugQuery supervisionTempLineDebugQuery) {
        QueryWrapper<SupervisionDevMainReportVO> queryWrapper = new QueryWrapper<>();
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        queryWrapper.in("supervision_temp_line_debug.create_by", colleaguesIds)
                .eq("supervision_temp_line_debug.state", DataStateEnum.ENABLE.getCode());
        if (StrUtil.isNotBlank(supervisionTempLineDebugQuery.getOrgNo())) {
            /*获取直接下属子单位*/
            List<String> data = deptFeignClient.getDepSonIdtByDeptId(supervisionTempLineDebugQuery.getOrgNo()).getData();
            queryWrapper.in("supervision_temp_line_report.org_id", data);
        }
        queryWrapper
                .and(CollUtil.isNotEmpty(InstanceUtil.filterTempLineTaskStatus()), w -> w.in("supervision_temp_line_debug.status", InstanceUtil.filterTempLineTaskStatus())
                        .or()
                        .eq("supervision_temp_line_debug.create_by", RequestUtil.getUserIndex())
                );

        if (Objects.nonNull(supervisionTempLineDebugQuery.getStatus())) {
            queryWrapper.eq("supervision_temp_line_debug.status", supervisionTempLineDebugQuery.getStatus());
        }
        if (StrUtil.isNotBlank(supervisionTempLineDebugQuery.getSearchValue())) {
            queryWrapper.and(x -> x
                    .like("supervision_temp_line_report.Power_Substation_Name", supervisionTempLineDebugQuery.getSearchValue())
                    .or()
                    .like("supervision_temp_line_report.connected_bus", supervisionTempLineDebugQuery.getSearchValue())
                    .or()
                    .like("supervision_temp_line_report.monitoring_terminal_name", supervisionTempLineDebugQuery.getSearchValue())
                    .or()
                    .like("supervision_temp_line_report.line_name", supervisionTempLineDebugQuery.getSearchValue())
            );
        }
        //添加上时间范围
        if (Objects.nonNull(supervisionTempLineDebugQuery.getSearchBeginTime()) && Objects.nonNull(supervisionTempLineDebugQuery.getSearchEndTime())) {
            queryWrapper.between("supervision_temp_line_debug.Create_Time",
                    DateUtil.beginOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchBeginTime())),
                    DateUtil.endOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchEndTime())));
        }
        queryWrapper.orderByDesc("supervision_temp_line_debug.Update_Time");
        return this.baseMapper.page(new Page<>(PageFactory.getPageNum(supervisionTempLineDebugQuery), PageFactory.getPageSize(supervisionTempLineDebugQuery)), queryWrapper);
    }

    @Override
    public Page<SupervisionTempLineDebugVO> pageHasDebug(SupervisionTempLineDebugParam.SupervisionTempLineDebugQuery supervisionTempLineDebugQuery) {
        QueryWrapper<SupervisionDevMainReportVO> queryWrapper = new QueryWrapper<>();
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        queryWrapper.in("supervision_temp_line_debug.Create_By", colleaguesIds)
                .eq("supervision_temp_line_debug.state", DataStateEnum.ENABLE.getCode());
        if (StrUtil.isNotBlank(supervisionTempLineDebugQuery.getOrgNo())) {
            /*获取直接下属子单位*/
            List<String> data = deptFeignClient.getDepSonIdtByDeptId(supervisionTempLineDebugQuery.getOrgNo()).getData();
            queryWrapper.in("supervision_temp_line_report.org_id", data);
        }
        queryWrapper
                .and(CollUtil.isNotEmpty(InstanceUtil.filterTempLineTaskStatus()), w -> w.in("supervision_temp_line_debug.status", InstanceUtil.filterTempLineTaskStatus())
                        .or()
                        .eq("supervision_temp_line_debug.create_by", RequestUtil.getUserIndex())
                );
        if (Objects.nonNull(supervisionTempLineDebugQuery.getStatus())) {
            queryWrapper.eq("supervision_temp_line_debug.status", supervisionTempLineDebugQuery.getStatus());
        }
        //添加上时间范围
        if (Objects.nonNull(supervisionTempLineDebugQuery.getSearchBeginTime()) && Objects.nonNull(supervisionTempLineDebugQuery.getSearchEndTime())) {
            queryWrapper.between("supervision_temp_line_debug.Create_Time",
                    DateUtil.beginOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchBeginTime())),
                    DateUtil.endOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchEndTime())));
        }
        queryWrapper.orderByDesc("supervision_temp_line_debug.Update_Time");
        return this.baseMapper.pageHasDebug(new Page<>(PageFactory.getPageNum(supervisionTempLineDebugQuery), PageFactory.getPageSize(supervisionTempLineDebugQuery)), queryWrapper);
    }

    @Override
    public SupervisionTempLineDebugVO getDetailTempLineDebug(String id) {
        SupervisionTempLineDebugVO supervisionTempLineDebugVO = null;
        SupervisionTempLineReport supervisionTempLineReport = supervisionTempLineReportService.getById(id);
        SupervisionTempLineDebugPO supervisionTempLineDebugPO = this.getById(id);
        if (ObjectUtil.isNotNull(supervisionTempLineDebugPO)) {
            supervisionTempLineDebugVO = new SupervisionTempLineDebugVO();
            supervisionTempLineDebugVO.setId(id);
            supervisionTempLineDebugVO.setUserName(supervisionTempLineReport.getUserName());
            supervisionTempLineDebugVO.setConnectedBus(supervisionTempLineReport.getConnectedBus());
            supervisionTempLineDebugVO.setMonitoringTerminalCode(supervisionTempLineReport.getMonitoringTerminalCode());
            supervisionTempLineDebugVO.setMonitoringTerminalName(supervisionTempLineReport.getMonitoringTerminalName());
            supervisionTempLineDebugVO.setPowerSubstationName(supervisionTempLineReport.getPowerSubstationName());

            supervisionTempLineDebugVO.setLineId(supervisionTempLineReport.getLineId());
            supervisionTempLineDebugVO.setLineName(supervisionTempLineReport.getLineName());
            supervisionTempLineDebugVO.setReason(supervisionTempLineDebugPO.getReason());
            supervisionTempLineDebugVO.setProcessInstanceId(supervisionTempLineDebugPO.getProcessInstanceId());
            supervisionTempLineDebugVO.setStatus(supervisionTempLineDebugPO.getStatus());
        }
        return supervisionTempLineDebugVO;
    }

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

    }

    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        BpmInstanceInfo bpmInstanceInfo = new BpmInstanceInfo();
        SupervisionTempLineDebugVO supervisionTempLineDebugVO = this.getDetailTempLineDebug(businessId);
        if (ObjectUtil.isNotNull(supervisionTempLineDebugVO)) {
            bpmInstanceInfo.setHistoryInstanceId(supervisionTempLineDebugVO.getHistoryInstanceId());
            String sign = "";
            if (StrUtil.isNotBlank(supervisionTempLineDebugVO.getPowerSubstationName())) {
                sign = supervisionTempLineDebugVO.getPowerSubstationName()
                        .concat(StrPool.SLASH);
            }
            sign = sign
                    .concat(supervisionTempLineDebugVO.getMonitoringTerminalName())
                    .concat(StrPool.SLASH)
                    .concat(supervisionTempLineDebugVO.getLineName());
            bpmInstanceInfo.setInstanceSign(sign);
        }
        return null;
    }

    @Override
    public Set<String> getAllRejectInstanceIds() {
        Set<String> rejectInstanceIds = new HashSet<>();
        LambdaQueryWrapper<SupervisionTempLineDebugPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SupervisionTempLineDebugPO::getCreateBy, RequestUtil.getUserIndex())
                .eq(SupervisionTempLineDebugPO::getStatus, BpmProcessInstanceStatusEnum.REJECT.getStatus())
                .eq(SupervisionTempLineDebugPO::getState, DataStateEnum.ENABLE.getCode())
                .select(SupervisionTempLineDebugPO::getProcessInstanceId);
        List<SupervisionTempLineDebugPO> supervisionTempLineDebugPOS = this.baseMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(supervisionTempLineDebugPOS)) {
            List<String> result = supervisionTempLineDebugPOS.stream().map(SupervisionTempLineDebugPO::getProcessInstanceId).collect(Collectors.toList());
            rejectInstanceIds.addAll(result);
        }
        return rejectInstanceIds;
    }

    /**
     * @Description: 临时表台账数据同步到实际表中
     * @Author: clam
     * @Date: 2024/5/29
     */
    @Override
    public String ledgerSync(String id) {
        SupervisionTempLineDebugPO byId = this.getById(id);
        if (byId.getStatus() != 2) {
            throw new BusinessException("未审核通过无法同步台账");
        }
        //获取临时监测点详情
        SupervisionTempLineReport tempLine = supervisionTempLineReportService.getById(id);
        //获取关联的设备信息
        SupervisionTempDeviceReport tempDevice = supervisionTempDeviceReportService.getById(tempLine.getMonitoringTerminalCode());
        SyncTerminalParam syncTerminalParam = new SyncTerminalParam();
        //用于绑定监测点部门
        syncTerminalParam.setDeptId(tempDevice.getPowerCompany());
        if (tempDevice.getCustomSubstationFlag() == 0) {
            List<Line> data = lineFeignClient.getBaseLineList(Stream.of(tempDevice.getSubstation()).collect(Collectors.toList())).getData();
            String pids = data.get(0).getPids();
            String[] idsArray = pids.split(",");

            syncTerminalParam.setProjectIndex(idsArray[0]);
            syncTerminalParam.setProvinceIndex(idsArray[1]);
            syncTerminalParam.setGdIndex(idsArray[2]);
            syncTerminalParam.setSubIndex(tempDevice.getSubstation());

        } else {
            //电站可能后期要录 todo
            List<String> data1 = deptLineFeignClient.getLineNodeByDeptId(tempDevice.getPowerCompany()).getData();
            List<Line> data = lineFeignClient.getBaseLineList(data1).getData();
            String pids = data.get(0).getPids();

            String[] idsArray = pids.split(",");

            syncTerminalParam.setProjectIndex(idsArray[0]);
            syncTerminalParam.setProvinceIndex(idsArray[1]);
            syncTerminalParam.setGdIndex(idsArray[2]);

            SubStationParam subStationParam = new SubStationParam();
            subStationParam.setName(tempDevice.getSubstationName());
            subStationParam.setSort(0);
            subStationParam.setScale(tempDevice.getSubstationVoltageLevel());
            subStationParam.setLat(tempDevice.getLatitude());
            subStationParam.setLng(tempDevice.getLongitude());
            syncTerminalParam.setSubStationParam(subStationParam);

        }

        //syncTerminalParam.setSubStationParam();
        DeviceParam deviceParam = new DeviceParam();
        SubVoltageParam subVoltageParam = new SubVoltageParam();
        LineParam lineParam = new LineParam();

        assembleSyncTerminalParam(deviceParam, tempDevice, subVoltageParam, lineParam, tempLine);

        syncTerminalParam.setDeviceParam(deviceParam);
        syncTerminalParam.setSubVoltageParam(subVoltageParam);
        syncTerminalParam.setLineParam(lineParam);

        String substation = terminalBaseClient.terminalSync(syncTerminalParam).getData();

        this.updateProcessStatus(id, 5);
        tempDevice.setSubstation(substation);
        supervisionTempDeviceReportService.updateById(tempDevice);
        return null;
    }

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

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

    }
    private void assembleSyncTerminalParam(DeviceParam deviceParam, SupervisionTempDeviceReport tempDevice, SubVoltageParam subVoltageParam, LineParam lineParam, SupervisionTempLineReport tempLine) {
        //包装device
        deviceParam.setDevIndex(tempDevice.getId());
        deviceParam.setName(tempDevice.getMonitoringTerminalName());
        deviceParam.setDevType(tempDevice.getTerminalType());
        deviceParam.setFrontType(tempDevice.getFrontType());
        deviceParam.setIp(tempDevice.getTerminalIp());
        deviceParam.setPort(Integer.valueOf(tempDevice.getTerminalPort()));
        deviceParam.setNodeId(tempDevice.getFrontEndMachine());
        deviceParam.setSeries(tempDevice.getIdentificationCode());
        deviceParam.setDevKey(tempDevice.getTerminalSecretKey());
        deviceParam.setDevModel(Integer.valueOf(tempDevice.getTerminalModel()));
        deviceParam.setDevDataType(Integer.valueOf(tempDevice.getDataType()));
        deviceParam.setCallFlag(Integer.valueOf(tempDevice.getCommunicationStatus()));
        deviceParam.setManufacturer(tempDevice.getManufacturer());
        deviceParam.setElectroplate(tempDevice.getElectroplatingFunction());
        deviceParam.setLoginTime(LocalDateTimeUtil.format(tempDevice.getCommissioningTime(), DatePattern.NORM_DATE_FORMATTER));
        deviceParam.setThisTimeCheck(LocalDateTimeUtil.format(tempDevice.getCurrentTerminalDetectionTime(), DatePattern.NORM_DATE_FORMATTER));
        deviceParam.setNextTimeCheck(LocalDateTimeUtil.format(tempDevice.getNextTerminalInspectionTime(), DatePattern.NORM_DATE_FORMATTER));
        deviceParam.setContract(tempDevice.getContractNumber());
        deviceParam.setSim(tempDevice.getSimCardNumber());
        deviceParam.setDevSeries(null);
        deviceParam.setDevLocation(tempDevice.getMonitoringDeviceInstallationPosition());
        deviceParam.setDevNo(tempDevice.getManufacturerDeviceNumber());
        deviceParam.setIsAlarm(Integer.valueOf(tempDevice.getAlarmFunction()));
        deviceParam.setSort(0);
        //subVoltageParam

        subVoltageParam.setName(tempLine.getConnectedBus());
        //母线线路号无要求，目前随机生成
        subVoltageParam.setNum(new Random().nextInt(6) + 1);
        //使用监测点的电压等级，监测点和母线是同一个电压等级
        subVoltageParam.setScale(tempLine.getVoltageLevel());
        subVoltageParam.setModel(1);
        subVoltageParam.setSort(0);
        //包装lineParam
        lineParam.setLineIndex(tempLine.getId());
        lineParam.setName(tempLine.getLineName());
        lineParam.setPt1(Float.valueOf(tempLine.getPt1()));
        lineParam.setPt2(Float.valueOf(tempLine.getPt2()));
        lineParam.setCt1(Float.valueOf(tempLine.getCt1()));
        lineParam.setCt2(Float.valueOf(tempLine.getCt2()));
        lineParam.setDevCapacity(tempLine.getDevCapacity());
        lineParam.setShortCapacity(tempLine.getShortCapacity());
        lineParam.setDealCapacity(tempLine.getDealCapacity());
        lineParam.setStandardCapacity(tempLine.getStandardCapacity());
        lineParam.setTimeInterval(tempLine.getTimeInterval());
        //这两个字段统一用BusinessType()来反射取
        lineParam.setLoadType(reflectionLoadType(tempLine.getBusinessType()));
        lineParam.setBusinessType(reflectionBusinessType(tempLine.getBusinessType()));
//        lineParam.setRemark();
//        lineParam.setMonitorId();
        lineParam.setPowerFlag(Integer.valueOf(tempLine.getPointNature()));
        lineParam.setObjName(tempLine.getObjName());
        //目前接线方式在device里，现在使用device代替监测点
        lineParam.setPtType(tempLine.getPtType());
        lineParam.setNum(tempLine.getNum());
        lineParam.setSort(0);
        lineParam.setVoltageDev(tempLine.getVoltageDeviationUpperLimit());
        lineParam.setUvoltageDev(tempLine.getVoltageDeviationLowerLimit());
        lineParam.setPowerSubstationName(tempLine.getPowerSubstationName());
//        lineParam.setCalssificationGrade();
//        lineParam.setSuperiorsSubstation();
        lineParam.setStatFlag(tempLine.getIsStatistical());
//        lineParam.setHangLine();
//        lineParam.setOwner();
//        lineParam.setOwnerDuty();
//        lineParam.setOwnerTel();
        lineParam.setWiringDiagram(tempLine.getMainWiringDiagram());


    }

    private String reflectionBusinessType(String businessType) {
        try {
            SysDicTreePO data = dictTreeFeignClient.queryById(businessType).getData();
            List<DictData> data1 = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.BUSINESS_TYPE.getCode()).getData();
            List<DictData> collect = data1.stream().filter(temp -> temp.getName().equals(data.getRemark())).collect(Collectors.toList());
            return collect.get(0).getId();
        } catch (Exception e) {
            throw new BusinessException("字典转换异常");
        }

    }

    private String reflectionLoadType(String businessType) {
        try {
            SysDicTreePO data = dictTreeFeignClient.queryById(businessType).getData();
            List<DictData> data1 = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.INTERFERENCE_SOURCE_TYPE.getCode()).getData();
            List<DictData> collect = data1.stream().filter(temp -> temp.getName().equals(data.getName())).collect(Collectors.toList());

            return collect.get(0).getId();
        } catch (Exception e) {
            throw new BusinessException("字典转换异常");
        }

    }


}
