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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.hdkj.lt.base.constants.DictConstants;
import com.hdkj.lt.base.constants.ErrorLogConstant;
import com.hdkj.lt.base.constants.RedisKeyConstants;
import com.hdkj.lt.base.constants.RocketMQConstants;
import com.hdkj.lt.base.enums.EventTypeEnum;
import com.hdkj.lt.base.enums.OperationStepEnum;
import com.hdkj.lt.core.bizms.modle.po.DwdShbDsFeederBase;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanAwaitTransferUsers;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferSchemePathDetail;
import com.hdkj.lt.core.bizms.modle.po.voltageLimitViolation.*;
import com.hdkj.lt.core.log.exception.ExceptionErrorLogCast;
import com.hdkj.lt.core.log.model.param.ErrorLogParam;
import com.hdkj.lt.core.mq.client.RocketMQTemplate;
import com.hdkj.lt.core.mq.config.RocketMQProperties;
import com.hdkj.lt.core.mq.model.RocketMQMessageEntity;
import com.hdkj.lt.core.sys.dao.DwdShbDsFeederBaseMapper;
import com.hdkj.lt.core.sys.model.dto.OrgInfoDto;
import com.hdkj.lt.core.sys.service.ISysStruService;
import com.hdkj.lt.modle.dto.abnormal.ApiAbnormalDataDTO;
import com.hdkj.lt.modle.dto.voltageLimitViolation.*;
import com.hdkj.lt.modle.vo.svg.LineFileInfoVO;
import com.hdkj.lt.mq.entity.dto.FeederInfo;
import com.hdkj.lt.mq.mapper.plan.PlanAwaitTransferAreaResultMapper;
import com.hdkj.lt.mq.mapper.voltageLimitViolation.FhzgInfoLimitTransferSchemeMapper;
import com.hdkj.lt.mq.mapper.voltageLimitViolation.FhzgLimitTransferSchemePathDetailMapper;
import com.hdkj.lt.mq.mapper.voltageLimitViolation.FhzgVoltageLimitViolationPowerCutMapper;
import com.hdkj.lt.mq.mapper.voltageLimitViolation.FhzgVoltageLimitViolationTransferSchemeDetailMapper;
import com.hdkj.lt.mq.service.base.ISvgFileInfoService;
import com.hdkj.lt.mq.service.voltageLimitViolation.FhzgInfoLimitTransferSchemeResultService;
import com.hdkj.lt.mq.service.voltageLimitViolation.FhzgInfoLimitTransferSchemeSwitchingSequenceService;
import com.hdkj.lt.mq.service.voltageLimitViolation.FhzgLimitTransferSchemePathDetailService;
import com.hdkj.lt.mq.service.voltageLimitViolation.FhzgVoltageLimitViolationPowerCutService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Now;
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.stream.Collectors;

import static com.hdkj.lt.base.constants.CommonConstant.*;
import static com.hdkj.lt.base.enums.CommonUnitEnum.FOUR;
import static com.hdkj.lt.base.enums.CommonUnitEnum.I;

/**
 * @author userlrk
 * @description 针对表【fhzg_voltage_limit_violation_power_cut(成片电压越限事件表)】的数据库操作Service实现
 * @createDate 2025-09-24 15:24:11
 */
@Service
@Slf4j
public class FhzgVoltageLimitViolationPowerCutServiceImpl extends ServiceImpl<FhzgVoltageLimitViolationPowerCutMapper, FhzgVoltageLimitViolationPowerCut>
        implements FhzgVoltageLimitViolationPowerCutService {
    @Autowired
    RocketMQProperties rocketMQProperties;
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @Autowired
    private FhzgInfoLimitTransferSchemeResultService resultService;
    @Autowired
    private FhzgVoltageLimitViolationTransferSchemeDetailMapper transferSchemeDetailMapper;
    @Autowired
    private FhzgInfoLimitTransferSchemeMapper schemeMapper;
    @Autowired
    private FhzgInfoLimitTransferSchemeSwitchingSequenceService transferSchemeSwitchingSequenceService;
    @Autowired
    private DwdShbDsFeederBaseMapper feederBaseMapper;
    @Autowired
    ISysStruService sysStruService;
    @Autowired
    private PlanAwaitTransferAreaResultMapper awaitTransferAreaResultMapper;
    @Autowired
    private ISvgFileInfoService svgFileInfoService;
    @Autowired
    private FhzgVoltageLimitViolationPowerCutMapper powerCutMapper;
    @Autowired
    private FhzgLimitTransferSchemePathDetailMapper pathDetailMapper;
    @Autowired
    private FhzgLimitTransferSchemePathDetailService pathDetailService;

    @Override
    //低电压json解析方法
    public void analysisLimitTransferScheme(Long dto) {
        LambdaQueryWrapper<FhzgInfoLimitTransferSchemeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FhzgInfoLimitTransferSchemeResult::getId, dto);
        FhzgInfoLimitTransferSchemeResult areaResult = resultService.getOne(queryWrapper);
        Long limitId;
        if (areaResult.getLimitId() == null) {
            limitId = IdUtil.getSnowflakeNextId();
            areaResult.setLimitId(limitId);
            resultService.saveOrUpdate(areaResult);
        } else {
            limitId = areaResult.getLimitId();
        }
        //清空相关数据
        removeByLimitId(limitId);
        //处理入参json
        Optional.ofNullable(areaResult.getSchemeResultJson())
                .map(e -> JSON.parseObject(e, VoltageTransferDataDTO.class))
                .ifPresent(data -> {
                    //低电压事件Id
                    FhzgVoltageLimitViolationPowerCut limitViolationPowerCut = new FhzgVoltageLimitViolationPowerCut();
                    limitViolationPowerCut.setId(limitId)
                            .setVoltageLimitStartTime(data.getStartTime())
                            .setEventCreateTime(data.getDateTime())
                            .setCreateTime(LocalDateTime.now())
                            .setVoltageLimitEndTime(data.getEndTime())
                            .setReason("成片越下限")
                            .setLimitNo(data.getId())
                            .setEventType(data.getEventType());
                    //保存低电压事件
                    dealWithAreaVoltViolationPowerCut(limitViolationPowerCut, data.getAreaVoltViolationList(), data.getFeederId());
//                    // 线路额定电流信息
//                    List<FeederCheckRuleDTO> feederCheckRuleList = data.getFeederCheckRuleList();
//                    Map<String, FeederCheckRuleDTO> feederCheckRuleDTOMap = feederCheckRuleList.stream()
//                            .collect(Collectors.toMap(FeederCheckRuleDTO::getFeederId, a -> a,
//                                    (existing, replacement) -> existing));
                    //转供前线路电压越限对比情况保存
                    Map<Long, XferPlanDTO> planMap = new HashMap<>();
                    Map<Long, LoopCheckRuleDTO> checkRuleDTOMap = new HashMap<>();
                    //处理方案中数据
                    if (data.getXferPlanList() != null && !data.getXferPlanList().isEmpty()) {
                        data.getXferPlanList().forEach(p -> {
                            //确定本侧对侧线路
                            String feederId = data.getFeederId();
                            String oppFeederId = null;
                            for (AreaVoltViolationDTO areaVoltViolationDTO : p.getAreaVoltViolationList()) {
                                if (!areaVoltViolationDTO.getFeederId().equals(feederId)) {
                                    oppFeederId = areaVoltViolationDTO.getFeederId();
                                }
                            }
                            //转供前数据仅保存本侧与对侧
                            List<AreaVoltViolationDTO> list = new ArrayList<>();
                            for (AreaVoltViolationDTO areaVoltViolationDTO : data.getAreaVoltViolationList()) {
                                if (areaVoltViolationDTO.getFeederId().equals(feederId) || areaVoltViolationDTO.getFeederId().equals(oppFeederId)) {
                                    list.add(areaVoltViolationDTO);
                                }
                            }
                            Long schemeId = IdUtil.getSnowflakeNextId();
                            //保存转供前数据
                            dealWithAreaVoltViolationList(list, 0, data.getFeederId(), schemeId, limitId, data.getFeederInfo());
                            FhzgInfoLimitTransferScheme transferScheme = new FhzgInfoLimitTransferScheme();
                            transferScheme.setId(schemeId).setLimitId(limitId).setSchemeNo(p.getId())
                                    .setSchemeState("0").setCheckState(1).setSchemeJson(JSON.toJSONString(p));
                            //保存方案基本信息
                            schemeMapper.insert(transferScheme);
                            planMap.put(schemeId, p);
                            //处理转供后对比数据
                            List<FeederInfoDTO> infoDTOS = new ArrayList<>();
                            FeederInfoDTO feederInfoDTO = new FeederInfoDTO();
                            feederInfoDTO.setFeederId(oppFeederId);
                            p.getXferSupplyAreaList().forEach(s -> {
                                infoDTOS.add(s.getFeederInfo());
                                feederInfoDTO.setMaxCurrentLoad(s.getLinkLineInfo().getPlanMaxCurrentLoad());
                                infoDTOS.add(feederInfoDTO);

                            });
                            dealWithAreaVoltViolationList(p.getAreaVoltViolationList(), 2, data.getFeederId(), schemeId, limitId, infoDTOS);
                            //保存方案中转供路径细明数据
                            List<FhzgLimitTransferSchemePathDetail> dataList = new ArrayList<>();
                            dealPlanTransferSchemePathDetail(dataList, p.getXferSupplyAreaList(), schemeId, data.getFeederId(), null, p.getTransferCapacity());
                            pathDetailService.saveBatch(dataList);
                        });
                    }
                    //处理开关动作顺序以及合环终态校验结果保存
                    if (!planMap.isEmpty()) {
                        LoopCheckRuleDTO loopCheckRuleDTO = data.getXferPlanList().get(0).getLoopCheckRule();
                        transferSchemeSwitchingSequenceService.analyzeXferPlanList(limitId, planMap, loopCheckRuleDTO, limitViolationPowerCut, null);
                        //根据合环结果判断方案是否校验通过
                        transferSchemeSwitchingSequenceService.updateLimitScheme(limitId);
                    }
                    planMap.forEach((key, val) -> {
                        LineFileInfoVO svgGenerationFile = svgFileInfoService.getSvgGenerationFile(limitViolationPowerCut.getLineId(), key, EIGHT);
                        if (svgGenerationFile == null) {
                            ErrorLogParam errorLogParam = new ErrorLogParam()
                                    .setErrorTime(LocalDateTime.now())
                                    .setEventType(EventTypeEnum.TOPO_FILE.getCode())
                                    .setEventId(limitId.toString())
                                    .setStage(ErrorLogConstant.Stage.GET_SVG_TOPO)
                                    .setErrorLevel("Warning")
                                    .setSourceSystem(ErrorLogConstant.SourceSystem.FHZG)
                                    .setOperationStep(OperationStepEnum.ABNORMAL.getName())
                                    .setRelatedId(key.toString())
                                    .setErrorCategory("方案成图失败")
                                    .setRelatedCategory("fhzg_info_limit_transfer_scheme")
                                    .setDetails("低电压事件id：" + limitId + "方案id：" + key + " 成图服务报错，请求参数: lineId:" + limitViolationPowerCut.getLineId() + ", objId" + key + ", type:" + SIX);
                            ExceptionErrorLogCast.cast(errorLogParam);
                        }
                    });
                    svgFileInfoService.getSvgGenerationFile(limitViolationPowerCut.getLineId(), limitId, SEVEN);
                });
    }

    @Override
    public void acceptLimitPowercut(String value) {
        Long id = IdUtil.getSnowflakeNextId();
        FhzgVoltageLimitViolationPowerCut limitViolationPowerCut = new FhzgVoltageLimitViolationPowerCut();
        limitViolationPowerCut.setLimitNo(value).setId(id);
        this.save(limitViolationPowerCut);
        try {
            if (rocketMQProperties.getEnabled()) {
                RocketMQMessageEntity messageEntity = RocketMQMessageEntity.builder()
                        .topicId(RocketMQConstants.TOPIC_ID_TO_ANALYSIS_RESULT_TICKET)
                        .cacheKey(RedisKeyConstants.ASYNC_POWER_CUT_RESULT_TOPIC_TICKET)
                        .tag("4") // 1-计划停电，2-故障停电,3运行调优，4全口径低电压
                        .body(id).build();
                rocketMQTemplate.sendAsyncMessage(messageEntity);
                log.info("发送停电计划解析消息成功faultId{}", id);
            }
        } catch (Exception e) {
            //todo 消息发送重试
            log.error("数据落库成功，发送解析计划数据消息失败方案编码LimitId:{}", id);
        }

    }

    //保存成片电压越限事件数据
    private void dealWithAreaVoltViolationPowerCut(FhzgVoltageLimitViolationPowerCut limitViolationPowerCut, List<AreaVoltViolationDTO> areaVoltViolationList, String feederId) {
        areaVoltViolationList.forEach(e -> {
            if (e.getFeederId().equals(feederId)) {
                limitViolationPowerCut
                        .setLineId(feederId)
                        .setLineName(getFeederName(e.getFeederId()))
                        .setOverVoltageIndexNormal(e.getGeneralOvervoltLvcustomerRate())
                        .setOverVoltageIndexHeavy(e.getSevereOvervoltLvcustomerRate())
                        .setUnderVoltageIndexNormal(e.getGeneralUndervoltLvcustomerRate())
                        .setUnderVoltageIndexHeavy(e.getSevereUndervoltLvcustomerRate())
                        .setVoltageIndex(e.getVoltRate())
                        .setOverVoltageTime(Optional.ofNullable(e.getOverVoltTime()).orElse(0))
                        .setUnderVoltageTime(Optional.ofNullable(e.getUnderVoltTime()).orElse(0))
                        .setUnderVoltageLineCount(Optional.ofNullable(e.getUnderVoltSegCount()).orElse(0))
                        .setUnderVoltageLineNum(Optional.ofNullable(e.getUnderVoltSegNum()).orElse(0))
                        .setUnderVoltageMvCustomerCount(Optional.ofNullable(e.getUnderVoltMvcustomerCount()).orElse(0))
                        .setUnderVoltageMvCustomerNum(Optional.ofNullable(e.getUnderVoltMvcustomerNum()).orElse(0))
                        .setUnderVoltageLvCustomerCount(Optional.ofNullable(e.getUnderVoltLvcustomerCount()).orElse(0))
                        .setUnderVoltageLvCustomerNum(Optional.ofNullable(e.getUnderVoltLvcustomerNum()).orElse(0))
                        .setUnderVoltageTransformerCount(Optional.ofNullable(e.getUnderVoltTransCount()).orElse(0))
                        .setUnderVoltageTransformerNum(Optional.ofNullable(e.getUnderVoltTransNum()).orElse(0));
                List<OrgInfoDto> orgInfoList = sysStruService.getCountyByPsrId(limitViolationPowerCut.getLineId());
                if (CollUtil.isNotEmpty(orgInfoList)) {
                    limitViolationPowerCut.setCountyName(orgInfoList.get(0).getOrganName());
                    limitViolationPowerCut.setCountyCode(Long.parseLong(orgInfoList.get(0).getStruId()));
                }
                save(limitViolationPowerCut);
            }
        });
    }


    //处理低电压转供前后及合并后线路情况
    private void dealWithAreaVoltViolationList(List<AreaVoltViolationDTO> areaVoltViolationList, Integer type, String feederId, Long schemeId, Long limitId, List<FeederInfoDTO> feederInfoDTOS) {
        FhzgVoltageLimitViolationTransferSchemeDetail schemeDetailAll = new FhzgVoltageLimitViolationTransferSchemeDetail();
        schemeDetailAll
                .setOverVoltageIndex(0.0)
                .setUnderVoltageIndex(0.0)
                .setVoltIndex(0.0)
                .setOverVoltageTime(0)
                .setUnderVoltageTime(0)
                .setUnderVoltageLineCount(0)
                .setUnderVoltageLineNum(0)
                .setUnderVoltageTransformerCount(0)
                .setUnderVoltageTransformerNum(0)
                .setUnderVoltageMvCustomerCount(0)
                .setUnderVoltageMvCustomerNum(0)
                .setUnderVoltageLvCustomerCount(0)
                .setUnderVoltageLvCustomerNum(0);
        areaVoltViolationList.forEach(e -> {
            //本侧对侧
            int tag;
            if (feederId.equals(e.getFeederId())) {
                tag = 0;
            } else {
                tag = 1;
            }
            FhzgVoltageLimitViolationTransferSchemeDetail schemeDetail = new FhzgVoltageLimitViolationTransferSchemeDetail();
            schemeDetail.setId(IdUtil.getSnowflakeNextId())
                    .setLineId(e.getFeederId())
                    .setLimitId(limitId)
                    .setSchemeId(schemeId)
                    .setLineName(getFeederName(e.getFeederId()))
                    .setLineTag(tag)
                    .setStatusTag(type)
                    .setOverVoltageIndex(e.getOverVoltRate())
                    .setUnderVoltageIndex(e.getUnderVoltRate())
                    .setVoltIndex(e.getVoltRate())
                    .setOverVoltageTime(Optional.ofNullable(e.getOverVoltTime()).orElse(0))
                    .setUnderVoltageTime(Optional.ofNullable(e.getUnderVoltTime()).orElse(0))
                    .setUnderVoltageLineCount(Optional.ofNullable(e.getUnderVoltSegCount()).orElse(0))
                    .setUnderVoltageLineNum(Optional.ofNullable(e.getUnderVoltSegNum()).orElse(0))
                    .setUnderVoltageMvCustomerCount(Optional.ofNullable(e.getUnderVoltMvcustomerCount()).orElse(0))
                    .setUnderVoltageMvCustomerNum(Optional.ofNullable(e.getUnderVoltMvcustomerNum()).orElse(0))
                    .setUnderVoltageLvCustomerCount(Optional.ofNullable(e.getUnderVoltLvcustomerCount()).orElse(0))
                    .setUnderVoltageLvCustomerNum(Optional.ofNullable(e.getUnderVoltLvcustomerNum()).orElse(0))
                    .setUnderVoltageTransformerCount(Optional.ofNullable(e.getUnderVoltTransCount()).orElse(0))
                    .setUnderVoltageTransformerNum(Optional.ofNullable(e.getUnderVoltTransNum()).orElse(0));
            //最大负载率
            feederInfoDTOS.forEach(f -> {
                if (f.getFeederId().equals(e.getFeederId())) {
                    schemeDetail.setMaxLoadRate(f.getMaxCurrentLoad());
                }
            });
            //计算合并后数据
            schemeDetailAll.setId(IdUtil.getSnowflakeNextId())
                    .setLineId(e.getFeederId())
                    .setSchemeId(schemeId)
                    .setLimitId(limitId)
                    .setLineName(getFeederName(e.getFeederId()))
                    .setLineTag(2)
                    .setStatusTag(type)
                    .setOverVoltageIndex(Optional.ofNullable(e.getOverVoltRate()).orElse(0.0) + schemeDetailAll.getOverVoltageIndex())
                    .setUnderVoltageIndex(Optional.ofNullable(e.getUnderVoltRate()).orElse(0.0) + schemeDetailAll.getUnderVoltageIndex())
                    .setVoltIndex(Optional.ofNullable(e.getVoltRate()).orElse(0.0) + schemeDetailAll.getVoltIndex())
                    .setOverVoltageTime(Optional.ofNullable(e.getOverVoltTime()).orElse(0) + schemeDetailAll.getOverVoltageTime())
                    .setUnderVoltageTime(Optional.ofNullable(e.getUnderVoltTime()).orElse(0) + schemeDetailAll.getUnderVoltageTime())
                    .setUnderVoltageLineCount(Optional.ofNullable(e.getUnderVoltSegCount()).orElse(0) + schemeDetailAll.getUnderVoltageLineCount())
                    .setUnderVoltageLineNum(Optional.ofNullable(e.getUnderVoltSegNum()).orElse(0) + schemeDetailAll.getUnderVoltageLineNum())
                    .setUnderVoltageTransformerCount(Optional.ofNullable(e.getUnderVoltTransCount()).orElse(0) + schemeDetailAll.getUnderVoltageTransformerCount())
                    .setUnderVoltageTransformerNum(Optional.ofNullable(e.getUnderVoltSegNum()).orElse(0) + schemeDetailAll.getUnderVoltageTransformerNum())
                    .setUnderVoltageMvCustomerCount(Optional.ofNullable(e.getUnderVoltMvcustomerCount()).orElse(0) + schemeDetailAll.getUnderVoltageMvCustomerCount())
                    .setUnderVoltageMvCustomerNum(Optional.ofNullable(e.getUnderVoltMvcustomerNum()).orElse(0) + schemeDetailAll.getUnderVoltageMvCustomerNum())
                    .setUnderVoltageLvCustomerCount(Optional.ofNullable(e.getUnderVoltLvcustomerCount()).orElse(0) + schemeDetailAll.getUnderVoltageLvCustomerCount())
                    .setUnderVoltageLvCustomerNum(Optional.ofNullable(e.getUnderVoltLvcustomerNum()).orElse(0) + schemeDetailAll.getUnderVoltageLvCustomerNum());
            transferSchemeDetailMapper.insert(schemeDetail);
        });
        //电压指数+越上限指数+越下限指数=100
        schemeDetailAll.setVoltIndex(schemeDetailAll.getVoltIndex() / 2)
                .setUnderVoltageIndex(schemeDetailAll.getUnderVoltageIndex() / 2)
                .setOverVoltageIndex(schemeDetailAll.getOverVoltageIndex() / 2);
        transferSchemeDetailMapper.insert(schemeDetailAll);
    }

    /**
     * 处理转供路径明细
     */
    private void dealPlanTransferSchemePathDetail(List<FhzgLimitTransferSchemePathDetail> dataList, List<XferSupplyAreaDTO> supplyAreaList,
                                                  Long schemeId, String lineId, List<FhzgPlanAwaitTransferUsers> awaitTransferUsers, Double transferCapacity) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        supplyAreaList.forEach(e -> {
            List<String> userList = Lists.newArrayList();
            String startSwitchId = Optional.ofNullable(e.getIsolateBreaker()).map(en -> en.getBreakerPSRID()).orElse(null);
            String startSwitchName = Optional.ofNullable(e.getIsolateBreaker()).map(en -> en.getBreakerName()).orElse(null);
            // 对线线路存在时映射对应的值
            FhzgLimitTransferSchemePathDetail schemePathDetail = new FhzgLimitTransferSchemePathDetail();
            // 对侧线路
            Optional.ofNullable(e.getLinkLineInfo()).ifPresent(linkLine -> {
                schemePathDetail.setOppositeLineId(Optional.ofNullable(linkLine.getPsrID()).orElse(null))
                        .setOppositeLineName(Optional.ofNullable(linkLine.getName()).orElse(null))
                        .setLoadFactor(Optional.ofNullable(linkLine.getPlanMaxCurrentLoad()).map(BigDecimal::valueOf).orElse(null))
                        .setSchemeId(schemeId).setCreateTime(LocalDateTime.now());
                Optional.ofNullable(loginUser).ifPresent(user -> schemePathDetail.setCreator(loginUser.getUserid()));
            });
            // 联络开关信息
            String linkSwitchId = Optional.ofNullable(e.getLinkSwitch()).map(LinkSwitchDTO::getPsrID).orElse("-");
            // 临界开关信息
            Optional.ofNullable(e.getLinkSwitch()).ifPresent(linkSwitch -> {
                schemePathDetail.setSwitchId(Optional.ofNullable(linkSwitch.getPsrID()).orElse(null))
                        .setSwitchName(Optional.ofNullable(linkSwitch.getName()).orElse(null));
            });
            // 开关段信息
            Optional.ofNullable(e.getSwitchInfoList()).ifPresent(switchList -> {
                // 设置起点开关
                schemePathDetail.setStartSwitchId(startSwitchId).setStartSwitchName(startSwitchName);
                // 终点开关ID集合（可能不包含未启用的联络开关）
                List<String> endSwitchIds = switchList.stream()
                        .filter(en -> !StringUtils.equalsAny(en.getSwitchId(), startSwitchId, linkSwitchId))
                        .map(SwitchInfoDTO::getSwitchId).collect(Collectors.toList());
                List<String> switchTypes = Arrays.asList(DictConstants.KG_PSR_TYPE.split(","));
                //动态切换表名，在此方法外调用
                //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(null, lineId));
                List<com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO> switchSectionList = awaitTransferAreaResultMapper.getSwitchSectionInfo(lineId, startSwitchId, linkSwitchId, endSwitchIds, switchTypes);
                if (ObjectUtils.isNotEmpty(switchSectionList)) {
                    // 处理中间开关和结束开关
                    Map<String, com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO> switchInfoMap = switchSectionList.stream()
                            .collect(Collectors.groupingBy(
                                    com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO::getSwitchType,
                                    Collectors.collectingAndThen(
                                            Collectors.reducing((s1, s2) -> com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO.builder()
                                                    .switchId(String.format("%s,%s", s1.getSwitchId(), s2.getSwitchId()))
                                                    .switchName(String.format("%s,%s", s1.getSwitchName(), s2.getSwitchName())).build()),
                                            Optional::get)
                            ));
                    // 中间开关信息
                    com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO midSwitchInfo = Optional.ofNullable(switchInfoMap.get("mid")).orElse(com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO.builder().build());
                    // 结束开关信息
                    com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO endSwitchInfo = Optional.ofNullable(switchInfoMap.get("end")).orElse(com.hdkj.lt.modle.dto.jsty.SwitchInfoDTO.builder().build());
                    schemePathDetail.setSwitchSectionId(midSwitchInfo.getSwitchId()).setSwitchSectionName(midSwitchInfo.getSwitchName())
                            .setEndSwitchId(endSwitchInfo.getSwitchId()).setEndSwitchName(endSwitchInfo.getSwitchName());
                }
            });
            // 取出本区域的所有的转供用户
            Optional.ofNullable(e.getAreaDeviceInfo()).ifPresent(device -> {
                userList.addAll(device.getMvTransList().stream().map(TransCustomerDTO::getPsrID).collect(Collectors.toList()));
                userList.addAll(device.getMvCustomerList().stream().map(TransCustomerDTO::getPsrID).collect(Collectors.toList()));
            });
            // 在待转供用户找到负荷开关负载累加，设置开关段负荷
//            double userSum = awaitTransferUsers.stream()
//                    .filter(en -> userList.contains(en.getTransformerNo()) && ObjectUtils.isNotEmpty(en.getUserLoads()))
//                    .map(en -> en.getUserLoads()).mapToDouble(BigDecimal::doubleValue).sum();
//            BigDecimal sum = BigDecimal.valueOf(userSum).setScale(6, RoundingMode.HALF_UP);
//            schemePathDetail.setSwitchSectionLoads(sum);
            if (transferCapacity != null) {
                schemePathDetail.setSwitchSectionLoads(BigDecimal.valueOf(transferCapacity * 1000));
            }
            // 开关段信息
            dataList.add(schemePathDetail);
        });
    }


    private void removeByLimitId(Long limitId) {
        //删除事件表数据
        this.removeById(limitId);
        //删除方案表数据
        LambdaQueryWrapper<FhzgInfoLimitTransferScheme> schemeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schemeLambdaQueryWrapper.eq(FhzgInfoLimitTransferScheme::getLimitId, limitId);
        List<FhzgInfoLimitTransferScheme> schemeList = schemeMapper.selectList(schemeLambdaQueryWrapper);
        if (schemeList != null) {
            schemeList.forEach(s -> {
                LambdaQueryWrapper<FhzgLimitTransferSchemePathDetail> pathDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
                pathDetailLambdaQueryWrapper.eq(FhzgLimitTransferSchemePathDetail::getSchemeId, s.getId());
                pathDetailMapper.delete(pathDetailLambdaQueryWrapper);
            });
        }
        LambdaQueryWrapper<FhzgVoltageLimitViolationTransferSchemeDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailLambdaQueryWrapper.eq(FhzgVoltageLimitViolationTransferSchemeDetail::getLimitId, limitId);
        transferSchemeDetailMapper.delete(detailLambdaQueryWrapper);
        schemeMapper.delete(schemeLambdaQueryWrapper);
    }

    private String getFeederName(String feederId) {
        LambdaQueryWrapper<DwdShbDsFeederBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DwdShbDsFeederBase::getPsrId, feederId);
        DwdShbDsFeederBase feederBase = feederBaseMapper.selectOne(lambdaQueryWrapper);
        if (feederBase != null) {
            return feederBase.getName();
        } else return "";
    }

}




