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.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.bf.entity.dto.FhzgPlanTransferSchemePathDefinitionDTO;
import com.hdkj.lt.bf.entity.dto.FhzgPlanTransferSchemeSwitchingSequenceAndPathDTO;
import com.hdkj.lt.bf.entity.dto.FhzgPlanTransferSchemeSwitchingSequenceCountDTO;
import com.hdkj.lt.bf.entity.vo.FhzgPlanPowerCutVO;
import com.hdkj.lt.bf.entity.vo.SectionTransferPage;
import com.hdkj.lt.bf.mapper.FhzgPlanTransferSchemePathDetailMapper;
import com.hdkj.lt.bf.mapper.FhzgPlanTransferSchemeSwitchingSequenceMapper;
import com.hdkj.lt.bf.service.FhzgPlanPowerCutService;
import com.hdkj.lt.bf.service.FhzgPlanTransferSchemePathDetailService;
import com.hdkj.lt.core.bizms.modle.dto.FhzgPlanTransferSchemePathDetailDTO;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferScheme;
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;

/**
 * @author luorui
 * @date 2025/5/15 18:16
 * <p>
 * 计划停电转供方案转供路径
 */
@Service
@Slf4j
public class FhzgPlanTransferSchemePathDetailServiceImpl implements FhzgPlanTransferSchemePathDetailService {

    @Autowired
    FhzgPlanTransferSchemePathDetailMapper fhzgPlanTransferSchemePathDetailMapper;
    @Autowired
    FhzgPlanTransferSchemeSwitchingSequenceMapper fhzgPlanTransferSchemeSwitchingSequenceMapper;
    @Autowired
    FhzgPlanPowerCutService fhzgPlanPowerCutService;
    /**
     * 根据组合方案id查询转供路径
     */
    @Override
    public SectionTransferPage<FhzgPlanTransferSchemePathDetailDTO> getTransferSchemePathDetailBySchemeId(FhzgPlanTransferScheme fhzgPlanTransferScheme) {
        if (Objects.isNull(fhzgPlanTransferScheme.getId())) {
            throw new BusinessException("组合方案id为空");
        }
        if (Objects.isNull(fhzgPlanTransferScheme.getPageNum())) {
            throw new BusinessException("分页页码为空");
        }
        if (Objects.isNull(fhzgPlanTransferScheme.getPageSize())) {
            throw new BusinessException("分页长度为空");
        }
        Page<FhzgPlanTransferScheme> page = new Page(fhzgPlanTransferScheme.getPageNum(), fhzgPlanTransferScheme.getPageSize());
        Page<FhzgPlanTransferSchemePathDetailDTO> fhzgPlanTransferSchemePathDetailDTOList = fhzgPlanTransferSchemePathDetailMapper.getTransferSchemePathDetailBySchemeId(page, fhzgPlanTransferScheme);
        //将 起始开关的名称拼接到待供开关段的最前面给前端显示
        Optional.ofNullable(fhzgPlanTransferSchemePathDetailDTOList).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<FhzgPlanTransferSchemePathDetailDTO> result = new SectionTransferPage<>();
        BeanUtil.copyProperties(fhzgPlanTransferSchemePathDetailDTOList,result);
        FhzgPlanTransferSchemePathDetailDTO totalSwitchSectionTransfer = fhzgPlanTransferSchemePathDetailMapper.getTotalSwitchSectionLoads(fhzgPlanTransferScheme);
        result.setTotalSwitchSectionLoads(Optional.ofNullable(totalSwitchSectionTransfer).map(FhzgPlanTransferSchemePathDetailDTO::getTotalSwitchSectionLoads).orElse(null));
        result.setTotalSwitchSectionLoads(result.getTotalSwitchSectionLoads().multiply(new BigDecimal("1000")));
        result.getRecords().stream().filter(i -> i.getSwitchSectionLoads() != null).forEach(i -> i.setSwitchSectionLoads(i.getSwitchSectionLoads().multiply(new BigDecimal("1000"))));
        return result;
    }


    /**
     * 根据组合方案id查询转供路径,凭借转供概述
     */
    @Override
    public FhzgPlanTransferSchemePathDefinitionDTO getTransferSchemePathDefinition(FhzgPlanTransferScheme fhzgPlanTransferScheme) {
        if (Objects.isNull(fhzgPlanTransferScheme.getId())) {
            throw new BusinessException("组合方案id为空");
        }
        if (Objects.isNull(fhzgPlanTransferScheme.getPlanId())) {
            throw new BusinessException("停电计划planId为空");
        }
        FhzgPlanPowerCutVO fhzgPlanPowerCutVO = fhzgPlanPowerCutService.getSchemeByPlanId(fhzgPlanTransferScheme.getPlanId());
        String lineName = Objects.isNull(fhzgPlanPowerCutVO) ? null : fhzgPlanPowerCutVO.getLineName();
        FhzgPlanTransferSchemePathDefinitionDTO fhzgPlanTransferSchemePathDefinitionDTO = new FhzgPlanTransferSchemePathDefinitionDTO();
        List<FhzgPlanTransferSchemePathDetailDTO> fhzgPlanTransferSchemePathDetailDTOList = fhzgPlanTransferSchemePathDetailMapper.getTransferSchemePathDetailByCombinationSchemeId(fhzgPlanTransferScheme);
        if (CollUtil.isNotEmpty(fhzgPlanTransferSchemePathDetailDTOList)) {
            //[带供路径1]带供[10KV***线] 开关段一，开关段二，开关段三等。   开关段包含起始开关和，带供开关段
            List<String> switchStrList = new ArrayList<>();
            fhzgPlanTransferSchemePathDetailDTOList.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("，"));
            fhzgPlanTransferSchemePathDefinitionDTO.setDefinition(valueStr);
        } else {
            log.info("未查询到转供路线信息，组合方案id：{}", fhzgPlanTransferScheme.getId());
        }
        return  fhzgPlanTransferSchemePathDefinitionDTO;
    }

    /**
     *
     * @author luorui
     * @date 2025/5/24 10:58
     * @discription 转供路径以及开关动作顺序概述
     *
     **/
    @Override
    public SectionTransferPage<FhzgPlanTransferSchemeSwitchingSequenceAndPathDTO> getTransferSchemePathAndSwitchById(FhzgPlanTransferScheme fhzgPlanTransferScheme) {
        if (Objects.isNull(fhzgPlanTransferScheme.getId())) {
            throw new BusinessException("组合方案id为空");
        }
        if (Objects.isNull(fhzgPlanTransferScheme.getPageNum())) {
            throw new BusinessException("分页页码为空");
        }
        if (Objects.isNull(fhzgPlanTransferScheme.getPageSize())) {
            throw new BusinessException("分页长度为空");
        }
        Page<FhzgPlanTransferScheme> page = new Page(fhzgPlanTransferScheme.getPageNum(), fhzgPlanTransferScheme.getPageSize());
        Page<FhzgPlanTransferSchemeSwitchingSequenceAndPathDTO> fhzgPlanTransferSchemePathDetailDTOList = fhzgPlanTransferSchemePathDetailMapper.getTransferSchemePathAndSwitchById(page, fhzgPlanTransferScheme);
        SectionTransferPage<FhzgPlanTransferSchemeSwitchingSequenceAndPathDTO> result = new SectionTransferPage<>();
        BeanUtil.copyProperties(fhzgPlanTransferSchemePathDetailDTOList,result);

        FhzgPlanTransferSchemeSwitchingSequenceCountDTO fhzgPlanTransferSchemeSwitchingSequenceCountDTO = fhzgPlanTransferSchemeSwitchingSequenceMapper.countSwitch(fhzgPlanTransferScheme.getId());
        //查询开关动作次数的总数，和人工倒闸次数
        result.setSwitchOperationTimes(fhzgPlanTransferSchemeSwitchingSequenceCountDTO.getSwitchOperationTimes());
        result.setNonAutoSwitchOperationTimes(fhzgPlanTransferSchemeSwitchingSequenceCountDTO.getNonAutoSwitchOperationTimes());
        result.getRecords().stream().filter(i -> i.getSwitchSectionLoads() != null).forEach(i -> i.setSwitchSectionLoads(i.getSwitchSectionLoads().multiply(new BigDecimal("1000"))));
        return result;
    }


}
