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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.IdUtil;
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.core.bizms.modle.dto.FhzgPlanAwaitTransferUsersCountDTO;

import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferScheme;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferSchemeEvaluationIndex;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferSchemeSwitchingSequence;
import com.hdkj.lt.core.bizms.modle.po.plan.FhzgPlanTransferSchemeUsers;

import com.hdkj.lt.mq.mapper.plan.*;
import com.hdkj.lt.mq.service.plan.IPlanTransferSchemeSwitchingSequenceService;
import com.hdkj.lt.mq.service.plan.PlanTransferSchemeEvaluationIndexService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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


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

    private final FhzgPlanTransferSchemeUsersMapper fhzgPlanTransferSchemeUsersMapper;

    private final FhzgPlanTransferSchemePathDetailMapper fhzgPlanTransferSchemePathDetailMapper;

    private final FhzgPlanAwaitTransferUsersMapper fhzgPlanAwaitTransferUsersMapper;

    private final FhzgPlanTransferSchemeMapper fhzgPlanTransferSchemeMapper;

    private final IPlanTransferSchemeSwitchingSequenceService planTransferSchemeSwitchingSequenceService;

    private final PlanSchemeOppositeLineLoadFactorMapper planSchemeOppositeLineLoadFactorMapper;

    /**
     * @author luorui
     * @date 2025/5/28 9:57
     * @discription 计算推演平台数据落库完成后，将计算评分所需要的指标数据全部挑选出来存到，指标数据表待后续计算评分使用
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public List<FhzgPlanTransferSchemeEvaluationIndex> saveSchemeEvaluationIndex(Long planId) {
        if (Objects.isNull(planId)) {
            throw new BusinessException("请求参数，计划比编码为空");
        }
        Map<Long, FhzgPlanTransferSchemeEvaluationIndex> resultMap = new HashMap<>();
        //1.根据计划查询所有方案 构建成Map结构 K->schemeId, V->FhzgPlanTransferSchemeEvaluationIndex
        List<Long> schemeList = fhzgPlanTransferSchemeMapper.getShemeIdByPlanId(planId);
        if (CollUtil.isEmpty(schemeList)) {
            log.info("计划未查询到方案信息，planId：{}", planId);
            return new ArrayList<>();
        }
        Snowflake snowflake = IdUtil.getSnowflake(1,1);
        schemeList.forEach(schemeId -> {
            FhzgPlanTransferSchemeEvaluationIndex fhzgPlanTransferSchemeEvaluationIndex = new FhzgPlanTransferSchemeEvaluationIndex();
            fhzgPlanTransferSchemeEvaluationIndex.setSchemeId(schemeId);//方案编码
            fhzgPlanTransferSchemeEvaluationIndex.setId(snowflake.nextId());//主键
            fhzgPlanTransferSchemeEvaluationIndex.setCreateTime(LocalDateTime.now());
            resultMap.put(schemeId, fhzgPlanTransferSchemeEvaluationIndex);
            //2.设置每一项指标值
            FhzgPlanTransferScheme fhzgPlanTransferScheme = fhzgPlanTransferSchemeMapper.selectById(schemeId);
            BigDecimal transferLoadRatio = null; // 转出负荷比例（%）
            Integer switchOperationTimes = null; //  开关动作次数
            Integer lossUsers = null; // 转出负荷比例（%）
            Integer nonAutoSwitchOperationTimes = null;// 非自动化开关动作次数
            BigDecimal oppositeLineMaxLoadRate = null; // 对侧线路最大负载率（%）
            Integer distributionTransformerVoltage = null; // 配变低压台数

            BigDecimal toBeTransferLoad = null;//待转供负荷（MW）
            BigDecimal carriedLoad = null;//带供负荷（MW）
            Integer autoSwitchOperationTimes = null;//自动化开关动作次数
            Integer totalToBeTransferUsers = null;//待转供用户总数
            Integer lossImportantUsers = null;//损失重要户数
            Integer lossSensitiveUsers = null;//损失敏感户数
            Integer lossPowerSecuredUsers = null;
            //对侧线路最大负载率（%）
            if (!Objects.isNull(fhzgPlanTransferScheme)) {
                // 转出负荷比例（%）
                transferLoadRatio = fhzgPlanTransferScheme.getLoadRecovery();
                //  开关动作次数
                switchOperationTimes = fhzgPlanTransferScheme.getSwitchOperationCount();
                //  损失户数
                lossUsers = fhzgPlanTransferScheme.getLossUsers();

            }
            // 非自动化开关动作次数
            Long switchingAutoSequenceCount = getSwitchingSequenceBySchemeId(schemeId);
            nonAutoSwitchOperationTimes = (switchOperationTimes != null && switchingAutoSequenceCount != null) ? switchOperationTimes - switchingAutoSequenceCount.intValue() : null;
            // 对侧线路最大负载率（%）
            oppositeLineMaxLoadRate = planSchemeOppositeLineLoadFactorMapper.getMaxOppositeLineLoadFactorBySchemeId(schemeId);
            // 配变低压台数
            distributionTransformerVoltage = fhzgPlanTransferSchemeUsersMapper.getLowVoltageNum(schemeId);
            // 待转供负荷（MW）
            FhzgPlanAwaitTransferUsersCountDTO fhzgPlanAwaitTransferUsersCountDTO = fhzgPlanAwaitTransferUsersMapper.selectAwaitUserCountAnduserLoads(planId);
            toBeTransferLoad = fhzgPlanAwaitTransferUsersCountDTO != null ? fhzgPlanAwaitTransferUsersCountDTO.getUserLoads() : null;
            //待转供用户总数
            totalToBeTransferUsers = fhzgPlanAwaitTransferUsersCountDTO != null ? fhzgPlanAwaitTransferUsersCountDTO.getUserCount() : null;
            //带供负荷（MW）
            BigDecimal totalSwitchSectionTransfer = fhzgPlanTransferSchemePathDetailMapper.getTotalSwitchSectionTransfer(fhzgPlanTransferScheme);
            carriedLoad = totalSwitchSectionTransfer;
            //自动化开关动作次数
            autoSwitchOperationTimes = switchingAutoSequenceCount != null ? switchingAutoSequenceCount.intValue() : null;
            //损失重要户数
            //损失敏感户数
            FhzgPlanTransferSchemeUsers planTransferSchemeUsers = fhzgPlanTransferSchemeUsersMapper.countCriticalAndSensitiveUsers(schemeId);
            lossImportantUsers = planTransferSchemeUsers != null ? planTransferSchemeUsers.getCriticalUserCount() : null;
            lossSensitiveUsers = planTransferSchemeUsers != null ? planTransferSchemeUsers.getSensitiveUserCount() : null;
            lossPowerSecuredUsers = planTransferSchemeUsers != null ? planTransferSchemeUsers.getProtectUserCount() : null;
            fhzgPlanTransferSchemeEvaluationIndex.setTransferLoadRatio(transferLoadRatio);
            fhzgPlanTransferSchemeEvaluationIndex.setLossUsers(lossUsers);
            fhzgPlanTransferSchemeEvaluationIndex.setSwitchOperationTimes(switchOperationTimes);
            fhzgPlanTransferSchemeEvaluationIndex.setNonAutoSwitchOperationTimes(nonAutoSwitchOperationTimes);
            fhzgPlanTransferSchemeEvaluationIndex.setOppositeLineMaxLoadRate(oppositeLineMaxLoadRate);
            fhzgPlanTransferSchemeEvaluationIndex.setDistributionTransformerVoltage(distributionTransformerVoltage);

            fhzgPlanTransferSchemeEvaluationIndex.setToBeTransferLoad(toBeTransferLoad);
            fhzgPlanTransferSchemeEvaluationIndex.setCarriedLoad(carriedLoad);
            fhzgPlanTransferSchemeEvaluationIndex.setAutoSwitchOperationTimes(autoSwitchOperationTimes);
            fhzgPlanTransferSchemeEvaluationIndex.setTotalToBeTransferUsers(totalToBeTransferUsers);
            fhzgPlanTransferSchemeEvaluationIndex.setLossImportantUsers(lossImportantUsers);
            fhzgPlanTransferSchemeEvaluationIndex.setLossSensitiveUsers(lossSensitiveUsers);
            fhzgPlanTransferSchemeEvaluationIndex.setLossPowerSecuredUsers(lossPowerSecuredUsers);

        });
        //3批量保存数据
        List<FhzgPlanTransferSchemeEvaluationIndex> fhzgPlanTransferSchemeEvaluationIndexList = resultMap.values().stream().collect(Collectors.toList());
        //先删除数据,评分指标和，评分数据
        this.deleteScoreData(planId);
        this.saveBatch(fhzgPlanTransferSchemeEvaluationIndexList);
        return fhzgPlanTransferSchemeEvaluationIndexList;
    }

    /**
     *
     * @author luorui
     * @date 2025/5/28 15:39
     * @discription 删除评分相关数据
     *
     **/
    @Override
    public Integer deleteScoreData(Long planId) {
        return baseMapper.deleteScoreData(planId);
    }


    /**
     * @author luorui
     * @date 2025/5/28 12:05
     * @discription 查询自动开关的数量
     **/
    private Long getSwitchingSequenceBySchemeId(Long schemeId) {
        LambdaQueryWrapper<FhzgPlanTransferSchemeSwitchingSequence> queryWrapper = new LambdaQueryWrapper<FhzgPlanTransferSchemeSwitchingSequence>()
                .eq(FhzgPlanTransferSchemeSwitchingSequence::getSchemeId, schemeId)
                .eq(FhzgPlanTransferSchemeSwitchingSequence::getIsAutoSwitch, 1);
        return planTransferSchemeSwitchingSequenceService.count(queryWrapper);
    }


}
