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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.bf.entity.dto.FaultTransferSchemeSwitchingSequenceAndPathDTO;
import com.hdkj.lt.bf.entity.dto.FhzgFaultTransferSchemePathDefinitionDTO;
import com.hdkj.lt.bf.entity.dto.FhzgPlanTransferSchemeSwitchingSequenceCountDTO;
import com.hdkj.lt.bf.entity.vo.FhzgFaultPowerCutVO;
import com.hdkj.lt.bf.entity.vo.SectionTransferPage;
import com.hdkj.lt.bf.mapper.FaultTransferSchemePathDetailMapper;
import com.hdkj.lt.bf.mapper.FaultTransferSchemeSwitchingSequenceMapper;
import com.hdkj.lt.bf.service.IFaultPowerCutService;
import com.hdkj.lt.bf.service.IFaultTransferSchemePathDetailService;
import com.hdkj.lt.core.bizms.modle.dto.FhzgFaultTransferSchemePathDetailDTO;
import com.hdkj.lt.core.bizms.modle.po.fault.FaultTransferScheme;
import com.hdkj.lt.core.bizms.modle.po.fault.FaultTransferSchemePathDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 故障停电转供方案路径明细信息表(联络开关) 服务实现类
 * </p>
 *
 * @author luorui
 * @since 2025-05-29
 */
@Service
@Slf4j
public class FaultTransferSchemePathDetailServiceImpl extends ServiceImpl<FaultTransferSchemePathDetailMapper, FaultTransferSchemePathDetail> implements IFaultTransferSchemePathDetailService {
    @Autowired
    FaultTransferSchemePathDetailMapper faultTransferSchemePathDetailMapper;
    @Autowired
    FaultTransferSchemeSwitchingSequenceMapper faultTransferSchemeSwitchingSequenceMapper;
    @Autowired
    IFaultPowerCutService fhzgFaultPowerCutService;

    @Autowired
    FaultTransferSchemePathDetailMapper fhzgFaultTransferSchemePathDetailMapper;

    @Autowired
    IFaultPowerCutService faultPowerCutService;
//   /**
//     * 根据组合方案id查询转供路径
//     */
//    @Override
//    public SectionTransferPage<FaultTransferSchemePathDetailDTO> getTransferSchemePathDetailBySchemeId(FaultTransferScheme faultTransferScheme) {
//        if (Objects.isNull(faultTransferScheme.getId())) {
//            throw new BusinessException("组合方案id为空");
//        }
//        if (Objects.isNull(faultTransferScheme.getPageNum())) {
//            throw new BusinessException("分页页码为空");
//        }
//        if (Objects.isNull(faultTransferScheme.getPageSize())) {
//            throw new BusinessException("分页长度为空");
//        }
//        Page<FaultTransferScheme> page = new Page(faultTransferScheme.getPageNum(), faultTransferScheme.getPageSize());
//        Page<FaultTransferSchemePathDetailDTO> fhzgFaultTransferSchemePathDetailDTOList = faultTransferSchemePathDetailMapper.getTransferSchemePathDetailBySchemeId(page, faultTransferScheme);
//        //将 起始开关的名称拼接到待供开关段的最前面给前端显示
//        Optional.ofNullable(fhzgFaultTransferSchemePathDetailDTOList).map(Page::getRecords).ifPresent(data->{
//            data.stream().forEach(e->{
//                e.setSwitchSectionName(StrUtil.isBlank(e.getStartSwitchName()) ? e.getSwitchSectionName() : e.getStartSwitchName() + "," + e.getSwitchSectionName());
//            });
//        });
//        SectionTransferPage<FhzgFaultTransferSchemePathDetailDTO> result = new SectionTransferPage<>();
//        BeanUtil.copyProperties(fhzgFaultTransferSchemePathDetailDTOList,result);
//        FhzgFaultTransferSchemePathDetailDTO totalSwitchSectionTransfer = faultTransferSchemeSwitchingSequenceMapper.getTotalSwitchSectionLoads(fhzgFaultTransferScheme);
//        result.setTotalSwitchSectionLoads(Optional.ofNullable(totalSwitchSectionTransfer).map(FhzgFaultTransferSchemePathDetailDTO::getTotalSwitchSectionLoads).orElse(null));
//        return result;
//    }
//


    /**
     * 根据组合方案id查询转供路径,凭借转供概述
     */
    @Override
    public FhzgFaultTransferSchemePathDefinitionDTO getTransferSchemePathDefinition(FaultTransferScheme fhzgFaultTransferScheme) {
        if (Objects.isNull(fhzgFaultTransferScheme.getId())) {
            throw new BusinessException("组合方案id为空");
        }
        if (Objects.isNull(fhzgFaultTransferScheme.getFaultId())) {
            throw new BusinessException("停电计划FaultId为空");
        }
        FhzgFaultPowerCutVO fhzgFaultPowerCutVO = fhzgFaultPowerCutService.getSchemeByFaultId(fhzgFaultTransferScheme.getFaultId());
        String lineName = Objects.isNull(fhzgFaultPowerCutVO) ? null : fhzgFaultPowerCutVO.getLineName();
        FhzgFaultTransferSchemePathDefinitionDTO fhzgFaultTransferSchemePathDefinitionDTO = new FhzgFaultTransferSchemePathDefinitionDTO();
        List<FhzgFaultTransferSchemePathDetailDTO> fhzgFaultTransferSchemePathDetailDTOList = fhzgFaultTransferSchemePathDetailMapper.getTransferSchemePathDetailByCombinationSchemeId(fhzgFaultTransferScheme);
        if (CollUtil.isNotEmpty(fhzgFaultTransferSchemePathDetailDTOList)) {
            //[带供路径1]带供[10KV***线] 开关段一，开关段二，开关段三等。   开关段包含起始开关和，带供开关段
            List<String> switchStrList = new ArrayList<>();
            fhzgFaultTransferSchemePathDetailDTOList.forEach(data -> {
                String oppositeLineName = data.getOppositeLineName();
                String startSwitchName = data.getStartSwitchName();
                String switchSectionNameStr = data.getSwitchSectionName();//存储时候用“，”拼接
                List<String> switchNameList = new ArrayList<>();//集合 开始开关名称和 带供的开关名称
                List<String> switchSectionNameList = StrUtil.split(switchSectionNameStr, ',', true, false);
                Optional.ofNullable(startSwitchName).ifPresent(e -> switchNameList.add(startSwitchName)); //将开始开关添加进去
                switchNameList.addAll(switchSectionNameList);
                //超过3个元素，用“等”拼接结束
                String switchStr;
                if (switchNameList.size() > 3) {
                    switchStr = switchSectionNameList.stream().limit(3).collect(Collectors.joining("、")) + "等";
                } else {
                    switchStr = switchSectionNameList.stream().limit(3).collect(Collectors.joining("、"));
                }
                StringBuilder builder = StrUtil.builder();
                builder.append("【")
                        .append(oppositeLineName)
                        .append("】")
                        .append("带供")
                        .append("【")
                        .append(lineName)
                        .append("】")
                        .append(switchStr);
                switchStrList.add(builder.toString());
            });
            //将多组线路用换行符号拼接
            String valueStr = switchStrList.stream().collect(Collectors.joining("，"));
            fhzgFaultTransferSchemePathDefinitionDTO.setDefinition(valueStr);
        } else {
            log.info("未查询到转供路线信息，组合方案id：{}", fhzgFaultTransferScheme.getId());
        }
        return fhzgFaultTransferSchemePathDefinitionDTO;
    }

    /**
     * @author luorui
     * @date 2025/5/24 10:58
     * @discription 转供路径以及开关动作顺序概述
     **/
    @Override
    public SectionTransferPage<FaultTransferSchemeSwitchingSequenceAndPathDTO> getTransferSchemePathAndSwitchById(FaultTransferScheme faultTransferScheme) {
        if (Objects.isNull(faultTransferScheme.getId())) {
            throw new BusinessException("组合方案id为空");
        }
        if (Objects.isNull(faultTransferScheme.getPageNum())) {
            throw new BusinessException("分页页码为空");
        }
        if (Objects.isNull(faultTransferScheme.getPageSize())) {
            throw new BusinessException("分页长度为空");
        }
        Page<FaultTransferScheme> page = new Page(faultTransferScheme.getPageNum(), faultTransferScheme.getPageSize());
        Page<FaultTransferSchemeSwitchingSequenceAndPathDTO> faultTransferSchemeSwitchingSequenceAndPathDTOList = faultTransferSchemePathDetailMapper.getTransferSchemePathAndSwitchById(page, faultTransferScheme);
        SectionTransferPage<FaultTransferSchemeSwitchingSequenceAndPathDTO> result = new SectionTransferPage<>();
        BeanUtil.copyProperties(faultTransferSchemeSwitchingSequenceAndPathDTOList, result);
        FhzgPlanTransferSchemeSwitchingSequenceCountDTO fhzgFaultTransferSchemeSwitchingSequenceCountDTO = faultTransferSchemeSwitchingSequenceMapper.countSwitch(faultTransferScheme.getId());
        //查询开关动作次数的总数，和人工倒闸次数
        result.setSwitchOperationTimes(fhzgFaultTransferSchemeSwitchingSequenceCountDTO.getSwitchOperationTimes());
        result.setNonAutoSwitchOperationTimes(fhzgFaultTransferSchemeSwitchingSequenceCountDTO.getNonAutoSwitchOperationTimes());
        result.getRecords().stream().filter(i -> i.getSwitchSectionLoads() != null).forEach(i -> i.setSwitchSectionLoads(i.getSwitchSectionLoads().multiply(new BigDecimal("1000"))));
        return result;
    }

    @Override
    public SectionTransferPage<FhzgFaultTransferSchemePathDetailDTO> getTransferSchemePathDetailBySchemeId(FaultTransferScheme faultTransferScheme) {
        if (Objects.isNull(faultTransferScheme.getId())) {
            throw new BusinessException("组合方案id为空");
        }
        if (Objects.isNull(faultTransferScheme.getPageNum())) {
            throw new BusinessException("分页页码为空");
        }
        if (Objects.isNull(faultTransferScheme.getPageSize())) {
            throw new BusinessException("分页长度为空");
        }
        Page<FaultTransferScheme> page = new Page(faultTransferScheme.getPageNum(), faultTransferScheme.getPageSize());
        Page<FhzgFaultTransferSchemePathDetailDTO> fhzgFaultTransferSchemePathDetailDTOList = faultTransferSchemePathDetailMapper.getTransferSchemePathDetailBySchemeId(page, faultTransferScheme);
        //将 起始开关的名称拼接到待供开关段的最前面给前端显示
        Optional.ofNullable(fhzgFaultTransferSchemePathDetailDTOList).map(Page::getRecords).ifPresent(data -> {
            data.stream().forEach(e -> {
                e.setSwitchSectionName(StrUtil.isBlank(e.getStartSwitchName()) ? e.getSwitchSectionName() : e.getStartSwitchName() + "," + e.getSwitchSectionName());
                // 需要剔除开关段表中的联络开关ID，并移动到结束开关中（20250620）
                String linkSwitchId = e.getSwitchId();
                // 开始开关重新赋值
                Optional.ofNullable(e.getSwitchSectionId())
                        .ifPresent(en -> e.setSwitchSectionId(en.replace(String.format("%s,", linkSwitchId), "")
                                .replace(String.format(",%s", linkSwitchId), "")));
                // 结束开关重新赋值
                e.setEndSwitchId(String.format("%s,%s", e.getEndSwitchId(), linkSwitchId));
            });
        });
        SectionTransferPage<FhzgFaultTransferSchemePathDetailDTO> result = new SectionTransferPage<>();
        BeanUtil.copyProperties(fhzgFaultTransferSchemePathDetailDTOList, result);
        FhzgFaultTransferSchemePathDetailDTO totalSwitchSectionTransfer = faultTransferSchemePathDetailMapper.getTotalSwitchSectionLoads(faultTransferScheme);
        result.setTotalSwitchSectionLoads(Optional.ofNullable(totalSwitchSectionTransfer).map(FhzgFaultTransferSchemePathDetailDTO::getTotalSwitchSectionLoads).orElse(null));
        result.setTotalSwitchSectionLoads(result.getTotalSwitchSectionLoads().multiply(new BigDecimal("1000")));
        result.getRecords().forEach(i -> i.setSwitchSectionLoads(i.getSwitchSectionLoads().multiply(new BigDecimal("1000"))));
        return result;
    }

}
