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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.HasDataTagDTO;
import com.hdkj.lt.bf.entity.vo.FhzgFaultPowerCutVO;
import com.hdkj.lt.bf.mapper.FaultAwaitTransferUsersMapper;
import com.hdkj.lt.bf.mapper.FaultDistMappingFileMapper;
import com.hdkj.lt.bf.mapper.FaultPowerCutMapper;
import com.hdkj.lt.bf.mapper.FhzgFaultSwitchInfoListMapper;
import com.hdkj.lt.bf.service.*;
import com.hdkj.lt.bf.service.aspect.UserCountyCodeAuto;
import com.hdkj.lt.core.bizms.modle.dto.FhzgFaultAwaitTransferUsersCountDTO;
import com.hdkj.lt.core.bizms.modle.dto.FhzgFaultDistCustomerDTO;
import com.hdkj.lt.core.bizms.modle.dto.FhzgFaultDistMappingFileDTO;
import com.hdkj.lt.core.bizms.modle.po.fault.*;
import com.hdkj.lt.modle.dto.jsty.AllSwitchInfoListDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 故障停电转供信息表 服务实现类
 * </p>
 *
 * @author luorui
 * @since 2025-05-29
 */
@Service
@Slf4j
public class FaultPowerCutServiceImpl extends ServiceImpl<FaultPowerCutMapper, FaultPowerCut> implements IFaultPowerCutService {

    @Autowired
    FaultDistMappingFileMapper faultDistMappingFileMapper;

    @Autowired
    FaultAwaitTransferUsersMapper faultAwaitTransferUsersMapper;

    @Autowired
    IFaultPowerCutPvUsersService faultPowerCutPvUsersService;

    @Autowired
    IFaultAwaitTransferSwitchSectionService awaitTransferSwitchSectionServices;

    @Autowired
    IFaultOppositeLineCarryCapacityService oppositeLineCarryCapacityService;

    @Autowired
    IFaultTransferSchemeService faultTransferSchemeService;
    @Autowired
    FhzgFaultSwitchInfoListMapper switchInfoListMapper;

    @Override
    @UserCountyCodeAuto(sourceFiled = "countyCode",targetFiled = "countyCodeList")
    public Page<FhzgFaultPowerCutVO> getSchemeList(FaultPowerCut obj) {
        Page<FhzgFaultPowerCutVO> page = new Page<>();
        page.setCurrent(obj.getPageNum());
        page.setSize(obj.getPageSize());
        List<FhzgFaultPowerCutVO> list = baseMapper.selectSchemeList(page, obj);

        if (CollUtil.isNotEmpty(list)) {
            //查询计划对应的线路图信息
            List<Long> idList = list.stream().map(FhzgFaultPowerCutVO::getId).collect(Collectors.toList());
            List<FhzgFaultDistMappingFileDTO> fileList = faultDistMappingFileMapper.getMappingFileByPlanId(idList);
            if (CollUtil.isNotEmpty(fileList)) {
                Map<Long, List<FhzgFaultDistMappingFileDTO>> fileListMap = fileList.stream().collect(Collectors.groupingBy(FhzgFaultDistMappingFileDTO::getFaultId));
                list.forEach(e -> {
                    e.setFileList(fileListMap.get(e.getId()));
                });
            } else {
                log.info("未查询到故障停电文件列表faultIdList:{}", idList);
            }
            //查询统计，用户数量，重要用户数量，敏感用户数量，用户负荷
            List<FhzgFaultAwaitTransferUsersCountDTO> usersCountDTOList = faultAwaitTransferUsersMapper.selectAwaitUserCountByFaultId(idList);
            if (CollUtil.isNotEmpty(usersCountDTOList)) {
                Map<Long, FhzgFaultAwaitTransferUsersCountDTO> fusersCountMap = usersCountDTOList.stream().collect(Collectors.toMap(FhzgFaultAwaitTransferUsersCountDTO::getFaultId, Function.identity(), (k1, k2) -> k2));
                list.forEach(e -> {
                    FhzgFaultAwaitTransferUsersCountDTO userCountDTO = fusersCountMap.get(e.getId());
                    if (!Objects.isNull(userCountDTO)) {
                        e.setTransferCriticalUsers(userCountDTO.getTransferCriticalUsers());//重要用户数量
                        e.setTransferSensitiveUsers(userCountDTO.getTransferSensitiveUsers());//敏感用户
                        e.setUserCount(userCountDTO.getUserCount());//用户数量
                        e.setUserLoads(userCountDTO.getUserLoads());//用户负荷
                        e.setProtectUsers(userCountDTO.getProtectUsers());//保电用户数量
                    }
                });
            } else {
                log.info("未查询到待转供用户数量faultIdList:{}", idList);
            }
            //查询停电计划对应的光伏用户数量
            List<FaultPowerCutPvUsers> countCutPvUsers = faultPowerCutPvUsersService.countByFaultId(idList);
            if (CollUtil.isNotEmpty(countCutPvUsers)) {
                Map<Long, FaultPowerCutPvUsers> cutPvUsersMap = countCutPvUsers.stream().collect(Collectors.toMap(FaultPowerCutPvUsers::getFaultId, Function.identity(), (k1, k2) -> k2));
                list.forEach(e -> {
                    FaultPowerCutPvUsers faultPowerCutPvUsers = cutPvUsersMap.get(e.getId());
                    Integer count = Objects.isNull(faultPowerCutPvUsers) ? 0 : Objects.isNull(faultPowerCutPvUsers.getCount()) ? 0 : faultPowerCutPvUsers.getCount();
                    e.setPvUsers(count);
                });
            } else {
                log.info("未查询到光伏用户数量faultIdList:{}", idList);
            }

        } else {
            log.info("查询故障停电数据为空condition:{}", obj);
        }
        list.stream().filter(i -> i.getUserLoads() != null).forEach(i->i.setUserLoads(i.getUserLoads().multiply(new BigDecimal("1000"))));
        return page.setRecords(list);
    }

    @Override
    public HasDataTagDTO getHasDataTag(FhzgFaultDistCustomerDTO dto) {
        Long faultId = dto.getFaultId();
        if (Objects.isNull(faultId)) {
            throw new BusinessException("查询参数planId为空");
        }
        HasDataTagDTO hasDataTagDTO = new HasDataTagDTO();
        Boolean transferAreaTag = false;
        Boolean transferSchemeTag = false;
        Boolean transferScoreTag = false;
        //查询转供范围下是否有数据，待转供用户，待转供开关段，对侧承载力分析 都没有数据则为false
        LambdaQueryWrapper<FaultAwaitTransferUsers> awaitTransferUsersWrapper = new LambdaQueryWrapper<>();
        awaitTransferUsersWrapper.eq(FaultAwaitTransferUsers::getFaultId, faultId);
        Long countAwaitTransferUsers = faultAwaitTransferUsersMapper.selectCount(awaitTransferUsersWrapper);
        if (countAwaitTransferUsers != null && countAwaitTransferUsers.compareTo(0L) > 0) {
            transferAreaTag = true;
        }
        if (!transferAreaTag) {
            LambdaQueryWrapper<FaultAwaitTransferSwitchSection> awaitTransferSwitchWrapper = new LambdaQueryWrapper<>();
            awaitTransferSwitchWrapper.eq(FaultAwaitTransferSwitchSection::getFaultId, faultId);
            Long countAwaitTransferSwitch = awaitTransferSwitchSectionServices.count(awaitTransferSwitchWrapper);
            if (countAwaitTransferSwitch != null && countAwaitTransferSwitch.compareTo(0L) > 0) {
                transferAreaTag = true;
            }
        }
        if (!transferAreaTag) {
            LambdaQueryWrapper<FaultOppositeLineCarryCapacity> oppositeLineCarryWrapper = new LambdaQueryWrapper<>();
            oppositeLineCarryWrapper.eq(FaultOppositeLineCarryCapacity::getFaultId, faultId);
            Long countOppositeLineCarry = oppositeLineCarryCapacityService.count(oppositeLineCarryWrapper);
            if (countOppositeLineCarry != null && countOppositeLineCarry.compareTo(0L) > 0) {
                transferAreaTag = true;
            }
        }
        //查询转供方案是否有数据  转供方案是否有数据   //查询转供方案评分是否有数据 评分指标结果 和 评分细则都没数据则不显示
        LambdaQueryWrapper<FaultTransferScheme> schemeWrapper = new LambdaQueryWrapper<>();
        schemeWrapper.eq(FaultTransferScheme::getFaultId, faultId);
        Long countScheme = faultTransferSchemeService.count(schemeWrapper);
        if (countScheme != null && countScheme.compareTo(0L) > 0) {
            transferSchemeTag = true;
            transferScoreTag = true;
        }
        hasDataTagDTO.setTransferAreaTag(transferAreaTag);
        hasDataTagDTO.setTransferSchemeTag(transferSchemeTag);
        hasDataTagDTO.setTransferScoreTag(transferScoreTag);
        log.info("返回前端标识,transferAreaTag:{},transferSchemeTag:{},:transferScoreTag:{}", transferAreaTag, transferSchemeTag, transferScoreTag);
        return hasDataTagDTO;
    }

    @Override
    public Integer updateSchemeState(FaultPowerCut obj) {
        if (Objects.isNull(obj.getId())) {
            throw new BusinessException("更新方案主键为空");
        }
        if (StrUtil.isBlank(obj.getSchemeState())) {
            throw new BusinessException("更新方案字段为空");
        }
        return baseMapper.updateSchemeState(obj);
    }

    @Override
    public FhzgFaultPowerCutVO getSchemeByFaultId(Long faultId) {
        FhzgFaultPowerCutVO faultPowerCutVO = baseMapper.getSchemeByFaultId(faultId);
        return faultPowerCutVO;
    }

    @Override
    public List<AllSwitchInfoListDTO> getAllSwitchBySchemeId(Long faultId) {
        LambdaQueryWrapper<FhzgFaultSwitchInfoList> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FhzgFaultSwitchInfoList::getFaultId, faultId);
        FhzgFaultSwitchInfoList switchInfoList = switchInfoListMapper.selectOne(lambdaQueryWrapper);
        //  FaultPowerCut faultPowerCut = baseMapper.selectById(faultId);
        String allSwitchInfoListJson = switchInfoList.getAllSwitchInfoListJson();
        return JSON.parseArray(allSwitchInfoListJson, AllSwitchInfoListDTO.class);
    }
}
