package com.hdkj.lt.bf.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.hdkj.lt.base.constants.DictConstants;
import com.hdkj.lt.bf.entity.FhzgPlanPowerCut;
import com.hdkj.lt.bf.entity.dto.CustomerAccountDTO;
import com.hdkj.lt.bf.entity.vo.*;
import com.hdkj.lt.bf.mapper.FeederBaseMapper;
import com.hdkj.lt.bf.mapper.FhzgGenerateGraphMapper;
import com.hdkj.lt.bf.mapper.FhzgPlanAwaitTransferSwitchSectionMapper;
import com.hdkj.lt.bf.mapper.FhzgPlanTransferSchemePathDetailMapper;
import com.hdkj.lt.bf.service.FhzgGenerateGraphService;
import com.hdkj.lt.bf.service.FhzgPlanPowerCutService;
import com.hdkj.lt.core.bizms.modle.dto.FhzgPlanTransferSchemePathDetailDTO;
import com.hdkj.lt.core.bizms.modle.dto.SchemeQueryDTO;
import com.hdkj.lt.core.bizms.modle.dto.UserListQueryDTO;
import com.hdkj.lt.core.bizms.modle.po.FeederTopo;
import com.hdkj.lt.core.bizms.modle.po.plan.*;
import com.hdkj.lt.core.bizms.modle.vo.JoinecUserVO;
import com.hdkj.lt.core.bizms.modle.vo.SwitchListVO;
import com.hdkj.lt.core.bizms.modle.vo.UserListVO;
import com.hdkj.lt.core.sys.dao.FhzgOrganSuffixMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
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.util.*;
import java.util.stream.Collectors;

/**
 * 成图服务
 *
 * @author zhuzhe
 * @since 2025-05-22
 */
@Slf4j
@Service
public class FhzgGenerateGraphServiceImpl implements FhzgGenerateGraphService {

    @Autowired
    FhzgGenerateGraphMapper fhzgGenerateGraphMapper;

    @Autowired
    FhzgPlanAwaitTransferSwitchSectionMapper fhzgPlanAwaitTransferSwitchSectionMapper;

    @Autowired
    FhzgPlanTransferSchemePathDetailMapper fhzgPlanTransferSchemePathDetailMapper;

    @Autowired
    FhzgPlanPowerCutService fhzgPlanPowerCutService;

    @Autowired
    FeederBaseMapper feederBaseMapper;

    @Autowired
    FhzgOrganSuffixMapper fhzgOrganSuffixMapper;

    /**
     * 根据停电范围查询开关列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<BreakerAreaVO> getSwitchListByOutArea(SchemeQueryDTO dto) {
        String resultString = fhzgGenerateGraphMapper.getSwitchListByOutArea(dto.getPlanId());
        if (StrUtil.isNotBlank(resultString)) {
            return JSON.parseObject(resultString, new TypeReference<List<BreakerAreaVO>>() {
            });
        }
        List<BreakerAreaVO> result = new ArrayList<>();

        // 查询停电计划，获取线路名称
        FhzgPlanPowerCut fhzgPlanPowerCut = fhzgGenerateGraphMapper.selectFhzgPlanById(dto.getPlanId());
        String lineId = fhzgPlanPowerCut.getLineId();

        // 根据计划id查询停电范围
        List<FhzgPlanPowerCutSwitch> cutSwitchList = fhzgGenerateGraphMapper.selectPowerCutSwitchList(dto);

        if (cutSwitchList == null || cutSwitchList.isEmpty()) {
            return null;
        }

        String isFullLine = cutSwitchList.get(0).getIsFullLine();

        // 整线停电，返回出线开关
        if ("1".equals(isFullLine)) {
            // 查询出线开关
            LambdaQueryWrapper<FeederTopo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StringUtils.isNotEmpty(lineId), FeederTopo::getFeeder, lineId)
                    .eq(FeederTopo::getIsStartKg, 1)
                    .in(FeederTopo::getPsrType, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));
            //动态切换表名
//*ztj            ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(dto.getPlanId(), null));
            List<FeederTopo> leadoutBreakerList = fhzgGenerateGraphMapper.getFeederTopo(wrapper);
            if (leadoutBreakerList == null || leadoutBreakerList.isEmpty()) {
                return Collections.emptyList();
            }
            BreakerAreaVO breakerAreaVO = new BreakerAreaVO();
            breakerAreaVO.setStartSwitch(leadoutBreakerList.get(0).getPsrId());
            // 查询开关后面的所有开关作为中间开关
            /*List<BrakerTransformerRelationDTO> switchTree = fhzgGenerateGraphMapper.getBreakerTree(null,
                    leadoutBreakerList.get(0).getPsrId(), lineId, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));
            if (switchTree != null && switchTree.size() > 0) {
                List<String> midIds = switchTree.stream().map(p -> p.getChildPsrId()).
                        filter(p -> StringUtils.isNotEmpty(p)).distinct().collect(Collectors.toList());
                breakerAreaVO.setMidSwitch(midIds);
            }*/

            breakerAreaVO.setIsFullLine("1");
            result.add(breakerAreaVO);
            return result;
        } else {
            for (FhzgPlanPowerCutSwitch fhzgPlanPowerCutSwitch : cutSwitchList) {
                String startStr = fhzgPlanPowerCutSwitch.getStartSwitch();
                String endStr = fhzgPlanPowerCutSwitch.getEndSwitch();

                BreakerAreaVO breakerAreaVO = new BreakerAreaVO();
                // 结束开关为空，返回开始开关
                if (endStr == null) {
                    breakerAreaVO.setStartSwitch(startStr);
                    // 查询开关后面的所有开关作为中间开关
                   /* List<BrakerTransformerRelationDTO> switchTree = fhzgGenerateGraphMapper.getBreakerTree(null,
                            startStr, lineId, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));
                    if (switchTree != null && switchTree.size() > 0) {
                        List<String> midIds = switchTree.stream().map(p -> p.getChildPsrId()).
                                filter(p -> StringUtils.isNotEmpty(p)).distinct().collect(Collectors.toList());
                        breakerAreaVO.setMidSwitch(midIds);
                    }*/
                } else {      // 返回开始开关、中间开关、结束开关
                    List<String> endSwitchs = Arrays.asList(endStr.split(","));
                    //动态切换表名，在findMidSwitchs方法外部调用
//*ztj                     ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(dto.getPlanId(), null));
                    breakerAreaVO = findMidSwitchs(startStr, endSwitchs, lineId);
                }
                breakerAreaVO.setIsFullLine("0");
                result.add(breakerAreaVO);
            }
        }
        fhzgGenerateGraphMapper.saveSwitchListByOutArea(dto.getPlanId(), JSON.toJSONString(result));
        return result;
    }

    /**
     * 根据停电范围查询开关段列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<BreakerAreaVO> getSwitchListByTransferSection(SchemeQueryDTO dto) {
        List<BreakerAreaVO> result = new ArrayList<>();
        // 根据计划id查询转供范围
        List<FhzgPlanAwaitTransferSwitchSection> cutSwitchList = fhzgGenerateGraphMapper.selectSwitchSectionList(dto);
        // 查询停电计划，获取线路名称
        FhzgPlanPowerCut fhzgPlanPowerCut = fhzgGenerateGraphMapper.selectFhzgPlanById(dto.getPlanId());
        String lineId = fhzgPlanPowerCut.getLineId();
        if (cutSwitchList == null || cutSwitchList.isEmpty()) {
            return null;
        }
        //*ztj String organSuffix = fhzgOrganSuffixMapper.getOrganSuffixByFaultIdOrLineId(null, lineId);
        // 动态切换表名
        //*ztj ArgTableNameHandler.setArgument(organSuffix);
        // 获取开始开关结束开关间包括母线在内所有开关id
        List<Map<String, String>> psrList = fhzgGenerateGraphMapper.getBreakerPsrIdByPlanId(dto.getPlanId());
        if (ObjectUtils.isNotEmpty(psrList)) {
            String startSwitchId = psrList.get(0).get("start_switch_id");
            List<String> endSwitchIds = psrList.stream().map(e -> e.get("end_switch_id")).collect(Collectors.toList());
            List<String> midSwitchIds = Lists.newArrayList();
            cutSwitchList.forEach(e -> {
                // 添加分段开关尾开关到中间开关
                if (StringUtils.isNotBlank(e.getEndSwitchId())) {
                    midSwitchIds.addAll(Arrays.asList(e.getEndSwitchId().split(",")).stream()
                            .filter(en -> !endSwitchIds.contains(en)).collect(Collectors.toList()));
                }
                // 添加分段开关尾开始开关到中间开关
                if (!StringUtils.equals(e.getStartSwitchId(), startSwitchId)) {
                    midSwitchIds.add(e.getStartSwitchId());
                }
            });
            // 动态切换表名
            //*ztj ArgTableNameHandler.setArgument(organSuffix);
            // 获取中间的母线信息
            List<String> psrIdList = fhzgGenerateGraphMapper.getBusbarBySwitchIds(ListUtils.union(midSwitchIds, Arrays.asList(startSwitchId)));
            BreakerAreaVO breakerAreaVO = new BreakerAreaVO();
            breakerAreaVO.setStartSwitch(startSwitchId).setEndSwitch(endSwitchIds).setMidSwitch(ListUtils.union(midSwitchIds, psrIdList));
            result.add(breakerAreaVO);
        }
        /*for (FhzgPlanAwaitTransferSwitchSection transferSwitchSection : cutSwitchList) {

            String startStr = transferSwitchSection.getStartSwitchId();
            String endStr = transferSwitchSection.getEndSwitchId();
            BreakerAreaVO breakerAreaVO = new BreakerAreaVO();
            List<String> endSwitchs = new ArrayList<>();
//            // 结束开关为空，返回开始开关
//            breakerAreaVO.setStartSwitch(startStr);
            if (endStr != null) {
                endSwitchs = Arrays.asList(endStr.split(","));
                breakerAreaVO.setEndSwitch(endSwitchs);
            }
            breakerAreaVO = findMidSwitchs(startStr, endSwitchs, lineId);
            if (breakerAreaVO != null) {
                result.add(breakerAreaVO);
            }
        }*/
        return result;
    }


    BreakerAreaVO findMidSwitchs(String startSwitch, List<String> endSwitchs, String feeder) {
        BreakerAreaVO result = new BreakerAreaVO();
        Set<String> midSwitchs = new HashSet<>();
        if (StringUtils.isNotEmpty(startSwitch)) {
            // 通过线路和 开始开关 查询topo树形结构
//            List<BrakerTransformerRelationDTO> switchTree = fhzgGenerateGraphMapper.getBreakerTree(null,
//                    startSwitch, feeder, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));
            //            if (switchTree != null && !switchTree.isEmpty()) {
//            if (psrIdList != null && !psrIdList.isEmpty()) {
//
//                // 过滤 ChildPsrId 为空的数据，如果存在多条则取第一条
//                Map<String, BrakerTransformerRelationDTO> childToParentMap = switchTree.stream().filter(p -> StringUtils.isNotEmpty(p.getChildPsrId()))
//                        .collect(Collectors.toMap(BrakerTransformerRelationDTO::getChildPsrId, Function.identity(), (first, seconde) -> first));
//
//                for (String endSwitch : endSwitchs) {
//                    String current = endSwitch;
//                    while (childToParentMap.containsKey(current)) {
//                        String parent = childToParentMap.get(current).getParentPsrId();
//                        if (StringUtils.isEmpty(parent)) {
//                            break;
//                        }
//                        midSwitchs.add(parent);
//                        current = parent;
//                    }
//                }
//                midSwitchs.removeAll(endSwitchs);
//                midSwitchs.remove(startSwitch);
//            }
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByFaultIdOrLineId(null, feeder));
            //获取开始开关结束开关间包括母线在内所有开关id
            List<String> kgPsrTypes = Arrays.asList(DictConstants.KG_PSR_TYPE.split(","));
            List<String> psrIdList = fhzgGenerateGraphMapper.getBreakerPsrId(startSwitch, feeder, endSwitchs.stream().collect(Collectors.joining(",")), kgPsrTypes);
            result.setStartSwitch(startSwitch);
            result.setEndSwitch(endSwitchs);
            if (!psrIdList.isEmpty()) {
                result.setMidSwitch(psrIdList);
            }
        }
        return result;
    }

    /**
     * @param dto
     * @return
     */
    @Override
    public SwitchByUserVO getSwitchByCustomer(CustomerAccountDTO dto) {
//        SwitchByUserVO result = new SwitchByUserVO();
//        // 查询用户信息
//        FhzgDistCustomer fhzgDistCustomer = fhzgGenerateGraphMapper.selectCustomerById(dto.getCustomerId());
//        //所属变压器编码
//        String transformerNo = fhzgDistCustomer.getTransformerNo();
//
//        //用户查询所属开关，根据 transformerNo 从topo表中查询上一级开关
//        List<SwitchByUserVO> topoList = fhzgGenerateGraphMapper.selectSwitchByCustomer(transformerNo, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));
//        if (topoList !=null && topoList.size() > 0 ) {
//            result = topoList.get(0);
//        }
//
//        result.setIsCriticalUser(fhzgDistCustomer.getIsCriticalUser());
//        return result;
        //动态切换表名
        //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixPlanByCustomerId(dto.getCustomerId()));
        String switchId = fhzgGenerateGraphMapper.selectSwitchByCustomerId(dto.getCustomerId());
        SwitchByUserVO result = new SwitchByUserVO();
        result.setPsrId(switchId);
        return result;
    }

    @Override
    public List<BreakerAreaVO> getPathOverviewSwitch(SchemeQueryDTO dto) {
        String resultString = fhzgGenerateGraphMapper.getPathOverviewSwitch(dto.getPlanId(), dto.getSchemeId());
        if (StrUtil.isNotBlank(resultString)) {
            return JSON.parseObject(resultString, new TypeReference<List<BreakerAreaVO>>() {
            });
        }
        List<BreakerAreaVO> result = new ArrayList<>();
        FhzgPlanTransferScheme fhzgPlanTransferScheme = new FhzgPlanTransferScheme();
        fhzgPlanTransferScheme.setId(dto.getSchemeId());

        // 根据方案id 查询转供路径
        List<FhzgPlanTransferSchemePathDetailDTO> pathDetailList =
                fhzgPlanTransferSchemePathDetailMapper.getTransferSchemePathDetailByCombinationSchemeId(fhzgPlanTransferScheme);
        if (pathDetailList == null || pathDetailList.isEmpty()) {
            return null;
        }
        // 对侧线路的主线开关ID结果
        Map<String, List<String>> lineSwitchMap = MapUtil.newHashMap();
        // 对侧线路ID集合，用于查询对侧线路的主线开关ID
        List<String> lindIds = pathDetailList.stream().map(FhzgPlanTransferSchemePathDetailDTO::getOppositeLineId).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(lindIds)) {
            // 查询对侧线路的主线开关信息
            List<String> kgPsrTypes = Arrays.asList(DictConstants.KG_PSR_TYPE.split(","));
            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(dto.getPlanId(), null));
            List<FeederTopo> feederSwitchList = feederBaseMapper.getFeederSwitchListById(lindIds, kgPsrTypes);
            // 根据线路分组，取对侧线路的开关ID集合
            lineSwitchMap.putAll(feederSwitchList.stream().collect(Collectors.groupingBy(
                    FeederTopo::getFeeder,
                    Collectors.mapping(FeederTopo::getPsrId, Collectors.toList()))));
        }
        //动态切换表名
        //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanSchemeId(dto.getSchemeId()));
        // 20250706 添加查询本侧线路转供路径的母线信息
        List<String> kgPsrTypes = Arrays.asList(DictConstants.KG_PSR_TYPE.split(","));
        Map<String, List<String>> oppositeSwitchMap = fhzgPlanTransferSchemePathDetailMapper.getFeederBusbarBySchemeId(dto.getSchemeId(), kgPsrTypes)
                .stream().collect(Collectors.groupingBy(e -> e.getString("xl_id"), Collectors.mapping(e -> e.getString("psr_id"), Collectors.toList())));
        // 方案的所有开始开关
        List<String> startList = Arrays.stream(pathDetailList.stream().map(e -> e.getStartSwitchId())
                .collect(Collectors.joining(",")).split(",")).distinct().collect(Collectors.toList());

        for (FhzgPlanTransferSchemePathDetailDTO pathDetail : pathDetailList) {
            String startId = pathDetail.getStartSwitchId();
            String midIds = pathDetail.getSwitchSectionId();
            String endIds = pathDetail.getEndSwitchId();

            BreakerAreaVO breakerAreaVO = new BreakerAreaVO();
            breakerAreaVO.setOppositeLineId(pathDetail.getOppositeLineId());
            breakerAreaVO.setStartSwitch(startId);
            if (midIds != null) {
                // 方案对应的本侧线路的母线信息
                List<String> midDeviceIdList = Optional.ofNullable(oppositeSwitchMap.get(pathDetail.getOppositeLineId())).orElse(Lists.newArrayList());
                // 对侧线路对应的开关和母线信息
                List<String> oppositeSwitch = Optional.ofNullable(lineSwitchMap.get(pathDetail.getOppositeLineId())).orElse(Lists.newArrayList());
                // 添加中间设备本侧母线+对侧线路开关母线ID
                midDeviceIdList.addAll(oppositeSwitch);
                // 当对侧线路的结束开关 和 其他转供线路的开始开关一致时，需要添加此开关到中间开关中
                if (ObjectUtils.allNotNull(startList, endIds)) {
                    List<String> appendKgList = Arrays.stream(endIds.split(",")).filter(e -> startList.contains(e)).collect(Collectors.toList());
                    midDeviceIdList.addAll(appendKgList);
                }
                breakerAreaVO.setMidSwitch(ListUtils.union(Arrays.asList(midIds.split(",")), midDeviceIdList));
            }
            if (endIds != null) {
                breakerAreaVO.setEndSwitch(Arrays.asList(endIds.split(",")));
            }
            result.add(breakerAreaVO);
        }
        fhzgGenerateGraphMapper.savePathOverviewSwitch(dto.getPlanId(), dto.getSchemeId(), JSON.toJSONString(result));
        return result;
    }

    @Override
    public OppesiteConcatSwitchVO getOppesiteConcatSwitch(SchemeQueryDTO dto) {
        OppesiteConcatSwitchVO oppesiteConcatSwitchVO = new OppesiteConcatSwitchVO();
        // 查询对侧线路
        FhzgPlanOppositeLineCarryCapacity carryCapacity = fhzgGenerateGraphMapper.getOppositeLineCarryCapacity(dto.getCapacityId());
        String lineId = carryCapacity.getLineId();
        // 查询对侧线路联络开关
        LambdaQueryWrapper<FeederTopo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(lineId), FeederTopo::getFeeder, lineId)
                .eq(FeederTopo::getNormalOpen, "true")
                .in(FeederTopo::getPsrType, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));

        //动态切换表名
        //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(null, lineId));
        List<FeederTopo> leadoutBreakerList = fhzgGenerateGraphMapper.getFeederTopo(wrapper);
        // 查询计划方案中的联络开关
        List<FhzgPlanOppositeLineConcatSwitch> concatSwitchList = fhzgGenerateGraphMapper.getOppositeLineConcatSwitch(dto.getPlanId());

        if (leadoutBreakerList == null || leadoutBreakerList.isEmpty() || concatSwitchList == null || concatSwitchList.isEmpty()) {
            return null;
        }
        List<String> psrIdList = leadoutBreakerList.stream().map(t -> t.getPsrId()).collect(Collectors.toList());
        List<String> oppesitePsrIdList = concatSwitchList.stream().map(t -> t.getConcatPsrId()).collect(Collectors.toList());

        // 本侧联络开关 和 对侧联络开关取交集
        List<String> result = psrIdList.stream().filter(oppesitePsrIdList::contains).collect(Collectors.toList());
        oppesiteConcatSwitchVO.setPsrId(result);
        return oppesiteConcatSwitchVO;
    }

    @Override
    public SwitchByUserVO getSwitchByDevice(CustomerAccountDTO dto) {
        SwitchByUserVO result = new SwitchByUserVO();
        LambdaQueryWrapper<FeederTopo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FeederTopo::getPsrId, dto.getTransformerNo());
        //此处涉及接口未使用，未调用动态切换表名方法
        List<FeederTopo> leadoutBreakerList = fhzgGenerateGraphMapper.getFeederTopo(wrapper);
        if (leadoutBreakerList != null && leadoutBreakerList.size() > 0) {
            result.setPsrId(leadoutBreakerList.get(0).getStartKgId());
        }
        return result;
    }

    @Override
    public BreakerAreaVO getSwitchListBySwitchSection(SchemeQueryDTO dto) {
        String resultString = fhzgGenerateGraphMapper.getSwitchListBySwitchSection(dto.getPlanId());
        if (StrUtil.isNotBlank(resultString)) {
            return JSON.parseObject(resultString, BreakerAreaVO.class);
        }
        BreakerAreaVO result = new BreakerAreaVO();
        FhzgPlanAwaitTransferSwitchSection switchSection = fhzgGenerateGraphMapper.getSwitchSectionById(dto.getSectionId());
        result.setStartSwitch(switchSection.getStartSwitchId());
        if (StringUtils.isNotEmpty(switchSection.getEndSwitchId())) {
            String endSwitchs = switchSection.getEndSwitchId();
            List<String> psrIds = Arrays.asList(endSwitchs.split(","));

            // 终止开关后面有开关，则将当前开关放入中间开关
            LambdaQueryWrapper<FeederTopo> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(FeederTopo::getStartKgId, psrIds)
                    .in(FeederTopo::getPsrType, Arrays.asList(DictConstants.KG_PSR_TYPE.split(",")));
            //动态切换表名
            //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPlanIdOrLineId(switchSection.getPlanId(), null));
            List<FeederTopo> topoList = fhzgGenerateGraphMapper.getFeederTopo(wrapper);

            if (topoList != null && topoList.size() > 0) {
                List<String> midSwitchList = new ArrayList<>();
                Map<String, List<FeederTopo>> parentToChildMap = topoList.stream().filter(p -> StringUtils.isNotEmpty(p.getStartKgId()))
                        .collect(Collectors.groupingBy(p -> p.getStartKgId()));
                for (String endSwitch : psrIds) {
                    List<FeederTopo> childs = parentToChildMap.get(endSwitch);
                    if (childs != null && childs.size() > 0) {
                        childs = childs.stream().filter(p -> StringUtils.isNotEmpty(p.getPsrId())).collect(Collectors.toList());
                        if (childs == null || childs.size() == 0) {
                            midSwitchList.add(endSwitch);
                        }
                    } else {
                        midSwitchList.add(endSwitch);
                    }
                }
                if (midSwitchList != null && midSwitchList.size() > 0) {
                    result.setMidSwitch(midSwitchList);
                }
            }
            result.setEndSwitch(psrIds);
        }
        fhzgGenerateGraphMapper.saveSwitchListBySwitchSection(dto.getPlanId(), JSON.toJSONString(result));
        return result;
    }

    @Override
    public PlanConfirmStateVO getPlanConfirmState(SchemeQueryDTO dto) {
        PlanConfirmStateVO result = new PlanConfirmStateVO();
        FhzgPlanPowerCut powerCut = fhzgGenerateGraphMapper.selectFhzgPlanById(dto.getPlanId());
        result.setSchemeState(powerCut.getSchemeState());
        return result;
    }

    @Override
    public List<LoadSwitchUserNumsVO> getLoadUserNums(SchemeQueryDTO dto) {
        List<LoadSwitchUserNumsVO> numsList = fhzgGenerateGraphMapper.getLoadUserNums(dto.getPlanId());
        return numsList;
    }

    @Override
    public List<LoadSwitchUserNumsVO> getUserNumsByLoad(SchemeQueryDTO dto) {
        List<LoadSwitchUserNumsVO> numsList = fhzgGenerateGraphMapper.getUserNumsByLoad(dto);
        return numsList;
    }

    @Override
    public List<LoadSwitchUserNumsVO> getUserNumsByLine(String feederId) {
        //动态切换表名
        //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, feederId));
        //判断是否是主干馈线
        Integer isMainFeeder = fhzgGenerateGraphMapper.isMainFeeder(feederId);
        List<String> kgPsrTypes = Arrays.asList(DictConstants.KG_PSR_TYPE.split(","));
        List<LoadSwitchUserNumsVO> numsList = fhzgGenerateGraphMapper.getUserNumsByLine(feederId, kgPsrTypes);
        if (isMainFeeder != null && isMainFeeder == 0) {
            //非主干馈线，不展示分支用户总数
            numsList.forEach(i -> i.setSwitchNum(null));
        }
        return numsList;
    }

    @Override
    public List<LoadSwitchUserNumsVO> getAllUserNumsByLine(String feederId) {
        //动态切换表名
        //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, feederId));
        // 配变类型
        List<String> pbPsrTypes = Arrays.asList(DictConstants.PB_PSR_TYPE.split(","));
        List<LoadSwitchUserNumsVO> numsList = fhzgGenerateGraphMapper.getAllUserNumsByLine(feederId, pbPsrTypes);
        return numsList;
    }


    /**
     * @author luorui
     * @date 2025/6/11 16:28
     * @discription 根据起始开关和结束开关，查询负荷开关段下的用户详细信息
     **/
    @Override
    public Page<UserListVO> getUserListByLoadSwitchSegmentPage(UserListQueryDTO dto) {
        Page<UserListVO> page = new Page(dto.getPageNum(), dto.getPageSize());
        List<String> pbPsrType = Arrays.asList(DictConstants.PB_PSR_TYPE.split(","));
        //动态切换表名
        //*ztj ArgTableNameHandler.setArgument(fhzgOrganSuffixMapper.getOrganSuffixByPsrIdOrFeeder(null, dto.getLineId()));
        Page<UserListVO> result = fhzgGenerateGraphMapper.getUserListByLoadSwitchSegmentPage(page, dto, pbPsrType);
        //将中压接入点中的专变拆出来
        result.getRecords().stream().filter(e -> StrUtil.equals(e.getUserType(), "1")).forEach(e -> {
            List<JoinecUserVO> list = new ArrayList<>();
            String prsIdStr = e.getPrsIdList();
            String nameStr = e.getNameList();
            if (StrUtil.isNotBlank(prsIdStr) && StrUtil.isNotBlank(prsIdStr)) {
                List<String> prsIdList = StrUtil.splitTrim(prsIdStr, ',');
                List<String> nameList = StrUtil.splitTrim(nameStr, ',');
                if (prsIdList.size() == nameList.size()) {
                    for (int i = 0; i < prsIdList.size(); i++) {
                        JoinecUserVO joinecUserVO = JoinecUserVO.builder().psrId(prsIdList.get(i)).consName(nameList.get(i)).build();
                        list.add(joinecUserVO);
                    }
                    e.setJoinecUserList(list);
                } else {
                    log.info("查询中压接入点下专变数据异常，loadSwitchId:{},lineId:{},中压接入点id：{}", dto.getLoadSwitchId(), dto.getLineId(), e.getUserId());
                }
            }
        });
        return result;
    }


    /**
     * @author luorui
     * @date 2025/7/10 16:57
     * @discription 查询负荷点下用户列表
     **/
    @Override
    public Page<UserListVO> getUserListByLoadSwitchSegmentPageNew(UserListQueryDTO dto) {
        //Page<UserListVO> page = new Page(dto.getPageNum(), dto.getPageSize());
        List<String> pbPsrType = Arrays.asList(DictConstants.PB_PSR_TYPE.split(","));
        Page<UserListVO> result = new Page<>();
        List<UserListVO> userList = fhzgGenerateGraphMapper.getUserListByLoadSwitchSegmentPageNew(dto, pbPsrType);
        int start = (int) Math.min((dto.getPageNum() - 1) * dto.getPageSize(), userList.size());
        int end = (int) Math.min(dto.getPageNum() * dto.getPageSize(), userList.size());
        result.setSize(dto.getPageSize());
        result.setCurrent(dto.getPageNum());
        //存在搜索条件时，仅返回指定配变数据
        if (dto.getPsrId() != null && !dto.getPsrId().isEmpty()) {
            String psrIdZb = fhzgGenerateGraphMapper.getZbPsrId(dto.getPsrId());
            dto.setPsrId(psrIdZb);
            userList = userList.stream().filter(e -> dto.getPsrId().equals(e.getUserId())).collect(Collectors.toList());
            result.setRecords(userList);
        } else {
            result.setRecords(userList.subList(start, end));
        }
        result.setTotal(userList.size());
        //将中压接入点中的专变拆出来
        result.getRecords().stream().filter(e -> StrUtil.equals(e.getUserType(), "1")).forEach(e -> {
            List<JoinecUserVO> list = new ArrayList<>();
            String prsIdStr = e.getPrsIdList();
            String nameStr = e.getNameList();
            if (StrUtil.isNotBlank(prsIdStr) && StrUtil.isNotBlank(prsIdStr)) {
                List<String> prsIdList = StrUtil.splitTrim(prsIdStr, ',');
                List<String> nameList = StrUtil.splitTrim(nameStr, ',');
                if (prsIdList.size() == nameList.size()) {
                    for (int i = 0; i < prsIdList.size(); i++) {
                        JoinecUserVO joinecUserVO = JoinecUserVO.builder().psrId(prsIdList.get(i)).consName(nameList.get(i)).build();
                        list.add(joinecUserVO);
                    }
                    e.setJoinecUserList(list);
                    //设置中压接入点名称为所属站房名
                    if (e.getJoinecUserList() != null && !e.getJoinecUserList().isEmpty()) {
                        String stationName = fhzgGenerateGraphMapper.getStationName(e.getUserId(), dto.getLineId());
                        StringBuilder sb = new StringBuilder();
                        if (stationName != null && !stationName.isEmpty()) {
                            sb.append(stationName).append("(").append(e.getUserName()).append(")");
                            e.setUserName(sb.toString());
                        } else {
                            //站房名称为空时取专变名称拼接
                            String mid = list.stream().map(JoinecUserVO::getConsName).collect(Collectors.joining("-"));
                            sb.append(mid).append("(").append(e.getUserName()).append(")");
                            e.setUserName(sb.toString());
                        }
                    }
                } else {
                    log.info("查询中压接入点下专变数据异常，loadSwitchId:{},lineId:{},中压接入点id：{}", dto.getLoadSwitchId(), dto.getLineId(), e.getUserId());
                }
            }
        });
        return result;
    }


    /**
     * @author luorui
     * @date 2025/6/11 16:28
     * @discription 根据中压接入点查询专表列表
     **/
    @Override
    public List<JoinecUserVO> getJoinecUserListByPsrId(String joinEc) {
        List<JoinecUserVO> result = fhzgGenerateGraphMapper.getJoinecUserListByPsrId(joinEc);
        return result;
    }

    @Override
    public Page<SwitchListVO> getSwitchInfoByLoadSwitchSegmentPage(UserListQueryDTO dto) {
        Page<SwitchListVO> page = new Page(dto.getPageNum(), dto.getPageSize());
        List<String> kgType = Arrays.asList(DictConstants.KG_PSR_TYPE.split(","));
        if (dto.getPsrId() != null && !dto.getPsrId().isEmpty()) {
            page.setSize(1000);
        }
        Page<SwitchListVO> result = fhzgGenerateGraphMapper.getSwitchInfoByLoadSwitchId(page, dto, kgType);
        //入参存在指定id时仅返回指定数据
        if (dto.getPsrId() != null && !dto.getPsrId().isEmpty()) {
            result.setRecords(result.getRecords().stream().filter(e -> dto.getPsrId().equals(e.getPsrId())).collect(Collectors.toList())
            );
        }
        result.setTotal(result.getRecords().size());
        return result;
    }
}
