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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
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.fault.FaultTransferScheme;
import com.hdkj.lt.core.bizms.modle.po.fault.FaultTransferSchemeEvaluationIndex;
import com.hdkj.lt.core.bizms.modle.po.fault.FaultTransferSchemeUsers;
import com.hdkj.lt.mq.mapper.fault.*;
import com.hdkj.lt.mq.service.fault.FaultTransferSchemeEvaluationIndexService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

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

/**
 * @author rj
 * @date 2025/5/28 10:14
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FaultTransferSchemeEvaluationIndexServiceImpl extends ServiceImpl<FhzgFaultTransferSchemeEvaluationIndexMapper, FaultTransferSchemeEvaluationIndex> implements FaultTransferSchemeEvaluationIndexService {

    private final FaultTransferSchemeServiceImpl fhzgFaultTransferSchemeServiceImpl;

    private final FaultSchemeOppositeLineLoadFactorMapper faultTransferSchemeOppositeLineLoadFactorMapper;

    private final FaultAwaitTransferUsersMapper fhzgFaultAwaitTransferUsersMapper;

    private final FhzgFaultTransferSchemePathDetailMapper fhzgFaultTransferSchemePathDetailMapper;

    private final FhzgFaultTransferSchemeUsersMapper fhzgFaultTransferSchemeUsersMapper;


    @Override
    public List<FaultTransferSchemeEvaluationIndex> saveSchemeEvaluationIndex(Long faultId) {
        if (Objects.isNull(faultId)) {
            throw new BusinessException("请求参数，计划比编码为空");
        }
        Map<Long, FaultTransferSchemeEvaluationIndex> resultMap = new HashMap<>();
        //1.根据计划查询所有方案 构建成Map结构 K->schemeId, V->FhzgPlanTransferSchemeEvaluationIndex
        List<Long> schemeList = baseMapper.getShemeIdByFaultId(faultId);
        if (CollUtil.isEmpty(schemeList)) {
            log.info("计划未查询到方案信息，faultId：{}", faultId);
            return new ArrayList<>();
        }
        schemeList.forEach(schemeId -> {
            FaultTransferSchemeEvaluationIndex faultTransferSchemeEvaluationIndex = new FaultTransferSchemeEvaluationIndex();
            faultTransferSchemeEvaluationIndex.setSchemeId(schemeId);//方案编码
            faultTransferSchemeEvaluationIndex.setCreateTime(LocalDateTime.now());
            resultMap.put(schemeId, faultTransferSchemeEvaluationIndex);
            //2.设置每一项指标值
            FaultTransferScheme faultTransferScheme = fhzgFaultTransferSchemeServiceImpl.getById(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(faultTransferScheme)) {
                // 转出负荷比例（%）
                transferLoadRatio = faultTransferScheme.getLoadRecovery();
                //  开关动作次数非自动化开关/开关动作次数
                String[] switchOperationArray = Optional.ofNullable(faultTransferScheme.getSwitchOperationCount()).map(e -> e.split("/")).orElse(null);
                if (ObjectUtils.isNotEmpty(switchOperationArray) && switchOperationArray.length >= 2) {
                    // 开关动作次数
                    switchOperationTimes = Optional.ofNullable(switchOperationArray[1]).map(Integer::valueOf).orElse(null);
                    // 非自动化开关动作次数
                    nonAutoSwitchOperationTimes = Optional.ofNullable(switchOperationArray[0]).map(Integer::valueOf).orElse(null);
                }
                //  损失户数
                lossUsers = faultTransferScheme.getLossUsers();
            }

            // 对侧线路最大负载率（%）
            oppositeLineMaxLoadRate = faultTransferSchemeOppositeLineLoadFactorMapper.getMaxOppositeLineLoadFactorBySchemeId(schemeId);
            // 配变低压台数
            distributionTransformerVoltage = fhzgFaultTransferSchemeUsersMapper.getLowVoltageNum(schemeId);

            // 待转供负荷（MW）
            FhzgPlanAwaitTransferUsersCountDTO fhzgPlanAwaitTransferUsersCountDTO = fhzgFaultAwaitTransferUsersMapper.selectAwaitUserCountAnduserLoads(faultId);
            toBeTransferLoad = fhzgPlanAwaitTransferUsersCountDTO != null ? fhzgPlanAwaitTransferUsersCountDTO.getUserLoads() : null;
            //待转供用户总数
            totalToBeTransferUsers = fhzgPlanAwaitTransferUsersCountDTO != null ? fhzgPlanAwaitTransferUsersCountDTO.getUserCount() : null;
            //带供负荷（MW）
            BigDecimal totalSwitchSectionTransfer = fhzgFaultTransferSchemePathDetailMapper.getTotalSwitchSectionTransfer(faultTransferScheme);
            carriedLoad = totalSwitchSectionTransfer;
            //自动化开关动作次数
            autoSwitchOperationTimes = ObjectUtils.allNotNull(switchOperationTimes,nonAutoSwitchOperationTimes) ? switchOperationTimes - nonAutoSwitchOperationTimes : null;
            //损失重要户数
            //损失敏感户数
            FaultTransferSchemeUsers planTransferSchemeUsers = fhzgFaultTransferSchemeUsersMapper.countCriticalAndSensitiveUsers(schemeId);
            lossImportantUsers = planTransferSchemeUsers != null ? planTransferSchemeUsers.getCriticalUserCount() : null;
            lossSensitiveUsers = planTransferSchemeUsers != null ? planTransferSchemeUsers.getSensitiveUserCount() : null;
            lossPowerSecuredUsers = planTransferSchemeUsers != null ? planTransferSchemeUsers.getProtectUserCount() : null;
            faultTransferSchemeEvaluationIndex.setTransferLoadRatio(transferLoadRatio);
            faultTransferSchemeEvaluationIndex.setLossUsers(lossUsers);
            faultTransferSchemeEvaluationIndex.setSwitchOperationTimes(switchOperationTimes);
            faultTransferSchemeEvaluationIndex.setNonAutoSwitchOperationTimes(nonAutoSwitchOperationTimes);
            faultTransferSchemeEvaluationIndex.setOppositeLineMaxLoadRate(oppositeLineMaxLoadRate);
            faultTransferSchemeEvaluationIndex.setDistributionTransformerVoltage(distributionTransformerVoltage);

            faultTransferSchemeEvaluationIndex.setToBeTransferLoad(toBeTransferLoad);
            faultTransferSchemeEvaluationIndex.setCarriedLoad(carriedLoad);
            faultTransferSchemeEvaluationIndex.setAutoSwitchOperationTimes(autoSwitchOperationTimes);
            faultTransferSchemeEvaluationIndex.setTotalToBeTransferUsers(totalToBeTransferUsers);
            faultTransferSchemeEvaluationIndex.setLossImportantUsers(lossImportantUsers);
            faultTransferSchemeEvaluationIndex.setLossSensitiveUsers(lossSensitiveUsers);
            faultTransferSchemeEvaluationIndex.setLossPowerSecuredUsers(lossPowerSecuredUsers);
        });
        //3批量保存数据
        List<FaultTransferSchemeEvaluationIndex> fhzgPlanTransferSchemeEvaluationIndexList = resultMap.values().stream().collect(Collectors.toList());
        //先删除数据,评分指标和，评分数据
        baseMapper.deleteScoreData(faultId);
        this.saveBatch(fhzgPlanTransferSchemeEvaluationIndexList);
        return fhzgPlanTransferSchemeEvaluationIndexList;
    }

    @Override
    public void deleteScoreData(Long faultId) {
        baseMapper.deleteScoreData(faultId);
    }


}
