package com.hdkj.lt.mq.service.plan.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hdkj.lt.base.constants.DictConstants;
import com.hdkj.lt.core.bizms.modle.po.DwdShbDsSwitchBase;
import com.hdkj.lt.core.bizms.modle.po.FhzgSwitchProtectionSettings;
import com.hdkj.lt.core.bizms.modle.po.plan.*;
import com.hdkj.lt.core.sys.dao.FhzgOrganSuffixMapper;
import com.hdkj.lt.core.sys.model.dto.FeederCacheDTO;
import com.hdkj.lt.core.sys.service.DwdShbDsFeederBaseService;
import com.hdkj.lt.core.sys.service.SwitchProtectionSettingsService;
import com.hdkj.lt.modle.dto.jsty.*;
import com.hdkj.lt.mq.entity.po.FhzgPlanPowerCut;
import com.hdkj.lt.mq.mapper.plan.FhzgPlanAnalyzeCalculateDecudeMapper;
import com.hdkj.lt.mq.service.base.IDwdShbDsSwitchBaseService;
import com.hdkj.lt.mq.service.plan.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 计划停电转供方案信息表 服务实现类
 *
 * @author zhuzhe
 * @since 2025-05-23
 */
@Service
@Slf4j
public class FhzgPlanAnalyzeCalculateDecudeServiceImpl implements FhzgPlanAnalyzeCalculateDecudeService {

    @Autowired
    FhzgPlanAnalyzeCalculateDecudeMapper fhzgPlanAnalyzeCalculateDecudeMapper;

    @Autowired
    FhzgOrganSuffixMapper fhzgOrganSuffixMapper;
    @Autowired
    IPlanTransferSchemeSwitchingLoopSwCurrentDetailService planTransferSchemeSwitchingLoopSwCurrentDetailService;
    @Autowired
    IPlanTransferSchemeSwitchingLoopSegCurrentDetailService planTransferSchemeSwitchingLoopSegCurrentDetailService;
    @Autowired
    DwdShbDsFeederBaseService dwdShbDsFeederBaseService;
    @Autowired
    IDwdShbDsSwitchBaseService dwdShbDsSwitchBaseService;
    @Autowired
    SwitchProtectionSettingsService fhzgSwitchProtectionSettingsService;
    @Autowired
    IPlanTransferSchemeSwitchingFinalSegCurrentDetailService planTransferSchemeSwitchingFinalSegCurrentDetailService;
    @Autowired
    IPlanTransferSchemeSwitchingFinalSwCurrentDetailService planTransferSchemeSwitchingFinalSwCurrentDetailService;


    @Override
    public void analyzeCalculateDecudeData(Long planId, List<SupplyAreaDTO> supplyAreaList) {
        // 根据计划id 删除 用户 和 开关段信息
        fhzgPlanAnalyzeCalculateDecudeMapper.deleteTransferUserByPlanId(planId);
        fhzgPlanAnalyzeCalculateDecudeMapper.deleteSwitchSectionByPlanId(planId);
        //根据计划id 查询线路名
        FhzgPlanPowerCut fhzgPlanPowerCut = fhzgPlanAnalyzeCalculateDecudeMapper.getLineNameByPlanId(planId);
        String lineId = fhzgPlanPowerCut.getLineId();
        for (int i = 0; i < supplyAreaList.size(); i++) {
            SupplyAreaDTO supplyAreaDTO = supplyAreaList.get(i);
            // 带转供开关段--开始开关
            BreakerInfoDTO isolateBreaker = supplyAreaDTO.getIsolateBreaker();

            // 线路和首开关id
            String breakerPSRID = isolateBreaker.getBreakerPSRID();

            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(planId, null));
            // 根据线路和首开关 查询开关段并保存  todo  现在场景只有首开关，后面的场景有终止开关，数据结构未定
            List<FhzgPlanAwaitTransferSwitchSection> switchSectionList = fhzgPlanAnalyzeCalculateDecudeMapper.getSwitchSection(lineId, breakerPSRID, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));

            if (switchSectionList != null && switchSectionList.size() > 0) {
                switchSectionList.stream().forEach(e -> e.setPlanId(planId).setAreaPsrId(breakerPSRID).setSwitchName(e.getStartSwitchName()));
                fhzgPlanAnalyzeCalculateDecudeMapper.saveSwitchSectionBatch(switchSectionList);
            }
        }

        // 更新开关段负荷
        // fhzgPlanAnalyzeCalculateDecudeMapper.updateSwitchSectionSwitchLoads();
    }

    /**
     * 合环校验
     *
     * @param planId
     * @param xferPlanMap
     */
    @Override
    public void analyzeXferPlanList(Long planId, Map<Long, XferPlanDTO> xferPlanMap, LoopCheckRuleDTO loopCheckRuledto,
                                    Map<String, FeederCheckRuleDTO> feederCheckRuleDTOMap, List<FeederCheckRuleDTO> feederCheckRuleList) {
        // 查询本侧线路
        FhzgPlanPowerCut fhzgPlanPowerCut = fhzgPlanAnalyzeCalculateDecudeMapper.getLineNameByPlanId(planId);
        Snowflake snowflake = IdUtil.getSnowflake(1,1);
        for (Long schemeId : xferPlanMap.keySet()) {
            // 根据方案ID获取方案数据
            XferPlanDTO xferPlanDTO = xferPlanMap.get(schemeId);
            // 获取开关动作列表
            List<BreakerInfoDTO> breakerOperationOrderList = xferPlanDTO.getBreakerOperationOrderListList().get(0);
            // 合环校验的参数配置
            LoopCheckRuleDTO loopCheckRule = Optional.ofNullable(loopCheckRuledto).orElse(new LoopCheckRuleDTO());

            //转供方案开关及设备区域信息
            List<XferSupplyAreaDTO> xferSupplyAreaList = xferPlanDTO.getXferSupplyAreaList();
            Map<String, XferSupplyAreaDTO> mapSupplyArea = xferSupplyAreaList.stream()
                    .filter(k -> ObjectUtils.isNotEmpty(k.getLinkSwitch()))
                    .collect(Collectors.toMap(k -> k.getLinkSwitch().getPsrID(), v -> v));
            int seq = 0;
            boolean orderIdIsAllNull = breakerOperationOrderList.stream().allMatch(i -> i.getOrderId() == null);
            for (BreakerInfoDTO breakerInfoDTO : breakerOperationOrderList) {
                FhzgPlanTransferSchemeSwitchingSequence switchingSequence = new FhzgPlanTransferSchemeSwitchingSequence();
                Long switchingSequenceId = snowflake.nextId();
                switchingSequence.setId(switchingSequenceId);
                switchingSequence.setSchemeId(schemeId);
                switchingSequence.setSwitchId(breakerInfoDTO.getBreakerPSRID());
                switchingSequence.setSwitchName(breakerInfoDTO.getBreakerName());
                switchingSequence.setSwitchType("0");
                // 是 三遥 开关
                if (StringUtils.isNotEmpty(breakerInfoDTO.getAutoType()) && breakerInfoDTO.getAutoType().equals("auto3Y")) {
                    switchingSequence.setIsAutoSwitch("1");
                } else {
                    switchingSequence.setIsAutoSwitch("0");
                }
                switchingSequence.setOperationContent(String.valueOf(breakerInfoDTO.getBreakerOperation()));
                //操作顺序
                if (orderIdIsAllNull) {
                    switchingSequence.setSwitchingSeq(seq++);
                } else {
                    switchingSequence.setSwitchingSeq(breakerInfoDTO.getOrderId());
                }
                //switchingSequence.setLoopCloseCheck();
                // 保存开关顺序

                // 合环校验和终态校验
                XferSupplyAreaDTO xferSupplyAreaDTO = mapSupplyArea.get(breakerInfoDTO.getBreakerPSRID());

                if (xferSupplyAreaDTO != null) {
                    HotCheckDTO hotCheck = Optional.ofNullable(xferSupplyAreaDTO.getHotCheck()).orElse(new HotCheckDTO());
                    FinalCheckDTO finalCheck = Optional.ofNullable(xferSupplyAreaDTO.getFinalCheck()).orElse(new FinalCheckDTO());

                    LinkLineDTO linkLineInfo = Optional.ofNullable(xferSupplyAreaDTO.getLinkLineInfo()).orElse(new LinkLineDTO());
                    // 合环校验
                    FhzgPlanTransferSchemeSwitchingLoopCheck switchingLoopCheck = new FhzgPlanTransferSchemeSwitchingLoopCheck();
                    switchingLoopCheck.setId(snowflake.nextId());
                    switchingLoopCheck.setSwitchingId(switchingSequenceId);
                    // 本侧线路
                    switchingLoopCheck.setLineId(fhzgPlanPowerCut.getLineId());
                    switchingLoopCheck.setLineName(fhzgPlanPowerCut.getLineName());
                    // 对侧线路
                    switchingLoopCheck.setOppositeLineId(linkLineInfo.getPsrID());
                    switchingLoopCheck.setOppositeLineName(linkLineInfo.getName());
                    // 相角差
                    Double busAngleDif = hotCheck.getBusAngleDif();
                    if (busAngleDif != null) {
                        switchingLoopCheck.setPhaseAngleDiff(String.valueOf(busAngleDif));
                    }
                    Double angleDifMargin = loopCheckRule.getAngleDifMargin();
                    if (angleDifMargin != null) {
                        switchingLoopCheck.setPhaseAngleDiffThreshold(angleDifMargin.toString());
                    }
                    //相角差判定值 固定值是我们传给推演平台 15，他们再返回给我们
                    if (busAngleDif != null && angleDifMargin != null) {
                        int a = Double.compare(Math.abs(busAngleDif), angleDifMargin);
                        if (a < 0) {  // 校验通过
                            switchingLoopCheck.setPhaseAngleDiffCheck("1");
                        } else {
                            switchingLoopCheck.setPhaseAngleDiffCheck("0");
                        }
                    } else {
                        switchingLoopCheck.setPhaseAngleDiffCheck("0");
                    }
                    // 本侧电压
                    Double acbvol = hotCheck.getAcbVol();
                    // 对侧线路 名称
                    String bfdPsrName = linkLineInfo.getName();
                    //对侧电压
                    Double bcbvol = hotCheck.getBcbVol();
                    //两侧线路压差
                    Double cbVolDif = hotCheck.getCbVolDif();
                    // 压差判定值
                    Double volDifMargin = loopCheckRule.getVolDifMargin();
                    if (acbvol != null) {
                        switchingLoopCheck.setLineVoltage(acbvol.toString());
                    }
                    if (bcbvol != null) {
                        switchingLoopCheck.setOppositeLineVoltage(bcbvol.toString());
                    }
                    if (cbVolDif != null) {
                        switchingLoopCheck.setLineVoltageDiff(String.valueOf(Math.abs(cbVolDif)));
                    }
                    if (volDifMargin != null) {
                        volDifMargin = volDifMargin / 100 * 10;//5%*10kv =0.5kV  压差判定值做转换
                        switchingLoopCheck.setLineVoltageDiffThreshold(volDifMargin.toString());
                    }
                    if (cbVolDif != null && volDifMargin != null) {
                        //压差判定值怎么判断 5%*10kv =0.5kV  这个值是我们传给推演平台，他们用完再返回，应该是固定值0.5kV
                        int a = Double.compare(Math.abs(cbVolDif), volDifMargin);
                        if (a < 0) {  // 校验通过
                            switchingLoopCheck.setLineVoltageDiffCheck("1");
                        } else {
                            switchingLoopCheck.setLineVoltageDiffCheck("0");
                        }
                    } else {
                        switchingLoopCheck.setLineVoltageDiffCheck("0");
                    }
                    //整线校验 环流值
                    Double loopCur = hotCheck.getLoopCur();
                    if (loopCur != null) {
                        switchingLoopCheck.setLoopCurrent(loopCur.toString());
                    }
                    //整线校验本侧额定电流
                    Double afdrateCurrent = hotCheck.getAfdrateCurrent();
//                    Double afdrateCurrent = feederCheckRuleDTOMap.get(fhzgPlanPowerCut.getLineId()).getRateCurrent();
//                    if (afdrateCurrent != null) {
//                        switchingLoopCheck.setAfdrateCurrent(afdrateCurrent.toString());
//                    }
                    //整线校验本侧合环电流
                    Double afdCurLoop = hotCheck.getAfdCurLoop();
                    if (afdCurLoop != null) {
                        switchingLoopCheck.setAfdCurLoop(afdCurLoop.toString());
                    }
                    //整线校验对侧额定电流
                    //Double rateCurrent = linkLineInfo.getRateCurrent();
                    Double rateCurrent = feederCheckRuleDTOMap.get(linkLineInfo.getPsrID()).getRateCurrent();
                    if (rateCurrent != null) {
                        switchingLoopCheck.setRateCurrent(rateCurrent.toString());
                    }
                    //整线校验对侧合环电流
                    Double bfdCurLoop = hotCheck.getBfdCurLoop();
                    if (bfdCurLoop != null) {
                        switchingLoopCheck.setBfdCurLoop(bfdCurLoop.toString());
                    }
                    //环流校验不再作为最终的合环校验结果，全部设置成通过
                    switchingLoopCheck.setLoopCurrentCheck("1");
                    //开关电流明细 保存
                    //将终态校验中的开关校验列表分组
                    List<FinalBreakerSafetyCheckResultDTO> finalBreakerSafetyCheckResultDTOList = finalCheck.getBreakerSafetyCheckResult();
                    Map<String, List<String>> finalBreakerSafetyMap = new HashMap<>();
                    if (CollUtil.isNotEmpty(finalBreakerSafetyCheckResultDTOList)) {
                        finalBreakerSafetyMap = finalBreakerSafetyCheckResultDTOList.stream().filter(e -> StrUtil.isNotBlank(e.getCheckType()))
                                .collect(Collectors.groupingBy(FinalBreakerSafetyCheckResultDTO::getCheckType,
                                        Collectors.mapping(FinalBreakerSafetyCheckResultDTO::getBreakerPSRID, Collectors.toList())));
                    }
                    List<CbResultDTO> cbResultList = hotCheck.getCbResult();
                    List<String> loopCheckSwitchPsrIdList_1 = finalBreakerSafetyMap.get("1");//取checkType=’1‘的开关用来过滤
                    List<String> loopCheckSwitchPsrIdList_3 = finalBreakerSafetyMap.get("3");//取checkType=’3‘的开关用来过滤
                    List<String> loopcheckSwitchPsrIdList = new ArrayList<>();
                    if (CollUtil.isNotEmpty(loopCheckSwitchPsrIdList_1)) {
                        loopcheckSwitchPsrIdList.addAll(loopCheckSwitchPsrIdList_1);
                    }
                    if (CollUtil.isNotEmpty(loopCheckSwitchPsrIdList_3)) {
                        loopcheckSwitchPsrIdList.addAll(loopCheckSwitchPsrIdList_3);
                    }
                    // 合环校验开关电流明细新增 判断是为不通过逻辑，1.hotCheck中的cbResult  包含在loopcheckSwitchPsrIdList中的 或 2.cbResult loopI >=中的开关所属导线额定电流 或3.cbResult loopI >=开关额定电流
                    if (CollUtil.isNotEmpty(cbResultList)) {
                        List<FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail> checkFailcbResultList = buildLoopSwCurrent(cbResultList, switchingSequenceId, hotCheck, feederCheckRuleList, loopcheckSwitchPsrIdList);
                        if (CollUtil.isNotEmpty(checkFailcbResultList)) {
                            //保存合环路径开关电流校验结果列表
                            planTransferSchemeSwitchingLoopSwCurrentDetailService.saveBatch(checkFailcbResultList);
//                          saveSwCurrentDetail(cbResultList, switchingSequenceId, hotCheck);
                            switchingLoopCheck.setSwitchCurrentCheck("0");//过滤出来有数据说明就有校验不通过的开关
                        } else {
                            switchingLoopCheck.setSwitchCurrentCheck("1");//没有过滤到校验不通过的数据
                        }
                    } else {
                        switchingLoopCheck.setSwitchCurrentCheck("1");//如果没传值默认设置为“通过”
                    }
                    //导线电流明细 保存
                    List<SegResultDTO> segResultDTOList = hotCheck.getSegResult();
                    List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetailList = new ArrayList<>();
                    if (CollUtil.isNotEmpty(segResultDTOList)) {
                        fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetailList = saveSegCurrentDetail(segResultDTOList, switchingSequenceId, hotCheck);
                    }
                    //合环校验的导线段电流校验结果，只要有一条校验结果不通过则为不通过
                    if (CollUtil.isNotEmpty(fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetailList)) {
                        List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> failList = fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetailList.stream().filter(e -> StrUtil.equals("0", e.getSegmentCurrentCheck())).collect(Collectors.toList());
                        switchingLoopCheck.setSegmentCurrentCheck(failList.size() > 0 ? "0" : "1");
                    } else {
                        switchingLoopCheck.setSegmentCurrentCheck("1");
                    }

                    //开关的合环校验结果
                    if (switchingLoopCheck.getPhaseAngleDiffCheck() != null && switchingLoopCheck.getPhaseAngleDiffCheck().equals("1")
                            && switchingLoopCheck.getLineVoltageDiffCheck() != null && switchingLoopCheck.getLineVoltageDiffCheck().equals("1")
                            && switchingLoopCheck.getSwitchCurrentCheck() != null && switchingLoopCheck.getSwitchCurrentCheck().equals("1")
                            && switchingLoopCheck.getSegmentCurrentCheck() != null && switchingLoopCheck.getSegmentCurrentCheck().equals("1")) {
                        switchingSequence.setLoopCloseCheck(1);
                    } else {
                        switchingSequence.setLoopCloseCheck(0);
                    }
                    fhzgPlanAnalyzeCalculateDecudeMapper.saveSwitchingLoopCheck(switchingLoopCheck);

                    //终态校验
                    FhzgPlanTransferSchemeSwitchingFinalCheck switchingFinalCheck = new FhzgPlanTransferSchemeSwitchingFinalCheck();
                    switchingFinalCheck.setId(snowflake.nextId());
                    switchingFinalCheck.setSwitchingId(switchingSequenceId);
                    // 本侧线路
                    switchingFinalCheck.setLineId(fhzgPlanPowerCut.getLineId());
                    switchingFinalCheck.setLineName(fhzgPlanPowerCut.getLineName());
                    // 对侧线路
                    switchingFinalCheck.setOppositeLineId(linkLineInfo.getPsrID());
                    switchingFinalCheck.setOppositeLineName(linkLineInfo.getName());

                    //对侧线路 额定电流
                    switchingFinalCheck.setAllowMaxCurrent(feederCheckRuleDTOMap.get(linkLineInfo.getPsrID()).getRateCurrent() == null ? "" : String.valueOf(feederCheckRuleDTOMap.get(linkLineInfo.getPsrID()).getRateCurrent()));
                    // 对侧预估最大电流
                    switchingFinalCheck.setEstimateMaxCurrent(linkLineInfo.getPlanMaxCurrentValue() == null ? "" : linkLineInfo.getPlanMaxCurrentValue().toString());
                    // 对侧预估最大负载率
                    switchingFinalCheck.setEstimateMaxLoadFactor(linkLineInfo.getPlanMaxCurrentLoad() == null ? "" : linkLineInfo.getPlanMaxCurrentLoad().toString());
                    //负载率判断值
                    Double feederLoadRate = new Double(80);
                    switchingFinalCheck.setLoadFactorThreshold(feederLoadRate.toString());
//                    Double feederLoadRate = loopCheckRule.getFeederLoadRate();
//                    if (feederLoadRate != null) {
//                        switchingFinalCheck.setLoadFactorThreshold(feederLoadRate.toString());
//                    }
                    //负载率校验结果  对侧预计负载率<负载率判定值即为通过
                    Double planMaxCurrentLoad = linkLineInfo.getPlanMaxCurrentLoad();
                    if (feederLoadRate != null && planMaxCurrentLoad != null) {
                        switchingFinalCheck.setLoadFactorCheck(feederLoadRate.compareTo(planMaxCurrentLoad) > 0 ? "1" : "0");
                    } else {
                        switchingFinalCheck.setLoadFactorCheck("0");
                    }
                    // 终态校验开关电流 保存
                    if (CollUtil.isNotEmpty(cbResultList)) {
                        //在校验不通过的开关列表中筛选出终态校验不通过的数据checkType ='2'||'3'
                        List<FinalBreakerSafetyCheckResultDTO> finalBreakerSafetyCheckResultDTO = finalCheck.getBreakerSafetyCheckResult();
                        List<String> finalChekPsrIdList = new ArrayList<>();
                        if (CollUtil.isNotEmpty(finalBreakerSafetyCheckResultDTO)) {
                            finalChekPsrIdList = finalBreakerSafetyCheckResultDTO.stream().filter(e -> StrUtil.equals(e.getCheckType(), "2") || StrUtil.equals(e.getCheckType(), "3")).map(FinalBreakerSafetyCheckResultDTO::getBreakerPSRID).collect(Collectors.toList());
                        }

                        List<PlanTransferSchemeSwitchingFinalSwCurrentDetail> finalSwCurrentDetailList = buildFinalSwCurrent(cbResultList, switchingSequenceId, hotCheck, feederCheckRuleList, finalChekPsrIdList);
                        if (CollUtil.isNotEmpty(finalSwCurrentDetailList)) {
                            //只要有数据则说明开关 电流校验不通过
                            switchingFinalCheck.setSwitchCurrentCheck("0");
                            planTransferSchemeSwitchingFinalSwCurrentDetailService.saveBatch(finalSwCurrentDetailList);
//                            saveFinalSwCurrentDetail(switchingSequenceId, finalBreakerSafetyCheckResultFinalDTO);
                        } else {
                            switchingFinalCheck.setSwitchCurrentCheck("1");
                        }
                    } else {
                        switchingFinalCheck.setSwitchCurrentCheck("1");//没有校验失败的数据
                    }
                    //保存终态校验导线电流明细
                    List<FinalSegResultDTO> finalSegResultDTOList = finalCheck.getSegResult();
                    if (CollUtil.isNotEmpty(finalSegResultDTOList)) {
                        saveFinalSegCurrentDetail(switchingSequenceId, finalSegResultDTOList, fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetailList);
                        switchingFinalCheck.setSegmentCurrentCheck("0");//只要有数据就是校验不通过
                    } else {
                        //保存开关段裕度值最小的数据， 取hotCheck 中的segResult ,裕度值 = rateCurrent - maxAfter24hI
                        saveMarginValueFinalSegCurrentDetail(switchingSequenceId, hotCheck.getSegResult(), hotCheck);
                        switchingFinalCheck.setSegmentCurrentCheck("1");//没有校验失败的数据
                    }
                    // 设置终态校验结果 ， 对侧最大负载率校验结果，加终态校验开关校验结果，导线校验结果不需要
                    String loadFactorCheck = switchingFinalCheck.getLoadFactorCheck();
                    String switchCurrentCheck = switchingFinalCheck.getSwitchCurrentCheck();
                    String segmentCurrentCheck = switchingFinalCheck.getSegmentCurrentCheck();
                    switchingSequence.setFinalStateCheck(1);//设置终态校验默认为通过
                    // 只要有对侧最大负载率校验结果或者开关校验结果不通过则开关动作顺序校验结果为不通过
                    if (StrUtil.equals(loadFactorCheck, "0") || StrUtil.equals(switchCurrentCheck, "0") || StrUtil.equals(segmentCurrentCheck, "0")) {
                        switchingSequence.setFinalStateCheck(0);
                    }
                    fhzgPlanAnalyzeCalculateDecudeMapper.saveSwitchingFinalCheck(switchingFinalCheck);
                }
                fhzgPlanAnalyzeCalculateDecudeMapper.saveSwitchingSequence(switchingSequence);
            }
        }
    }

    //构建合环路径开关电流，待保存的校验不通过数据集合
    private List<PlanTransferSchemeSwitchingFinalSwCurrentDetail> buildFinalSwCurrent(List<CbResultDTO> cbResultList, Long switchingId, HotCheckDTO hotCheck, List<FeederCheckRuleDTO> feederCheckRuleList, List<String> finalChekPsrIdList) {
        List<PlanTransferSchemeSwitchingFinalSwCurrentDetail> list = new ArrayList<>();
        //查询开关的设置信息
        List<String> psrIdList = cbResultList.stream().filter(e -> StrUtil.isNotBlank(e.getPsrID())).map(CbResultDTO::getPsrID).collect(Collectors.toList());
        List<FhzgSwitchProtectionSettings> switchProtectionSettingsList = fhzgSwitchProtectionSettingsService.list(new LambdaQueryWrapper<FhzgSwitchProtectionSettings>().in(FhzgSwitchProtectionSettings::getDevicePrsId, psrIdList));
        Map<String, FhzgSwitchProtectionSettings> stringFhzgSwitchProtectionSettingsMap = switchProtectionSettingsList.stream().filter(e -> StrUtil.isNotBlank(e.getDevicePrsId())).collect(Collectors.toMap(FhzgSwitchProtectionSettings::getDevicePrsId, Function.identity(), (k1, k2) -> k2));
        //查询开关的额定电流
        List<DwdShbDsSwitchBase> dwdShbDsSwitchBaseList = dwdShbDsSwitchBaseService.list(new LambdaQueryWrapper<DwdShbDsSwitchBase>().in(DwdShbDsSwitchBase::getPsrId, psrIdList));
        Map<String, DwdShbDsSwitchBase> dwdShbDsSwitchBaseMap = dwdShbDsSwitchBaseList.stream().collect(Collectors.toMap(DwdShbDsSwitchBase::getPsrId, Function.identity(), (k1, k2) -> k2));
        //所属线路额定电流Map
        Map<String, Double> feederRateCurrentMap = new HashMap<>();
        if (CollUtil.isNotEmpty(feederCheckRuleList)) {
            feederCheckRuleList.forEach(i -> feederRateCurrentMap.put(i.getFeederId(), i.getRateCurrent()));
        }
        Map<String, Double> finalFeederRateCurrentMap = feederRateCurrentMap;
        cbResultList.forEach(e -> {
            String currentThreshold = stringFhzgSwitchProtectionSettingsMap.get(e.getPsrID()) == null ? null : stringFhzgSwitchProtectionSettingsMap.get(e.getPsrID()).getOc3Value();
            PlanTransferSchemeSwitchingFinalSwCurrentDetail flanTransferSchemeSwitchingFinalSwCurrentDetail = new PlanTransferSchemeSwitchingFinalSwCurrentDetail();
            flanTransferSchemeSwitchingFinalSwCurrentDetail.setSwitchingId(switchingId)
                    .setSwitchId(e.getPsrID())
                    .setSwitchName(e.getName())
                    .setSwitchCurrentCheck("0")//列表中取出的数据都是校验不通过的数据
                    .setMaxAfter24hI(e.getMaxAfter24hI() == null ? null : e.getMaxAfter24hI().toString())
                    .setCurrentThreshold(currentThreshold)//判定值 过流III段
                    .setCreateTime(LocalDateTime.now());
            setLineIdAndName(e, flanTransferSchemeSwitchingFinalSwCurrentDetail, hotCheck);
            //开关所属线路额定电流设置值
            Double lineRateCurrent = finalFeederRateCurrentMap.get(flanTransferSchemeSwitchingFinalSwCurrentDetail.getLineId());
            flanTransferSchemeSwitchingFinalSwCurrentDetail.setLineRateCurrent(lineRateCurrent == null ? null : lineRateCurrent.toString());
            //查询开关额定电流
            DwdShbDsSwitchBase dwdShbDsSwitchBase = dwdShbDsSwitchBaseMap.get(e.getPsrID());
            flanTransferSchemeSwitchingFinalSwCurrentDetail.setSwitchRateCurrent(dwdShbDsSwitchBase == null ? null : dwdShbDsSwitchBase.getRatedCurrent() == null ? null : dwdShbDsSwitchBase.getRatedCurrent().toString());
            list.add(flanTransferSchemeSwitchingFinalSwCurrentDetail);
        });
        //过滤出校验不通过的数据 1.hotCheck中的cbResult  包含在loopcheckSwitchPsrIdList中的 或 2.cbResult loopI >=中的开关所属导线额定电流 或3.cbResult loopI >=开关额定电流
        List<PlanTransferSchemeSwitchingFinalSwCurrentDetail> checkFaillist = list.stream().filter(e -> finalSwCheck(e, finalChekPsrIdList)).map(e -> e.setSwitchCurrentCheck("0")).collect(Collectors.toList());
        //对于判断阈值缺失的默认校验通过，但是需要在页面展示
        List<PlanTransferSchemeSwitchingFinalSwCurrentDetail> checkLostList = new ArrayList<>();
        list.forEach(i -> {
            if (StringUtils.isBlank(i.getCurrentThreshold()) || StringUtils.isBlank(i.getLineRateCurrent()) || StringUtils.isBlank(i.getSwitchRateCurrent())) {
                i.setSwitchCurrentCheck("1");
                checkLostList.add(i);
            }
        });
        planTransferSchemeSwitchingFinalSwCurrentDetailService.saveBatch(checkLostList);
        return checkFaillist;
    }

    //返回值为true代表校验不通过，返回false 代表校验通过.1.hotCheck中的cbResult  包含在loopcheckSwitchPsrIdList中的 或 2.cbResult loopI >=中的开关所属导线额定电流 或3.cbResult loopI >=开关额定电流
    private boolean finalSwCheck(PlanTransferSchemeSwitchingFinalSwCurrentDetail planTransferSchemeSwitchingFinalSwCurrentDetail, List<String> finalChekPsrIdList) {
        //任一判定阈值缺失 默认校验通过
        if (StringUtils.isBlank(planTransferSchemeSwitchingFinalSwCurrentDetail.getCurrentThreshold()) || StringUtils.isBlank(planTransferSchemeSwitchingFinalSwCurrentDetail.getLineRateCurrent()) || StringUtils.isBlank(planTransferSchemeSwitchingFinalSwCurrentDetail.getSwitchRateCurrent())) {
            return false;
        }
        if (finalChekPsrIdList.contains(planTransferSchemeSwitchingFinalSwCurrentDetail.getSwitchId())) {
            return true;
        }
        //loopI
        String loopCloseCurrent = planTransferSchemeSwitchingFinalSwCurrentDetail.getLoopCloseCurrent();
        String lineRateCurrent = planTransferSchemeSwitchingFinalSwCurrentDetail.getLineRateCurrent();
        String switchRateCurrent = planTransferSchemeSwitchingFinalSwCurrentDetail.getSwitchRateCurrent();
        if (StrUtil.isBlank(loopCloseCurrent) || StrUtil.isBlank(lineRateCurrent) || Double.parseDouble(loopCloseCurrent) >= Double.parseDouble(lineRateCurrent)) {
            return true;
        }
        if (StrUtil.isBlank(loopCloseCurrent) || StrUtil.isBlank(switchRateCurrent) || Double.parseDouble(loopCloseCurrent) >= Double.parseDouble(switchRateCurrent)) {
            return true;
        }
        return false;
    }

    private void setLineIdAndName(CbResultDTO cbResultDTO, PlanTransferSchemeSwitchingFinalSwCurrentDetail planTransferSchemeSwitchingFinalSwCurrentDetail, HotCheckDTO hotCheck) {
        if (StrUtil.equals(cbResultDTO.getWhichSide(), "B")) {
            planTransferSchemeSwitchingFinalSwCurrentDetail.setLineId(hotCheck.getBfdPSRID());
            planTransferSchemeSwitchingFinalSwCurrentDetail.setLineName(hotCheck.getBfdName());
        } else if (StrUtil.equals(cbResultDTO.getWhichSide(), "A") || StrUtil.equals(cbResultDTO.getWhichSide(), "M")) {
            planTransferSchemeSwitchingFinalSwCurrentDetail.setLineId(hotCheck.getAfdPSRID());
            String afdPSRID = hotCheck.getAfdPSRID();
            if (StrUtil.isNotBlank(afdPSRID)) {
                FeederCacheDTO feederCacheDTO = dwdShbDsFeederBaseService.getFeederByCacheOrDb(afdPSRID);
                planTransferSchemeSwitchingFinalSwCurrentDetail.setLineName(feederCacheDTO.getName());
            }
        } else {
            log.info("whichSide类型错误");
        }
    }

    //终态校验 开关电流校验结果
    private void saveFinalSwCurrentDetail(Long switchingId, List<FinalBreakerSafetyCheckResultDTO> finalBreakerSafetyCheckResultList) {
        //查询开关的设置信息
        List<String> psrIdList = finalBreakerSafetyCheckResultList.stream().filter(e -> StrUtil.isNotBlank(e.getBreakerPSRID())).map(FinalBreakerSafetyCheckResultDTO::getBreakerPSRID).collect(Collectors.toList());
        List<FhzgSwitchProtectionSettings> switchProtectionSettingsList = fhzgSwitchProtectionSettingsService.list(new LambdaQueryWrapper<FhzgSwitchProtectionSettings>().in(FhzgSwitchProtectionSettings::getDevicePrsId, psrIdList));
        Map<String, String> stringFhzgSwitchProtectionSettingsMap = switchProtectionSettingsList.stream().collect(Collectors.toMap(FhzgSwitchProtectionSettings::getDevicePrsId, FhzgSwitchProtectionSettings::getOc3Value, (k1, k2) -> k2));
        List<PlanTransferSchemeSwitchingFinalSwCurrentDetail> list = new ArrayList<>();
        finalBreakerSafetyCheckResultList.forEach(e -> {
            String currentThreshold = stringFhzgSwitchProtectionSettingsMap.get(e.getBreakerPSRID());
            PlanTransferSchemeSwitchingFinalSwCurrentDetail flanTransferSchemeSwitchingFinalSwCurrentDetail = new PlanTransferSchemeSwitchingFinalSwCurrentDetail();
            flanTransferSchemeSwitchingFinalSwCurrentDetail.setSwitchingId(switchingId)
                    .setSwitchId(e.getBreakerPSRID())
                    .setSwitchName(e.getName())
                    .setLineName(e.getFeederName())
                    .setSwitchCurrentCheck("0")//列表中取出的数据都是校验不通过的数据
                    .setMaxAfter24hI(e.getMaxAfter24hI() == null ? null : e.getMaxAfter24hI().toString())
                    .setCurrentThreshold(currentThreshold)//判定值
                    .setCreateTime(LocalDateTime.now());
            list.add(flanTransferSchemeSwitchingFinalSwCurrentDetail);
        });
        planTransferSchemeSwitchingFinalSwCurrentDetailService.saveBatch(list);
    }

    //终态校验 导线电流校验结果
    private void saveFinalSegCurrentDetail(Long switchingId, List<FinalSegResultDTO> finalSegResultDTOList, List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetailList) {
        List<PlanTransferSchemeSwitchingFinalSegCurrentDetail> list = new ArrayList<>();
        finalSegResultDTOList.forEach(e -> {
            PlanTransferSchemeSwitchingFinalSegCurrentDetail planTransferSchemeSwitchingFinalSegCurrentDetail = new PlanTransferSchemeSwitchingFinalSegCurrentDetail();
            planTransferSchemeSwitchingFinalSegCurrentDetail.setSwitchingId(switchingId)
                    .setSegmentId(e.getSegmentPSRID())
                    .setSegmentName(e.getName())
                    .setSegmentCurrentCheck("0")//列表中取出的数据都是校验不通过的数据
                    .setMaxAfter24hI(e.getMaxAfterI() == null ? null : e.getMaxAfterI().toString())
                    .setRatedI(e.getRatedI() == null ? null : e.getRatedI().toString())
                    .setLineName(e.getFeederName());
            list.add(planTransferSchemeSwitchingFinalSegCurrentDetail);
        });
        planTransferSchemeSwitchingFinalSegCurrentDetailService.saveBatch(list);
    }

    //终态校验 导线段电流保存 裕度值最小的数据
    private void saveMarginValueFinalSegCurrentDetail(Long switchingId, List<SegResultDTO> segResult, HotCheckDTO hotCheck) {
        List<PlanTransferSchemeSwitchingFinalSegCurrentDetail> list = new ArrayList<>();
        segResult.forEach(e -> {
            PlanTransferSchemeSwitchingFinalSegCurrentDetail planTransferSchemeSwitchingFinalSegCurrentDetail = new PlanTransferSchemeSwitchingFinalSegCurrentDetail();
            planTransferSchemeSwitchingFinalSegCurrentDetail.setSwitchingId(switchingId)
                    .setSegmentId(e.getPsrID())
                    .setSegmentName(e.getName())
                    .setSegmentCurrentCheck("1")//进入该保存逻辑的都是校验通过的数据
                    .setMaxAfter24hI(e.getMaxAfter24hI() == null ? null : String.valueOf(Math.abs(e.getMaxAfter24hI())))
                    .setRatedI(e.getRateCurrent() == null ? null : e.getRateCurrent().toString())
                    .setMarginValue(e.getMaxAfter24hI() != null && e.getRateCurrent() != null ? BigDecimal.valueOf(e.getRateCurrent()).subtract(BigDecimal.valueOf(Math.abs(e.getMaxAfter24hI()))).setScale(6, RoundingMode.HALF_UP).toString() : null);//裕度值计算=rateCurrent-maxAfter24hI 保留6位小数
            setLineIdAndName(e, planTransferSchemeSwitchingFinalSegCurrentDetail, hotCheck);
            list.add(planTransferSchemeSwitchingFinalSegCurrentDetail);
        });
        PlanTransferSchemeSwitchingFinalSegCurrentDetail planTransferSchemeSwitchingFinalSegCurrentDetail = list.stream().filter(e -> StrUtil.isNotBlank(e.getMarginValue())).sorted(Comparator.comparingDouble(e -> Double.parseDouble(e.getMarginValue()))).findFirst().orElse(null);
        if (planTransferSchemeSwitchingFinalSegCurrentDetail != null) {
            planTransferSchemeSwitchingFinalSegCurrentDetailService.save(planTransferSchemeSwitchingFinalSegCurrentDetail);
        }
    }

    private void setLineIdAndName(SegResultDTO SegResultDTO, PlanTransferSchemeSwitchingFinalSegCurrentDetail planTransferSchemeSwitchingFinalSegCurrentDetail, HotCheckDTO hotCheck) {
        if (StrUtil.equals(SegResultDTO.getWhichSide(), "B")) {
            planTransferSchemeSwitchingFinalSegCurrentDetail.setLineId(hotCheck.getBfdPSRID());
            planTransferSchemeSwitchingFinalSegCurrentDetail.setLineName(hotCheck.getBfdName());
        } else if (StrUtil.equals(SegResultDTO.getWhichSide(), "A") || StrUtil.equals(SegResultDTO.getWhichSide(), "M")) {
            planTransferSchemeSwitchingFinalSegCurrentDetail.setLineId(hotCheck.getAfdBPSRID());
            String afdPSRID = hotCheck.getAfdPSRID();
            if (StrUtil.isNotBlank(afdPSRID)) {
                FeederCacheDTO feederCacheDTO = dwdShbDsFeederBaseService.getFeederByCacheOrDb(afdPSRID);
                planTransferSchemeSwitchingFinalSegCurrentDetail.setLineName(feederCacheDTO.getName());
            }
        } else {
            log.info("whichSide类型错误");
        }
    }

    //构建合环路径开关电流，待保存的校验不通过数据集合
    private List<FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail> buildLoopSwCurrent(List<CbResultDTO> cbResultList, Long switchingId, HotCheckDTO hotCheck, List<FeederCheckRuleDTO> feederCheckRuleList, List<String> finalChekPsrIdList) {
        List<FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail> list = new ArrayList<>();
        //查询开关的设置信息
        List<String> psrIdList = cbResultList.stream().filter(e -> StrUtil.isNotBlank(e.getPsrID())).map(CbResultDTO::getPsrID).collect(Collectors.toList());
        List<FhzgSwitchProtectionSettings> switchProtectionSettingsList = fhzgSwitchProtectionSettingsService.list(new LambdaQueryWrapper<FhzgSwitchProtectionSettings>().in(FhzgSwitchProtectionSettings::getDevicePrsId, psrIdList));
        Map<String, FhzgSwitchProtectionSettings> stringFhzgSwitchProtectionSettingsMap = switchProtectionSettingsList.stream().filter(e -> StrUtil.isNotBlank(e.getDevicePrsId())).collect(Collectors.toMap(FhzgSwitchProtectionSettings::getDevicePrsId, Function.identity(), (k1, k2) -> k2));
        //查询开关的额定电流
        List<DwdShbDsSwitchBase> dwdShbDsSwitchBaseList = dwdShbDsSwitchBaseService.list(new LambdaQueryWrapper<DwdShbDsSwitchBase>().in(DwdShbDsSwitchBase::getPsrId, psrIdList));
        Map<String, DwdShbDsSwitchBase> dwdShbDsSwitchBaseMap = dwdShbDsSwitchBaseList.stream().collect(Collectors.toMap(DwdShbDsSwitchBase::getPsrId, Function.identity(), (k1, k2) -> k2));
        //所属线路额定电流Map
        Map<String, Double> feederRateCurrentMap = new HashMap<>();
        if (CollUtil.isNotEmpty(feederCheckRuleList)) {
            feederCheckRuleList.forEach(i -> feederRateCurrentMap.put(i.getFeederId(), i.getRateCurrent()));
        }
        Map<String, Double> finalFeederRateCurrentMap = feederRateCurrentMap;
        cbResultList.forEach(e -> {
            FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail = new FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail();
            FhzgSwitchProtectionSettings fhzgSwitchProtectionSettings = stringFhzgSwitchProtectionSettingsMap.get(e.getPsrID());
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail
                    .setSwitchName(e.getName())
                    .setSwitchId(e.getPsrID())
                    .setSwitchingId(switchingId)
                    .setLineId(e.getWhichSide())
                    .setPreLoopCloseCurrent(e.getBeforeI() == null ? null : e.getBeforeI().toString())
                    .setLoopCloseCurrent(e.getLoopI() == null ? null : String.valueOf(Math.abs(e.getLoopI())))//合环中电流可能为负数 转换成绝对值
                    .setLoopOpenCurrent(e.getAfterI() == null ? null : e.getAfterI().toString())
                    .setCurrentThreshold(fhzgSwitchProtectionSettings == null ? null : fhzgSwitchProtectionSettings.getOc3Value())//开关环流判断值
                    .setOc2Value(fhzgSwitchProtectionSettings == null ? null : fhzgSwitchProtectionSettings.getOc2Value())//过流II段
                    .setCreateTime(LocalDateTime.now());
            setLineIdAndName(e, fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail, hotCheck);
            //开关所属线路额定电流设置值
            Double lineRateCurrent = finalFeederRateCurrentMap.get(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getLineId());
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.setLineRateCurrent(lineRateCurrent == null ? null : lineRateCurrent.toString());
            //查询开关额定电流
            DwdShbDsSwitchBase dwdShbDsSwitchBase = dwdShbDsSwitchBaseMap.get(e.getPsrID());
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.setSwitchRateCurrent(dwdShbDsSwitchBase == null ? null : dwdShbDsSwitchBase.getRatedCurrent() == null ? null : dwdShbDsSwitchBase.getRatedCurrent().toString());
            list.add(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail);
        });
        //过滤出校验不通过的数据 1.hotCheck中的cbResult  包含在loopcheckSwitchPsrIdList中的 或 2.cbResult loopI >=中的开关所属导线额定电流 或3.cbResult loopI >=开关额定电流
        List<FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail> checkFaillist = list.stream().filter(e -> loopSwCheck(e, finalChekPsrIdList)).map(e -> e.setSwitchCurrentCheck("0")).collect(Collectors.toList());
        //对于判断阈值缺失的默认校验通过，但是需要在页面展示
        List<FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail> checkLostList = new ArrayList<>();
        list.forEach(i -> {
            if (StringUtils.isBlank(i.getCurrentThreshold()) || StringUtils.isBlank(i.getLineRateCurrent()) || StringUtils.isBlank(i.getSwitchRateCurrent())) {
                i.setSwitchCurrentCheck("1");
                checkLostList.add(i);
            }
        });
        planTransferSchemeSwitchingLoopSwCurrentDetailService.saveBatch(checkLostList);
        return checkFaillist;
    }

    //返回值为true代表校验不通过，返回false 代表校验通过.1.hotCheck中的cbResult  包含在loopcheckSwitchPsrIdList中的 或 2.cbResult loopI >=中的开关所属导线额定电流 或3.cbResult loopI >=开关额定电流
    private boolean loopSwCheck(FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail, List<String> finalChekPsrIdList) {
        if (StringUtils.isBlank(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getCurrentThreshold()) || StringUtils.isBlank(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getLineRateCurrent()) || StringUtils.isBlank(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getSwitchRateCurrent())) {
            return false;
        }
        if (finalChekPsrIdList.contains(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getSwitchId())) {
            return true;
        }
        //loopI
        String loopCloseCurrent = fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getLoopCloseCurrent();
        String lineRateCurrent = fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getLineRateCurrent();
        String switchRateCurrent = fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getSwitchRateCurrent();
        if (StrUtil.isBlank(loopCloseCurrent) || StrUtil.isBlank(lineRateCurrent) || Double.parseDouble(loopCloseCurrent) >= Double.parseDouble(lineRateCurrent)) {
            return true;
        }
        if (StrUtil.isBlank(loopCloseCurrent) || StrUtil.isBlank(switchRateCurrent) || Double.parseDouble(loopCloseCurrent) >= Double.parseDouble(switchRateCurrent)) {
            return true;
        }
        return false;
    }

    //合环校验 保存开关电流校验列表, 取finalCheck中 checkType ='1'的数据 然后cbResultList中匹配数据
    private boolean saveSwCurrentDetail(List<CbResultDTO> cbResultList, Long switchingId, HotCheckDTO hotCheck) {
        AtomicBoolean switchCurrentCheck = new AtomicBoolean(true);
        List<FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail> list = new ArrayList<>();
        //查询开关的设置信息
        List<String> psrIdList = cbResultList.stream().filter(e -> StrUtil.isNotBlank(e.getPsrID())).map(CbResultDTO::getPsrID).collect(Collectors.toList());
        List<FhzgSwitchProtectionSettings> switchProtectionSettingsList = fhzgSwitchProtectionSettingsService.list(new LambdaQueryWrapper<FhzgSwitchProtectionSettings>().in(FhzgSwitchProtectionSettings::getDevicePrsId, psrIdList));
        Map<String, FhzgSwitchProtectionSettings> stringFhzgSwitchProtectionSettingsMap = switchProtectionSettingsList.stream().collect(Collectors.toMap(FhzgSwitchProtectionSettings::getDevicePrsId, Function.identity(), (k1, k2) -> k2));
        cbResultList.forEach(e -> {
            FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail = new FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail();
            FhzgSwitchProtectionSettings fhzgSwitchProtectionSettings = stringFhzgSwitchProtectionSettingsMap.get(e.getPsrID());
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail
                    .setSwitchName(e.getName())
                    .setSwitchId(e.getPsrID())
                    .setSwitchingId(switchingId)
                    .setLineId(e.getWhichSide())
                    .setPreLoopCloseCurrent(e.getBeforeI() == null ? null : e.getBeforeI().toString())
                    .setLoopCloseCurrent(e.getLoopI() == null ? null : String.valueOf(Math.abs(e.getLoopI())))//合环中电流可能为负数 转换成绝对值
                    .setLoopOpenCurrent(e.getAfterI() == null ? null : e.getAfterI().toString())
                    .setCurrentThreshold(fhzgSwitchProtectionSettings == null ? null : fhzgSwitchProtectionSettings.getOc3Value())//开关环流判断值
                    .setOc2Value(fhzgSwitchProtectionSettings == null ? null : fhzgSwitchProtectionSettings.getOc2Value())//过流II段
                    .setSwitchCurrentCheck("0")   //此处数据都是校验不通过的数据
                    .setCreateTime(LocalDateTime.now());
            setLineIdAndName(e, fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail, hotCheck);
            if (StrUtil.equals(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.getSwitchCurrentCheck(), "0")) {
                switchCurrentCheck.set(false);//只要有一条数据校验不通过，则返回false
            }
            list.add(fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail);
        });
        planTransferSchemeSwitchingLoopSwCurrentDetailService.saveBatch(list);
        return switchCurrentCheck.get();
    }

    private void setLineIdAndName(CbResultDTO cbResultDTO, FhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail, HotCheckDTO hotCheck) {
        if (StrUtil.equals(cbResultDTO.getWhichSide(), "B")) {
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.setLineId(hotCheck.getBfdPSRID());
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.setLineName(hotCheck.getBfdName());
        } else if (StrUtil.equals(cbResultDTO.getWhichSide(), "A") || StrUtil.equals(cbResultDTO.getWhichSide(), "M")) {
            fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.setLineId(hotCheck.getAfdPSRID());
            String afdPSRID = hotCheck.getAfdPSRID();
            if (StrUtil.isNotBlank(afdPSRID)) {
                FeederCacheDTO feederCacheDTO = dwdShbDsFeederBaseService.getFeederByCacheOrDb(afdPSRID);
                fhzgPlanTransferSchemeSwitchingLoopSwCurrentDetail.setLineName(feederCacheDTO.getName());
            }
        } else {
            log.info("whichSide类型错误");
        }
    }

    //合环校验 保存导线电流校验列。数据新增过滤逻辑，如果存在校验不通过的数据则只需要保存校验不通过的数据，如果全部为校验通过的数据，则只保存裕度值最小的数据，裕度值计算=rateCurrent-loopI。
    private List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> saveSegCurrentDetail(List<SegResultDTO> segResultList, Long switchingId, HotCheckDTO hotCheck) {
        List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> list = new ArrayList<>();
        List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> checkLostList = new ArrayList<>();

        segResultList.forEach(e -> {
            FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail = new FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail();
            fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail
                    .setSegmentName(e.getName())
                    .setSegmentId(e.getPsrID())
                    .setSwitchingId(switchingId)
                    .setLineId(e.getWhichSide())
                    .setPreLoopCloseCurrent(e.getBeforeI() == null ? null : e.getBeforeI().toString())
                    .setLoopCloseCurrent(e.getLoopI() == null ? null : String.valueOf(Math.abs(e.getLoopI())))//合环中电流可能为负数 转换成绝对值
                    .setLoopOpenCurrent(e.getAfterI() == null ? null : e.getAfterI().toString())
                    .setSegmentRatedAmpacity(e.getRateCurrent() == null ? null : e.getRateCurrent().toString())//额定电流
                    .setSegmentCurrentCheck(e.getLoopI() == null || e.getRateCurrent() == null ? "0" : (Double.compare(Math.abs(e.getLoopI()), e.getRateCurrent()) < 0) ? "1" : "0")//合环中电流<导线额定电流（标定载流量）
                    .setMarginValue(e.getLoopI() != null && e.getRateCurrent() != null ? BigDecimal.valueOf(e.getRateCurrent()).subtract(BigDecimal.valueOf(Math.abs(e.getLoopI()))).setScale(6, RoundingMode.HALF_UP).toString() : null)//裕度值计算=rateCurrent-loopI 保留6位小数
                    .setCreateTime(LocalDateTime.now());
            setLineIdAndName(e, fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail, hotCheck);
            //缺失判定阈值时 默认校验通过
            if (e.getRateCurrent() == null) {
                fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail.setSegmentCurrentCheck("1");
                checkLostList.add(fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail);
            }
            list.add(fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail);
        });
        //保存判定阈值缺失的数据
        planTransferSchemeSwitchingLoopSegCurrentDetailService.saveBatch(checkLostList);
        //裕度值,过滤
        List<FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail> faileList = list.stream().filter(e -> StrUtil.equals(e.getSegmentCurrentCheck(), "0")).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(faileList)) {
            //如果存在校验不通过的数据则只需要保存校验不通过的数据
            planTransferSchemeSwitchingLoopSegCurrentDetailService.saveBatch(faileList);
        } else {
            //全部都是校验通过的数据。如果全部为校验通过的数据，则只保存裕度值最小的数据，裕度值计算=rateCurrent-loopI
            FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail = list.stream().filter(e -> StrUtil.isNotBlank(e.getMarginValue())).sorted(Comparator.comparingDouble(e -> Double.parseDouble(e.getMarginValue()))).findFirst().orElse(null);
            if (fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail != null) {
                planTransferSchemeSwitchingLoopSegCurrentDetailService.save(fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail);
            }
        }
        return list;
    }

    private void setLineIdAndName(SegResultDTO segResultDTO, FhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail, HotCheckDTO hotCheck) {
        if (StrUtil.equals(segResultDTO.getWhichSide(), "B")) {
            fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail.setLineId(hotCheck.getBfdPSRID());
            fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail.setLineName(hotCheck.getBfdName());
        } else if (StrUtil.equals(segResultDTO.getWhichSide(), "A") || StrUtil.equals(segResultDTO.getWhichSide(), "M")) {
            fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail.setLineId(hotCheck.getAfdBPSRID());
            String afdPSRID = hotCheck.getAfdPSRID();
            if (StrUtil.isNotBlank(afdPSRID)) {
                FeederCacheDTO feederCacheDTO = dwdShbDsFeederBaseService.getFeederByCacheOrDb(afdPSRID);
                fhzgPlanTransferSchemeSwitchingLoopSegCurrentDetail.setLineName(feederCacheDTO.getName());
            }
        } else {
            log.info("whichSide类型错误");
        }
    }
}
