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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdkj.lt.base.exception.BusinessException;
import com.hdkj.lt.bf.constants.TransferSchemeConstants;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferSchemeEvaluationIndex;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferStrategyConfigDetail;
import com.hdkj.lt.bf.entity.dto.EvaluationHeadDTO;
import com.hdkj.lt.core.bizms.modle.dto.FhzgPlanTransferSchemeEvaluationIndexDTO;
import com.hdkj.lt.core.bizms.modle.dto.TransferSchemeEvaluationReqDTO;
import com.hdkj.lt.bf.entity.vo.TransferSchemeEvaluationIndexVO;
import com.hdkj.lt.bf.mapper.FhzgPlanTransferSchemeEvaluationIndexMapper;
import com.hdkj.lt.bf.service.FhzgPlanStrategyService;
import com.hdkj.lt.bf.service.IFhzgPlanTransferSchemeEvaluationIndexService;
import com.hdkj.lt.core.sys.dao.SysDictMapper;
import com.hdkj.lt.core.sys.model.po.DicSingle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 转供方案评比指标数据表 服务实现类
 * </p>
 *
 * @author luorui
 * @since 2025-05-23
 */
@Service
@Slf4j
public class FhzgPlanTransferSchemeEvaluationIndexServiceImpl extends ServiceImpl<FhzgPlanTransferSchemeEvaluationIndexMapper, FhzgPlanTransferSchemeEvaluationIndex> implements IFhzgPlanTransferSchemeEvaluationIndexService {

    @Autowired
    FhzgPlanStrategyService fhzgPlanStrategyService;

    @Autowired
    SysDictMapper sysDictMapper;

    private static final String TRANSFER_EVALUATION_INDEX = "transfer_evaluation_index";
    private static final String SCHEME_EVALUATION_RISK_WARNING = "scheme_evaluation_risk_warning";
    private static final String SWITCH_OPERATION_TIMES = "switchOperationTimes";
    private static final String DISTRIBUTION_TRANSFORMER_VOLTAGE = "distributionTransformerVoltage";
    private static final String OPPOSITE_LINE_MAX_LOAD_RATE1 = "oppositeLineMaxLoadRate1";
    private static final String OPPOSITE_LINE_MAX_LOAD_RATE2 = "oppositeLineMaxLoadRate2";



    /**
     * @author luorui
     * @date 2025/5/23 15:32
     * @discription 根据计划编码查询评分指标和方案评分指标值
     **/
    @Override
    public TransferSchemeEvaluationIndexVO getTransferSchemeEvaluationIndexByPlanId(TransferSchemeEvaluationReqDTO transferSchemeEvaluationReqDTO) {
        if (Objects.isNull(transferSchemeEvaluationReqDTO.getPlanId())) {
            throw new BusinessException("计划编码为空planId");
        }
        //查询该计划使用的 策略表头
        List<FhzgPlanTransferStrategyConfigDetail>  strategyConfigList = fhzgPlanStrategyService.getStrategyDetailByPlanId(transferSchemeEvaluationReqDTO.getPlanId());
        if (CollUtil.isEmpty(strategyConfigList)) {
            log.info("评分策略信息为空");
        }
        List<EvaluationHeadDTO> strategyConfigHeadList = caseStrategyConfig(strategyConfigList);
        //查询表头信息 指标
        List<DicSingle> dicSingleList = sysDictMapper.getDictSingleByTypeName(TRANSFER_EVALUATION_INDEX);
        if (CollUtil.isEmpty(dicSingleList)) {
            log.error("评分指标字典信息为空");
            throw new BusinessException("评分指标字典信息为空");
        }
        List<EvaluationHeadDTO> evaluationHeadList = caseDic(dicSingleList);
        List<EvaluationHeadDTO> headDTOList = new ArrayList<>();
        headDTOList.addAll(strategyConfigHeadList);//有序
        headDTOList.addAll(evaluationHeadList);//有序
        //查询方案信息
        TransferSchemeEvaluationIndexVO transferSchemeEvaluationIndexVO = new TransferSchemeEvaluationIndexVO();
        List<FhzgPlanTransferSchemeEvaluationIndexDTO> shemeList = baseMapper.getTransferSchemeEvaluationIndexByPlanId(transferSchemeEvaluationReqDTO);
        shemeList.stream().filter(i -> i.getToBeTransferLoad() != null).forEach(i->i.setToBeTransferLoad(i.getToBeTransferLoad().multiply(new BigDecimal("1000"))));
        shemeList.stream().filter(i -> i.getCarriedLoad() != null).forEach(i->i.setCarriedLoad(i.getCarriedLoad().multiply(new BigDecimal("1000"))));
        transferSchemeEvaluationIndexVO.setShemeList(shemeList);
        transferSchemeEvaluationIndexVO.setHeadList(headDTOList);

        return transferSchemeEvaluationIndexVO;
    }

    /**
     *
     * @author luorui
     * @date 2025/5/23 20:52
     * @discription 根据方案编码查询风险提示信息
     *
     **/
    @Override
    public List<String> getTransferSchemeRiskWarningById(TransferSchemeEvaluationReqDTO transferSchemeEvaluationReqDTO) {
        Long schemeId = transferSchemeEvaluationReqDTO.getSchemeId();
        if (Objects.isNull(transferSchemeEvaluationReqDTO.getSchemeId())) {
            throw new BusinessException("方案编码为空");
        }
        //风险提示数据字典
        List<DicSingle> dicSingleList = sysDictMapper.getDictSingleByTypeName(SCHEME_EVALUATION_RISK_WARNING);
        if(CollUtil.isEmpty(dicSingleList)){
            throw new BusinessException("风险提示数据字典为空");
        }
        List<String> result = new ArrayList<>();
        Map<String,String> dicSingleMap = dicSingleList.stream().collect(Collectors.toMap(DicSingle::getValue, DicSingle::getLabel, (k1, k2) -> k2));
        LambdaQueryWrapper<FhzgPlanTransferSchemeEvaluationIndex> queryWrapper = new LambdaQueryWrapper<FhzgPlanTransferSchemeEvaluationIndex>()
                .eq(FhzgPlanTransferSchemeEvaluationIndex::getSchemeId, schemeId).last(" limit 1");
        FhzgPlanTransferSchemeEvaluationIndex fhzgPlanTransferSchemeEvaluationIndex = baseMapper.selectOne(queryWrapper);
        if (Objects.isNull(fhzgPlanTransferSchemeEvaluationIndex)) {
            log.info("方案未查询到指标数据schemeId：{}", schemeId);
            return result;
        }
        Integer switchOperationTimes = fhzgPlanTransferSchemeEvaluationIndex.getSwitchOperationTimes();//开关动作次数
        if (switchOperationTimes != null && switchOperationTimes > 4) {
            result.add(dicSingleMap.get(SWITCH_OPERATION_TIMES));
        }
        Integer  distributionTransformerVoltage = fhzgPlanTransferSchemeEvaluationIndex.getDistributionTransformerVoltage();// 配变低压台数
        if (distributionTransformerVoltage != null) {
            result.add(String.format(dicSingleMap.get(DISTRIBUTION_TRANSFORMER_VOLTAGE), distributionTransformerVoltage));
        } else {
            result.add(String.format(dicSingleMap.get(DISTRIBUTION_TRANSFORMER_VOLTAGE), "-"));
        }
        BigDecimal oppositeLineMaxLoadRate = fhzgPlanTransferSchemeEvaluationIndex.getOppositeLineMaxLoadRate();//对侧线路最大负载率
        if (oppositeLineMaxLoadRate != null && oppositeLineMaxLoadRate.compareTo( new BigDecimal("80")) >= 0) {
            result.add(dicSingleMap.get(OPPOSITE_LINE_MAX_LOAD_RATE1));
        }
        if (oppositeLineMaxLoadRate !=null && oppositeLineMaxLoadRate.compareTo( new BigDecimal("100")) >= 0) {
            result.add(dicSingleMap.get(OPPOSITE_LINE_MAX_LOAD_RATE2));
        }
        return result;
    }


    /**
     * @author luorui
     * @date 2025/5/23 15:58
     * @discription 将字典表数据转换成前端字段
     **/
    private List<EvaluationHeadDTO> caseDic(List<DicSingle> dicSingleList) {
        List<EvaluationHeadDTO> evaluationHeadDTOList = new ArrayList<>();
        dicSingleList.forEach(e -> {
            EvaluationHeadDTO evaluationHeadDTO = new EvaluationHeadDTO();
            evaluationHeadDTO.setCode(e.getValue());
            evaluationHeadDTO.setSort(e.getSort());
            evaluationHeadDTO.setName(e.getLabel());
            evaluationHeadDTO.setIsStrategy(TransferSchemeConstants.YesOrNo.NO);
            evaluationHeadDTOList.add(evaluationHeadDTO);
        });
        return evaluationHeadDTOList;
    }

    /**
     * @author luorui
     * @date 2025/5/23 15:58
     * @discription 转换策略表头
     **/
    private List<EvaluationHeadDTO> caseStrategyConfig(List<FhzgPlanTransferStrategyConfigDetail>  strategyConfigList) {
        List<EvaluationHeadDTO> evaluationHeadDTOList = new ArrayList<>();
        if(CollUtil.isNotEmpty(strategyConfigList)){
            strategyConfigList.forEach(e -> {
                EvaluationHeadDTO evaluationHeadDTO = new EvaluationHeadDTO();
                evaluationHeadDTO.setCode(e.getIndicatorCode());
                evaluationHeadDTO.setSort(e.getPriority());
                evaluationHeadDTO.setName(e.getIndicatorName());
                evaluationHeadDTO.setIsStrategy(TransferSchemeConstants.YesOrNo.YES);
                evaluationHeadDTOList.add(evaluationHeadDTO);
            });
        }
        return evaluationHeadDTOList;
    }



}
