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


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.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.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.enums.common.DealStateEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.biz.commApi.CommLineClient;
import com.njcn.device.biz.pojo.dto.LineDTO;
import com.njcn.device.pq.api.LineIntegrityClient;
import com.njcn.device.pq.api.TerminalBaseClient;
import com.njcn.device.pq.pojo.dto.LineDataQualityDTO;
import com.njcn.device.pq.pojo.param.LineDataQualityParam;
import com.njcn.harmonic.api.ReportFeignClient;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.supervision.enums.FlowStatusEnum;
import com.njcn.supervision.enums.SupervisionKeyEnum;
import com.njcn.supervision.enums.SupervisionResponseEnum;
import com.njcn.supervision.enums.SupervisionUserStatusEnum;
import com.njcn.supervision.mapper.device.SupervisionTempLineReportMapper;
import com.njcn.supervision.mapper.device.SupervisionTempLineRunTestMapper;
import com.njcn.supervision.pojo.param.device.SupervisionTempLineRunTestParam;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineReport;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineRunTestPO;
import com.njcn.supervision.pojo.po.device.TempLineRunTestWarning;
import com.njcn.supervision.pojo.po.user.UserReportNormalPO;
import com.njcn.supervision.pojo.po.user.UserReportProjectPO;
import com.njcn.supervision.pojo.po.user.UserReportSensitivePO;
import com.njcn.supervision.pojo.po.user.UserReportSubstationPO;
import com.njcn.supervision.pojo.vo.device.SupervisionTempLineRunTestVO;
import com.njcn.supervision.pojo.vo.device.TempLineRunTestWarningVO;
import com.njcn.supervision.service.device.ISupervisionTempLineRunTestService;
import com.njcn.supervision.service.device.TempLineRunTestWarningService;
import com.njcn.supervision.service.user.*;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2024-05-21
 */
@Service
@RequiredArgsConstructor
public class SupervisionTempLineRunTestServiceImpl extends ServiceImpl<SupervisionTempLineRunTestMapper, SupervisionTempLineRunTestPO> implements ISupervisionTempLineRunTestService {

    private final CommLineClient commLineClient;
    private final SupervisionTempLineReportMapper supervisionTempLineReportMapper;
    private final LineIntegrityClient lineIntegrityClient;
    private final BpmProcessFeignClient bpmProcessFeignClient;
    private final UserReportPOService userReportPOService;
    private final UserReportProjectPOService userReportProjectPOService;
    private final UserReportSubstationPOService userReportSubstationPOService;
    private final UserReportSensitivePOService userReportSensitivePOService;
    private final IUserReportNormalService iUserReportNormalService;
    private final ReportFeignClient reportFeignClient;
    private final FileStorageUtil fileStorageUtil;
    private final TerminalBaseClient terminalBaseClient;
    private final TempLineRunTestWarningService tempLineRunTestWarningService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRunTest(SupervisionTempLineRunTestParam supervisionTempLineRunTestParam) {
        List<String> ids = supervisionTempLineRunTestParam.getLineIds();

        List<SupervisionTempLineReport> supervisionTempLineReportList = supervisionTempLineReportMapper.selectBatchIds(ids);
        List<String> lineIds = supervisionTempLineReportList.stream().map(SupervisionTempLineReport::getId).collect(Collectors.toList());

        List<LineDTO> lineDTOList = commLineClient.getLineDetailBatch(lineIds).getData();
        if (lineIds.size() != lineDTOList.size()) {
            throw new BusinessException(CommonResponseEnum.FAIL, "请联系管理员检查监测点唯一编号是否匹配");
        }

        //校验
        //查询干扰源用户建档是否治理治理审核通过，才能去试运行，否则要提示出来;
        List<String> userIds = supervisionTempLineReportList.stream().map(SupervisionTempLineReport::getUserId).collect(Collectors.toList());
        List<UserReportProjectPO> list = userReportProjectPOService.lambdaQuery().in(UserReportProjectPO::getId, userIds).eq(UserReportProjectPO::getNeedGovernance, 1).list();
        List<UserReportSubstationPO> list2 = userReportSubstationPOService.lambdaQuery().in(UserReportSubstationPO::getId, userIds).eq(UserReportSubstationPO::getNeedGovernance, 1).list();
        List<UserReportSensitivePO> list3 = userReportSensitivePOService.lambdaQuery().in(UserReportSensitivePO::getId, userIds).eq(UserReportSensitivePO::getNeedGovernance, 1).list();
        List<String> tempUserIds = list.stream().map(UserReportProjectPO::getId).collect(Collectors.toList());
        tempUserIds.addAll(list2.stream().map(UserReportSubstationPO::getId).collect(Collectors.toList()));
        tempUserIds.addAll(list3.stream().map(UserReportSensitivePO::getId).collect(Collectors.toList()));


        if (CollectionUtil.isNotEmpty(tempUserIds)) {
            for (int i = tempUserIds.size() - 1; i >= 0; i--) {
                List<UserReportNormalPO> list1 = iUserReportNormalService.lambdaQuery().eq(UserReportNormalPO::getUserReportId, tempUserIds.get(i)).list();
                if (CollectionUtil.isNotEmpty(list1)) {
                    //为空则没有治理工程不需要移除，存在审核未通过的也不要移除,只有全是2的移除
                    list1 = list1.stream().filter(temp -> !Objects.equals(temp.getStatus(), 2)).collect(Collectors.toList());
                    if (CollectionUtil.isEmpty(list1)) {
                        tempUserIds.remove(i);
                    }
                }
            }

        }
        if (CollectionUtil.isNotEmpty(tempUserIds)) {
            String userNames = supervisionTempLineReportList.stream()
                    .filter(temp -> tempUserIds.contains(temp.getUserId()))
                    .map(SupervisionTempLineReport::getUserName)
                    .collect(Collectors.joining(", "));
            throw new BusinessException(CommonResponseEnum.FAIL, "存在关联干扰源用户:" + userNames + "需要治理通过才可以进行试运行");
        }


        List<SupervisionTempLineRunTestPO> supervisionTempLineRunTestPOList = this.list(new LambdaQueryWrapper<SupervisionTempLineRunTestPO>().in(SupervisionTempLineRunTestPO::getId, ids).ne(SupervisionTempLineRunTestPO::getStatus, BpmTaskStatusEnum.REJECT.getStatus()));
        if (CollUtil.isNotEmpty(supervisionTempLineRunTestPOList)) {
            String msg = assMsg(supervisionTempLineReportList, supervisionTempLineRunTestPOList);
            throw new BusinessException(CommonResponseEnum.FAIL, msg);
        }

        List<SupervisionTempLineRunTestPO> poList = new ArrayList<>();
        for (SupervisionTempLineReport item : supervisionTempLineReportList) {
            SupervisionTempLineRunTestPO supervisionTempLineRunTestPO = new SupervisionTempLineRunTestPO();
            supervisionTempLineRunTestPO.setId(item.getId());
            supervisionTempLineRunTestPO.setLineId(item.getLineId());
            supervisionTempLineRunTestPO.setState(DataStateEnum.ENABLE.getCode());
            supervisionTempLineRunTestPO.setStatus(9);
            supervisionTempLineRunTestPO.setTestRunState(1);
            supervisionTempLineRunTestPO.setSuitRate(0.00);
            supervisionTempLineRunTestPO.setOnlineRate(0.00);
            supervisionTempLineRunTestPO.setIntegrityRate(0.00);
            supervisionTempLineRunTestPO.setTestRunTime(supervisionTempLineRunTestParam.getStartTime() + "--" + supervisionTempLineRunTestParam.getEndTime());
            if (Objects.nonNull(supervisionTempLineRunTestParam.getOperateType()) && supervisionTempLineRunTestParam.getOperateType() == 1) {
                SupervisionTempLineRunTestPO testPo = this.getById(item.getId());
                String historyInstanceIds = InstanceUtil.dealHistoryId(testPo.getProcessInstanceId(), testPo.getHistoryInstanceId());
                supervisionTempLineRunTestPO.setHistoryInstanceId(historyInstanceIds);
            }
            poList.add(supervisionTempLineRunTestPO);
        }
        this.saveOrUpdateBatch(poList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateRunTest(SupervisionTempLineRunTestParam.SupervisionTempLineRunTestUpdateParam supervisionTempLineRunTestParam) {
        SupervisionTempLineRunTestPO supervisionTempLineRunTestPO = this.baseMapper.selectById(supervisionTempLineRunTestParam.getId());
        supervisionTempLineRunTestParam.setProcessInstanceId(supervisionTempLineRunTestPO.getProcessInstanceId());
        supervisionTempLineRunTestParam.setHistoryInstanceId(supervisionTempLineRunTestPO.getHistoryInstanceId());
        BeanUtil.copyProperties(supervisionTempLineRunTestParam, supervisionTempLineRunTestPO);
        if (Objects.isNull(supervisionTempLineRunTestPO)) {
            throw new BusinessException(CommonResponseEnum.FAIL, "无法查询到该信息,请检查信息是否存在!");
        }
        //1.先判断是否发送告警单，没有则不允许重新发送
        List<TempLineRunTestWarningVO> tempLineRunTestWarningVOS = this.baseMapper.selectResults(supervisionTempLineRunTestParam.getId());
        long count = tempLineRunTestWarningVOS.stream().filter(x -> StrUtil.isBlank(x.getWarningId())).count();
        if (count > 0) {
            throw new BusinessException(CommonResponseEnum.FAIL, "请先发送告警单信息!");
        }
        //2.判断告警单，是否有未审核通过则不允许重新发送
        if (CollUtil.isNotEmpty(tempLineRunTestWarningVOS)) {
            Integer status = tempLineRunTestWarningVOS.get(0).getStatus();
            if (!status.equals(FlowStatusEnum.APPROVE.getCode())) {
                throw new BusinessException(CommonResponseEnum.FAIL, "请处理告警单信息，处理审核通过才可重新发送!");
            }
            String startTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 1), DatePattern.NORM_DATE_PATTERN);
            String endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 3), DatePattern.NORM_DATE_PATTERN);
            supervisionTempLineRunTestPO.setTestRunTime(startTime + "--" + endTime);
        }
        supervisionTempLineRunTestPO.setStatus(9);
        supervisionTempLineRunTestPO.setTestRunReport("");
        supervisionTempLineRunTestPO.setState(DataStateEnum.ENABLE.getCode());
        supervisionTempLineRunTestPO.setTestRunState(DataStateEnum.ENABLE.getCode());

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void isTestRunStartOrEnd(HttpServletResponse response) {
        LocalDateTime time = LocalDateTime.now();
        LambdaQueryWrapper<SupervisionTempLineRunTestPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SupervisionTempLineRunTestPO::getTestRunState, 1)
                .eq(SupervisionTempLineRunTestPO::getState, DataStateEnum.ENABLE.getCode());
        List<SupervisionTempLineRunTestPO> supervisionTempLineRunTestPOList = this.list(lambdaQueryWrapper);
        List<SupervisionTempLineRunTestPO> usePoList = new ArrayList<>();
        for (SupervisionTempLineRunTestPO item : supervisionTempLineRunTestPOList) {
            String endTime = item.getTestRunTime().split("--")[1];
            LocalDateTime end = LocalDate.parse(endTime, DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN)).atTime(23, 59, 59);
            if (end.isBefore(time)) {
                //结束时间在当前时间之前，则已经执行完试运行，开始组装审核条件
                usePoList.add(item);
            }
        }
        if (CollUtil.isNotEmpty(usePoList)) {
            List<String> lineRunTestIds = usePoList.stream().map(SupervisionTempLineRunTestPO::getId).collect(Collectors.toList());
            List<SupervisionTempLineReport> supervisionTempLineReports = supervisionTempLineReportMapper.selectBatchIds(lineRunTestIds);
            Map<String, String> lineReportMap = supervisionTempLineReports.stream().filter(x -> StrUtil.isNotBlank(x.getMainWiringDiagram())).collect(Collectors.toMap(SupervisionTempLineReport::getId, SupervisionTempLineReport::getMainWiringDiagram));
            Map<String, List<SupervisionTempLineRunTestPO>> map = usePoList.stream().collect(Collectors.groupingBy(SupervisionTempLineRunTestPO::getTestRunTime));
            map.forEach((key, val) -> {
                String startTime = key.split("--")[0];
                String endTime = key.split("--")[1];
                List<String> ids = val.stream().map(SupervisionTempLineRunTestPO::getId).collect(Collectors.toList());
                LineDataQualityParam lineDataQualityParam = LineDataQualityParam.builder().lineIds(ids).beginTime(startTime).endTime(endTime).build();
                List<LineDataQualityDTO> lineDataQualityDTOList = lineIntegrityClient.getLineDataQuality(lineDataQualityParam).getData();
                Map<String, LineDataQualityDTO> qualityDTOMap = lineDataQualityDTOList.stream().collect(Collectors.toMap(LineDataQualityDTO::getLineId, Function.identity()));
                for (SupervisionTempLineRunTestPO supervisionTempLineRunTestPO : val) {
                    // 将工作流的编号，更新到流程单中
                    SupervisionTempLineRunTestPO po = new SupervisionTempLineRunTestPO();
                    if (StrUtil.isNotBlank(supervisionTempLineRunTestPO.getProcessInstanceId())) {
                        String historyInstanceIds = InstanceUtil.dealHistoryId(supervisionTempLineRunTestPO.getProcessInstanceId(),
                                supervisionTempLineRunTestPO.getHistoryInstanceId());
                        po.setHistoryInstanceId(historyInstanceIds);
                    }
                    // 发起 BPM 流程
                    Map<String, Object> processInstanceVariables = new HashMap<>(16);
                    BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
                    bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.LINE_RUN_TEST.getKey());
                    bpmProcessInstanceCreateReqDTO.setBusinessKey(supervisionTempLineRunTestPO.getId());
                    bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(new HashMap<>(16));
                    bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
                    String processInstanceId = bpmProcessFeignClient.createProcessInstance(supervisionTempLineRunTestPO.getCreateBy(), bpmProcessInstanceCreateReqDTO).getData();
                    po.setProcessInstanceId(processInstanceId);
                    po.setId(supervisionTempLineRunTestPO.getId());
                    po.setStatus(1);
                    po.setTestRunState(2);
                    if (qualityDTOMap.containsKey(supervisionTempLineRunTestPO.getId())) {
                        LineDataQualityDTO dto = qualityDTOMap.get(supervisionTempLineRunTestPO.getId());
                        po.setOnlineRate(dto.getOnlineRate());
                        po.setIntegrityRate(dto.getIntegrityRate());
                        po.setSuitRate(dto.getSuitRate());
                        MockMultipartFile file= new MockMultipartFile("file", new byte[0]);
                        if (lineReportMap.containsKey(supervisionTempLineRunTestPO.getId())) {
                            String url = lineReportMap.get(supervisionTempLineRunTestPO.getId());
                            InputStream fileStream = null;
                            try {
                                fileStream = fileStorageUtil.getFileStream(url.substring(url.indexOf("/")));
                                file = new MockMultipartFile("file", url.substring(url.lastIndexOf("/") + 1), MediaType.IMAGE_PNG_VALUE, fileStream);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (fileStream != null) {
                                        fileStream.close(); // 关闭InputStream
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        try {
                            startTime = DateUtil.beginOfDay(DateUtil.parse(startTime)).toString();
                            endTime = DateUtil.endOfDay(DateUtil.parse(endTime)).toString();
                            String fileUrl = reportFeignClient.exportModelJB(
                                    startTime,
                                    endTime,
                                    0,
                                    dto.getLineId(),
                                    dto.getLineName(),
                                    "",
                                    "",
                                    true, file).getData();
                            po.setTestRunReport(fileUrl);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        po.setOnlineRate(0.00);
                        po.setIntegrityRate(0.00);
                        po.setSuitRate(0.00);
                    }
                    this.baseMapper.updateById(po);
                }
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcessStatus(String businessKey, String reason, Integer status) {
        SupervisionTempLineRunTestPO supervisionTempLineRunTestPO = this.baseMapper.selectById(businessKey);
        //如果状态为审批通过
        if (status.equals(BpmProcessInstanceStatusEnum.APPROVE.getStatus())) {
            userReportPOService.updateUserStatus(businessKey, SupervisionUserStatusEnum.PRODUCT.getCode());
            terminalBaseClient.terminalSyncRunFly(businessKey);
        }
        //如果状态为审批不通过,则插入一条数据标识问题信息
        if (status.equals(BpmProcessInstanceStatusEnum.REJECT.getStatus())) {
            TempLineRunTestWarning warning = new TempLineRunTestWarning();
            warning.setId(IdWorker.get32UUID());
            warning.setLineRunId(businessKey);
            warning.setReason(reason);
            warning.setDealState(DealStateEnum.UNSOLVED.getCode());
            warning.setTestRunReport(supervisionTempLineRunTestPO.getTestRunReport());
            tempLineRunTestWarningService.save(warning);
        }
        supervisionTempLineRunTestPO.setStatus(status);
        this.updateById(supervisionTempLineRunTestPO);
    }

    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        BpmInstanceInfo bpmInstanceInfo = new BpmInstanceInfo();
        SupervisionTempLineRunTestVO supervisionTempLineRunTestVO = this.getRunTestById(businessId);
        if(ObjectUtil.isNotNull(supervisionTempLineRunTestVO)){
            bpmInstanceInfo.setHistoryInstanceId(supervisionTempLineRunTestVO.getHistoryInstanceId());
            String sign = supervisionTempLineRunTestVO.getPowerSubstationName()
                    .concat(StrPool.SLASH)
                    .concat(supervisionTempLineRunTestVO.getMonitoringTerminalName())
                    .concat(StrPool.SLASH)
                    .concat(supervisionTempLineRunTestVO.getConnectedBus())
                    .concat(StrPool.SLASH)
                    .concat(supervisionTempLineRunTestVO.getLineName());
            bpmInstanceInfo.setInstanceSign(sign);
        }
        return null;
    }

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

    @Override
    public SupervisionTempLineRunTestVO getRunTestById(String id) {
        return this.baseMapper.getRunTestInfo(id);
    }

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

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

    private String assMsg(List<SupervisionTempLineReport> supervisionTempLineReportList, List<SupervisionTempLineRunTestPO> supervisionTempLineRunTestPOList) {
        StringBuilder builder = new StringBuilder();
        Map<String, SupervisionTempLineReport> map = supervisionTempLineReportList.stream().collect(Collectors.toMap(SupervisionTempLineReport::getId, Function.identity()));
        List<String> ids = supervisionTempLineRunTestPOList.stream().map(SupervisionTempLineRunTestPO::getId).collect(Collectors.toList());
        for (String id : ids) {
            if (map.containsKey(id)) {
                builder.append(map.get(id).getPowerSubstationName()).append("_").append(map.get(id).getLineName()).append(";");
            }
        }
        return builder.toString();
    }


}
