package com.njcn.harmonic.service.upload.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.pms.api.LineIntegrityDataClient;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.pojo.param.DataQualityDetailsParam;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.device.pq.pojo.po.RStatIntegrityD;
import com.njcn.harmonic.common.mapper.RStatDataVDMapper;
import com.njcn.harmonic.mapper.upload.*;
import com.njcn.harmonic.pojo.dto.upload.PqEvaluationCreateDTO;
import com.njcn.harmonic.pojo.dto.upload.RDimUpDTO;
import com.njcn.harmonic.pojo.param.UploadDataParam;
import com.njcn.harmonic.pojo.param.UploadParam;
import com.njcn.harmonic.pojo.param.upload.DimBusBarParam;
import com.njcn.harmonic.pojo.po.RStatDataVD;
import com.njcn.harmonic.pojo.po.day.RStatLimitRateDPO;
import com.njcn.harmonic.pojo.po.upload.*;
import com.njcn.harmonic.pojo.vo.upload.DimBusBarVO;
import com.njcn.harmonic.pojo.vo.upload.UploadEvaluationDataVo;
import com.njcn.harmonic.mapper.RStatLimitRateDMapper;
import com.njcn.harmonic.service.upload.IEvaluationDataService;
import com.njcn.harmonic.service.upload.IRUploadDataLogService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.web.enums.GWSendEnum;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.pojo.dto.PmsPage;
import com.njcn.web.pojo.param.SendParam;
import com.njcn.web.utils.GwSendUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 电能质量基准水平评估数据-日表 服务实现类
 * </p>
 *
 * @author xuyang
 * @since 2023-12-12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class REvaluationDataServiceImpl extends ServiceImpl<RUploadEvaluationDataDMapper, RUploadEvaluationDataD> implements IEvaluationDataService {

    private final DeptFeignClient deptFeignClient;
    private final DicDataFeignClient dicDataFeignClient;

    private final PmsRunStatisticDMapper pmsRunStatisticDMapper;

    private final PmsRunStatisticMMapper pmsRunStatisticMMapper;

    private final PmsRunStatisticYMapper pmsRunStatisticYMapper;

    private final RDimBusUpDMapper rDimBusUpDMapper;

    private final RDimBusUpMMapper rDimBusUpMMapper;

    private final RDimBusUpYMapper rDimBusUpYMapper;

    private final MonitorClient monitorClient;

    private final IRUploadDataLogService irUploadDataLogService;

    private final LineIntegrityDataClient lineIntegrityDataClient;

    private final RStatLimitRateDMapper rStatLimitRateDMapper;

    private final RStatDataVDMapper rStatDataVDMapper;


    @Override
    public Page<UploadEvaluationDataVo> getEvaluationData(UploadDataParam param) {
        LambdaQueryWrapper<RUploadEvaluationDataD> lambdaQueryWrapper = this.getDeptLevel(param);
        //默认按照省名称排序
        //lambdaQueryWrapper.orderByDesc(RUploadEvaluationDataD::getProvinceName);
        Page<RUploadEvaluationDataD> page = this.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), lambdaQueryWrapper);
        List<UploadEvaluationDataVo> voList = BeanUtil.copyToList(page.getRecords(), UploadEvaluationDataVo.class);
        if (CollectionUtil.isNotEmpty(voList)) {
            voList = voList.stream().peek(item -> {
                if (!Objects.equals(item.getAvgValue(), 3.1415926)) {
                    BigDecimal four = BigDecimal.valueOf(item.getAvgValue());
                    double value = four.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    item.setAvgValue(value);
                } else if (!Objects.equals(item.getStandardDeviation(), 3.1415926)) {
                    BigDecimal four = BigDecimal.valueOf(item.getStandardDeviation());
                    double value = four.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    item.setStandardDeviation(value);
                }
                BigDecimal four = BigDecimal.valueOf(item.getMonitorBusRate());
                double value = four.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                item.setMonitorBusRate(value);
            }).collect(Collectors.toList());
        }
        Page<UploadEvaluationDataVo> pageVo = new Page<>();
        pageVo.setTotal(page.getTotal());
        pageVo.setPages(page.getPages());
        pageVo.setSize(page.getSize());
        pageVo.setRecords(voList);
        pageVo.setCurrent(page.getCurrent());
        return pageVo;
    }

    @Override
    public String uploadEvaluationData(UploadParam param) {
        LocalDate localDate = LocalDate.parse(param.getTime(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        List<RUploadEvaluationDataD> list;
        //指定数据上送,不管之前有没有上送,都重新上送一次
        //(预防之前上送过,修改数据后需要再次上送)
        if (CollUtil.isNotEmpty(param.getList())) {
            list = this.lambdaQuery()
                    .eq(RUploadEvaluationDataD::getComputeDate, param.getTime())
                    .in(RUploadEvaluationDataD::getId, param.getList())
                    .list();
        }
        //未指定数据上送,则上送省市县级数据(包含日、月数据)
        else {
            list = this.lambdaQuery()
                    .eq(RUploadEvaluationDataD::getComputeDate, param.getTime())
                    .in(RUploadEvaluationDataD::getStatisticalLevel, Stream.of("3", "4", "5").collect(Collectors.toList()))
                    .list();
        }

        //以尺寸100分片
        List<List<RUploadEvaluationDataD>> partition = ListUtils.partition(list, 100);
        //分片上传
        StrBuilder resultLog = new StrBuilder();
        AtomicBoolean resultFlag = new AtomicBoolean(true);
        for (int i = 0; i < partition.size(); i++) {
            //处理数据
            List<RUploadEvaluationDataD> collect = partition.get(i).stream().peek(item -> {
                if (Objects.equals(item.getAvgValue(), 3.1415926)) {
                    item.setAvgValue(0d);
                } else {
                    BigDecimal four = BigDecimal.valueOf(item.getAvgValue());
                    double value = four.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                    item.setAvgValue(value);
                }
                if (Objects.equals(item.getStandardDeviation(), 3.1415926)) {
                    item.setStandardDeviation(0d);
                }
                if (Objects.equals(item.getHarmonicNum(), 0)) {
                    item.setHarmonicNum(null);
                }
                if (Objects.equals(item.getVoltageLevel(), "0")) {
                    item.setVoltageLevel(null);
                } else {
                    item.setVoltageLevel(getVoltage(item.getVoltageLevel()));
                }
                if (Objects.equals(item.getCityId(), "")) {
                    item.setCityId(null);
                }
                if (Objects.equals(item.getCountyId(), "")) {
                    item.setCountyId(null);
                }
                BigDecimal four = BigDecimal.valueOf(item.getMonitorBusRate());
                double value = four.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                item.setMonitorBusRate(value);
            }).collect(Collectors.toList());
            List<PqEvaluationCreateDTO> dtoList = BeanUtil.copyToList(collect, PqEvaluationCreateDTO.class);
            //组装数据
            SendParam sp = new SendParam();
            sp.setStats(dtoList);
            sp.setStatisticalDate(collect.get(0).getComputeDate());
            if(i == 0){
                sp.setIsAppend("0");
            }else if(i==partition.size()-1){
                sp.setIsAppend("2");
            }else {
                sp.setIsAppend("1");
            }
            //上送数据
            Map<String, String> send = GwSendUtil.send(sp, GWSendEnum.EVALUATION);
            //获取返回结果
            List<String> l = dtoList.stream().map(PqEvaluationCreateDTO::getId).collect(Collectors.toList());

            returnInformation(i, l, send, resultLog, resultFlag, localDate);
        }

        if (resultFlag.get()) {
            resultLog.append(" 上送" + list.size() + "条数据成功");
            assUploadLog(localDate, resultLog, resultFlag);
        }


        return "上送成功:成功数据" + list.size() + "条";
    }

    private void assUploadLog(LocalDate statisticDate, StrBuilder msg, AtomicBoolean resultFlag) {
        RUploadDataLog rUploadDataLog = new RUploadDataLog();
        rUploadDataLog.setStatisticDate(statisticDate);
        rUploadDataLog.setBigType(0);
        rUploadDataLog.setSmallType(0);
        rUploadDataLog.setCreateTime(LocalDateTime.now());
        rUploadDataLog.setResult(resultFlag.get() ? 1 : 0);
        rUploadDataLog.setResultMsg(msg.toString());
        irUploadDataLogService.saveOrUpdateByMultiId(rUploadDataLog);
    }

    @Override
    public PmsPage<DimBusBarVO> getBaseEvaOnlineBusDetail(DimBusBarParam param) {
        PmsPage<DimBusBarVO> pmsPage = new PmsPage<>(param.getPageNum(), param.getPageSize());
        List<String> temBusIds = new ArrayList<>();

        LocalDate begin = LocalDate.parse(param.getStartTime());
        if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_D.getCode())) {
            //具体日期投运,监测台账查询
            LambdaQueryWrapper<PmsRunStatisticD> dayLam = new LambdaQueryWrapper<>();
            dayLam.select(PmsRunStatisticD::getRunBusIds)
                    .eq(PmsRunStatisticD::getStatisticDate, begin).eq(PmsRunStatisticD::getDeptId, param.getOrgId());
            PmsRunStatisticD pmsRunStatisticD = pmsRunStatisticDMapper.selectOne(dayLam);
            if (Objects.nonNull(pmsRunStatisticD)) {
                temBusIds = new ArrayList<>(Arrays.asList(pmsRunStatisticD.getRunBusIds().split(StrUtil.COMMA)));
            }

        } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_M.getCode())) {
            //具体日期投运,监测台账查询
            LambdaQueryWrapper<PmsRunStatisticM> dayLam = new LambdaQueryWrapper<>();
            dayLam.select(PmsRunStatisticM::getRunBusIds)
                    .eq(PmsRunStatisticM::getStatisticDate, begin).eq(PmsRunStatisticM::getDeptId, param.getOrgId());
            PmsRunStatisticM pmsRunStatisticM = pmsRunStatisticMMapper.selectOne(dayLam);
            if (Objects.nonNull(pmsRunStatisticM)) {
                temBusIds = new ArrayList<>(Arrays.asList(pmsRunStatisticM.getRunBusIds().split(StrUtil.COMMA)));
            }
        } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_Y.getCode())) {

            //具体日期投运,监测台账查询
            LambdaQueryWrapper<PmsRunStatisticY> dayLam = new LambdaQueryWrapper<>();
            dayLam.select(PmsRunStatisticY::getRunBusIds)
                    .eq(PmsRunStatisticY::getStatisticDate, begin).eq(PmsRunStatisticY::getDeptId, param.getNodeId());
            PmsRunStatisticY pmsRunStatisticY = pmsRunStatisticYMapper.selectOne(dayLam);
            if (Objects.nonNull(pmsRunStatisticY)) {
                temBusIds = new ArrayList<>(Arrays.asList(pmsRunStatisticY.getOnlineBusMidIds().split(StrUtil.COMMA)));
            }
        }
        if (CollectionUtil.isEmpty(temBusIds)) {
            return new PmsPage<>();
        }
        param.setOnlineBusIds(temBusIds);
        Page<DimBusBarVO> page = this.baseMapper.getBaseEvaOnlineBusDetail(new Page<>(param.getPageNum(), param.getPageSize()), param);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<DictData> voltageDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
            Map<String, DictData> voltageMap = voltageDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

            List<DictData> monitorDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
            Map<String, DictData> monitorDicMap = monitorDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

            for (DimBusBarVO dimBusBarVO : page.getRecords()) {
                dimBusBarVO.setBusVoltageLevelName(voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getName());
                dimBusBarVO.setStationVoltageLevelName(voltageMap.get(dimBusBarVO.getStationVoltageLevel()).getName());
                dimBusBarVO.setBusVoltageLevel(String.format("%02d", voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getAlgoDescribe()));
                dimBusBarVO.setStationVoltageLevel(String.format("%02d", voltageMap.get(dimBusBarVO.getStationVoltageLevel()).getAlgoDescribe()));
                dimBusBarVO.setPsrStateName(monitorDicMap.get(dimBusBarVO.getPsrStateName()).getName());
            }
        }
        BeanUtil.copyProperties(page, pmsPage);
        pmsPage.setList(page.getRecords());
        return pmsPage;
    }

    @Override
    public PmsPage<DimBusBarVO> getBaseEvaMonitorBusDetail(DimBusBarParam param) {
        PmsPage<DimBusBarVO> pmsPage = new PmsPage<>(param.getPageNum(), param.getPageSize());
        List<String> temBusIds = new ArrayList<>();

        Map<String, String> effectMap = new HashMap<>();

        LocalDate begin = LocalDate.parse(param.getStartTime());
        if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_D.getCode())) {
            //具体日期投运,监测台账查询
            LambdaQueryWrapper<PmsRunStatisticD> dayLam = new LambdaQueryWrapper<>();
            dayLam.select(PmsRunStatisticD::getOnlineBusMidIds)
                    .eq(PmsRunStatisticD::getStatisticDate, begin)
                    .eq(PmsRunStatisticD::getDeptId, param.getOrgId());
            PmsRunStatisticD pmsRunStatisticD = pmsRunStatisticDMapper.selectOne(dayLam);
            if (Objects.nonNull(pmsRunStatisticD)) {
                if (StrUtil.isNotBlank(pmsRunStatisticD.getOnlineBusMidIds())) {
                    temBusIds = new ArrayList<>(Arrays.asList(pmsRunStatisticD.getOnlineBusMidIds().split(StrUtil.COMMA)));

                    List<RDimBusUpD> rDimBusUpDList = rDimBusUpDMapper.selectList(new LambdaQueryWrapper<RDimBusUpD>().in(RDimBusUpD::getMidBusId, temBusIds)
                            .eq(RDimBusUpD::getStatisticDate, param.getStartTime()).eq(RDimBusUpD::getPhasicType, "A"));
                    effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpD::getBusId, RDimBusUpD::getEffectIds));
                }
            }


        } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_M.getCode())) {
            //具体日期投运,监测台账查询
            LambdaQueryWrapper<PmsRunStatisticM> dayLam = new LambdaQueryWrapper<>();
            dayLam.select(PmsRunStatisticM::getOnlineBusMidIds)
                    .eq(PmsRunStatisticM::getStatisticDate, begin).eq(PmsRunStatisticM::getDeptId, param.getOrgId());
            PmsRunStatisticM pmsRunStatisticM = pmsRunStatisticMMapper.selectOne(dayLam);
            if (Objects.nonNull(pmsRunStatisticM)) {
                if (StrUtil.isNotBlank(pmsRunStatisticM.getOnlineBusMidIds())) {
                    temBusIds = new ArrayList<>(Arrays.asList(pmsRunStatisticM.getOnlineBusMidIds().split(StrUtil.COMMA)));

                    List<RDimBusUpM> rDimBusUpDList = rDimBusUpMMapper.selectList(new LambdaQueryWrapper<RDimBusUpM>().in(RDimBusUpM::getMidBusId, temBusIds)
                            .eq(RDimBusUpM::getStatisticDate, param.getStartTime()).eq(RDimBusUpM::getPhasicType, "A"));
                    effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpM::getBusId, RDimBusUpM::getEffectIds));
                }
            }
        } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_Y.getCode())) {

            //具体日期投运,监测台账查询
            LambdaQueryWrapper<PmsRunStatisticY> dayLam = new LambdaQueryWrapper<>();
            dayLam.select(PmsRunStatisticY::getOnlineBusMidIds)
                    .eq(PmsRunStatisticY::getStatisticDate, begin).eq(PmsRunStatisticY::getDeptId, param.getNodeId());
            PmsRunStatisticY pmsRunStatisticY = pmsRunStatisticYMapper.selectOne(dayLam);
            if (Objects.nonNull(pmsRunStatisticY)) {
                if (StrUtil.isNotBlank(pmsRunStatisticY.getOnlineBusMidIds())) {
                    temBusIds = new ArrayList<>(Arrays.asList(pmsRunStatisticY.getOnlineBusMidIds().split(StrUtil.COMMA)));

                    List<RDimBusUpY> rDimBusUpDList = rDimBusUpYMapper.selectList(new LambdaQueryWrapper<RDimBusUpY>().in(RDimBusUpY::getMidBusId, temBusIds)
                            .eq(RDimBusUpY::getStatisticDate, param.getStartTime()).eq(RDimBusUpY::getPhasicType, "A"));
                    effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpY::getBusId, RDimBusUpY::getEffectIds));
                }
            }
        }
        if (CollectionUtil.isEmpty(temBusIds)) {
            return new PmsPage<>();
        }
        param.setOnlineBusIds(temBusIds);
        Page<DimBusBarVO> page = this.baseMapper.getBaseEvaOnlineBusDetail(new Page<>(param.getPageNum(), param.getPageSize()), param);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<DictData> voltageDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
            Map<String, DictData> voltageMap = voltageDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

            List<DictData> monitorDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
            Map<String, DictData> monitorDicMap = monitorDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

            for (DimBusBarVO dimBusBarVO : page.getRecords()) {
                dimBusBarVO.setBusVoltageLevelName(voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getName());
                dimBusBarVO.setStationVoltageLevelName(voltageMap.get(dimBusBarVO.getStationVoltageLevel()).getName());
                dimBusBarVO.setBusVoltageLevel(String.format("%02d", voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getAlgoDescribe()));
                dimBusBarVO.setStationVoltageLevel(String.format("%02d", voltageMap.get(dimBusBarVO.getStationVoltageLevel()).getAlgoDescribe()));
                dimBusBarVO.setPsrStateName(monitorDicMap.get(dimBusBarVO.getPsrStateName()).getName());

                String tem = effectMap.get(dimBusBarVO.getLineId());
                int count = 0;
                if (tem.length() > 0) {
                    for (int i = 0; i < tem.length(); i++) {
                        if (tem.charAt(i) == ',') {
                            count++;
                        }
                    }
                }
                dimBusBarVO.setBusEfectiveMnitorNum(count);

            }
        }

        BeanUtil.copyProperties(page, pmsPage);
        pmsPage.setList(page.getRecords());
        return pmsPage;
    }


    @Override
    public PmsPage<DimBusBarVO> getBusListByVoltageLevel(DimBusBarParam param) {
        PmsPage<DimBusBarVO> result = new PmsPage<>(param.getPageNum(), param.getPageSize());

        List<String> temBusIds = new ArrayList<>();

        List<RDimUpDTO> rDimUpDTOList = new ArrayList<>();

        LocalDate begin = LocalDate.parse(param.getStartTime());

        String statisticType = param.getStatType();
        if (DicDataEnum.STATISTICAL_TYPE_D.getCode().equals(statisticType)) {
            temBusIds = getOnlineBusIds(param.getNodeId(), begin, PmsRunStatisticD.class);
        } else if (DicDataEnum.STATISTICAL_TYPE_M.getCode().equals(statisticType)) {
            temBusIds = getOnlineBusIds(param.getNodeId(), begin, PmsRunStatisticM.class);
        } else if (DicDataEnum.STATISTICAL_TYPE_Y.getCode().equals(statisticType)) {
            temBusIds = getOnlineBusIds(param.getNodeId(), begin, PmsRunStatisticY.class);
        }
        temBusIds = this.busTargetAss(param, temBusIds, rDimUpDTOList);
        if (CollectionUtil.isEmpty(temBusIds)) {
            return result;
        }
        param.setOnlineBusIds(temBusIds);
        Page<DimBusBarVO> page = this.baseMapper.getBaseEvaOnlineBusDetail(new Page<>(param.getPageNum(), param.getPageSize()), param);
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            Map<String, RDimUpDTO> map = rDimUpDTOList.stream().collect(Collectors.toMap(RDimUpDTO::getBusMidId, Function.identity()));

            List<DictData> voltageDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
            Map<String, DictData> voltageMap = voltageDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

            List<DictData> monitorDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_STATE.getCode()).getData();
            Map<String, DictData> monitorDicMap = monitorDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));


            page.getRecords().forEach(it -> {
                if (map.containsKey(it.getAstId())) {
                    RDimUpDTO rDimUpDTO = map.get(it.getAstId());
                    it.setBusEfectiveMnitorNum(rDimUpDTO.getEffectIds().split(StrUtil.COMMA).length);
                    it.setMonitorId(rDimUpDTO.getEffectId());
                    it.setIndexAvgValue(rDimUpDTO.getV().toString());
                }

                it.setBusVoltageLevelName(voltageMap.get(it.getBusVoltageLevel()).getName());
                it.setStationVoltageLevelName(voltageMap.get(it.getStationVoltageLevel()).getName());
                it.setBusVoltageLevel(String.format("%02d", voltageMap.get(it.getBusVoltageLevel()).getAlgoDescribe()));
                it.setStationVoltageLevel(String.format("%02d", voltageMap.get(it.getStationVoltageLevel()).getAlgoDescribe()));
                it.setPsrStateName(monitorDicMap.get(it.getPsrStateName()).getName());
            });
        }
        BeanUtil.copyProperties(page, result);
        result.setList(page.getRecords());
        return result;
    }

    @Override
    public PmsPage<DimBusBarVO.DimBusBarEffectMonitorVO> getMonitorListByBus(DimBusBarParam param) {
        PmsPage<DimBusBarVO.DimBusBarEffectMonitorVO> result = new PmsPage<>(param.getPageNum(), param.getPageSize());
        if (StrUtil.isBlank(param.getBusId())) {
            return result;
        }
        List<DimBusBarVO.DimBusBarEffectMonitorVO> voList = new ArrayList<>();

        Page<DimBusBarVO> page = this.baseMapper.getBaseEvaOnlineBusDetail(new Page<>(param.getPageNum(), param.getPageSize()), param);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            Map<String, String> effectMap = new HashMap<>();
            if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_D.getCode())) {
                //具体日期投运,监测台账查询
                List<RDimBusUpD> rDimBusUpDList = rDimBusUpDMapper.selectList(new LambdaQueryWrapper<RDimBusUpD>().eq(RDimBusUpD::getMidBusId, param.getBusId())
                        .eq(RDimBusUpD::getStatisticDate, param.getStartTime()).eq(RDimBusUpD::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpD::getBusId, RDimBusUpD::getEffectIds));
            } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_M.getCode())) {
                List<RDimBusUpM> rDimBusUpDList = rDimBusUpMMapper.selectList(new LambdaQueryWrapper<RDimBusUpM>().eq(RDimBusUpM::getMidBusId, param.getBusId())
                        .eq(RDimBusUpM::getStatisticDate, param.getStartTime()).eq(RDimBusUpM::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpM::getBusId, RDimBusUpM::getEffectIds));
            } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_Y.getCode())) {
                List<RDimBusUpY> rDimBusUpDList = rDimBusUpYMapper.selectList(new LambdaQueryWrapper<RDimBusUpY>().eq(RDimBusUpY::getMidBusId, param.getBusId())
                        .eq(RDimBusUpY::getStatisticDate, param.getStartTime()).eq(RDimBusUpY::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpY::getBusId, RDimBusUpY::getEffectIds));
            }

            DimBusBarVO dimBusBarVO = page.getRecords().get(0);
            if (effectMap.containsKey(dimBusBarVO.getLineId())) {
                String effectIds = effectMap.get(dimBusBarVO.getLineId());
                if (StrUtil.isNotBlank(effectIds)) {
                    List<String> monitorIds = new ArrayList<>(Arrays.asList(effectIds.split(StrUtil.COMMA)));

                    List<Monitor> monitorList = monitorClient.getMonitorList(monitorIds).getData();
                    if (CollUtil.isNotEmpty(monitorList)) {
                        List<String> ids = monitorList.stream().map(Monitor::getId).collect(Collectors.toList());

                        QueryWrapper<RStatLimitRateDPO> queryWrapper = new QueryWrapper<>();
                        harmMonitorTarget(param, queryWrapper);
                        queryWrapper.in("my_index", ids);
                        List<RStatLimitRateDPO> rStatLimitRateDPOList = rStatLimitRateDMapper.selectList(queryWrapper);
                        if (CollUtil.isNotEmpty(rStatLimitRateDPOList)) {
                            Map<String, List<RStatLimitRateDPO>> map = rStatLimitRateDPOList.stream().collect(Collectors.groupingBy(RStatLimitRateDPO::getLineId));

                            List<DictData> voltageDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
                            Map<String, DictData> voltageMap = voltageDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));
                            for (Monitor monitor : monitorList) {
                                if (map.containsKey(monitor.getId())) {
                                    DimBusBarVO.DimBusBarEffectMonitorVO vo = new DimBusBarVO.DimBusBarEffectMonitorVO();
                                    vo.setBusId(dimBusBarVO.getMidId());
                                    vo.setBusName(dimBusBarVO.getBusName());
                                    vo.setBusVoltageLevelName(voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getName());
                                    vo.setBusVoltageLevel(String.format("%02d", voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getAlgoDescribe()));
                                    vo.setCityOrg(dimBusBarVO.getCityOrg());
                                    vo.setCityOrgName(dimBusBarVO.getCityOrgName());
                                    vo.setMaintOrg(dimBusBarVO.getMaintOrg());
                                    vo.setMaintOrgName(dimBusBarVO.getMaintOrgName());
                                    vo.setMonitorId(monitor.getMonitorId());
                                    vo.setMonitorName(monitor.getName());
                                    vo.setStationId(dimBusBarVO.getStationId());
                                    vo.setStationName(dimBusBarVO.getStationName());
                                    vo.setStatus("01");
                                    vo.setStatusName("运行");
                                    voList.add(vo);
                                }
                            }
                        }
                    }
                }

            }


        }
        result.setTotal(voList.size());
        result.setList(voList);
        return result;
    }

    @Override
    public PmsPage<DimBusBarVO.DimBusBarMonitorVO> getBaseEvaBusMonitorList(DimBusBarParam param) {
        PmsPage<DimBusBarVO.DimBusBarMonitorVO> result = new PmsPage<>(param.getPageNum(), param.getPageSize());
        if (StrUtil.isBlank(param.getBusId())) {
            return result;
        }
        Page<DimBusBarVO> page = this.baseMapper.getBaseEvaOnlineBusDetail(new Page<>(param.getPageNum(), param.getPageSize()), param);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            List<DimBusBarVO.DimBusBarMonitorVO> voList = new ArrayList<>();
            DimBusBarVO dimBusBarVO = page.getRecords().get(0);
            Map<String, String> effectMap = new HashMap<>();
            if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_D.getCode())) {
                //具体日期投运,监测台账查询
                List<RDimBusUpD> rDimBusUpDList = rDimBusUpDMapper.selectList(new LambdaQueryWrapper<RDimBusUpD>().eq(RDimBusUpD::getMidBusId, param.getBusId())
                        .eq(RDimBusUpD::getStatisticDate, param.getStartTime()).eq(RDimBusUpD::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpD::getBusId, RDimBusUpD::getEffectIds));
            } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_M.getCode())) {
                List<RDimBusUpM> rDimBusUpDList = rDimBusUpMMapper.selectList(new LambdaQueryWrapper<RDimBusUpM>().eq(RDimBusUpM::getMidBusId, param.getBusId())
                        .eq(RDimBusUpM::getStatisticDate, param.getStartTime()).eq(RDimBusUpM::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpM::getBusId, RDimBusUpM::getEffectIds));
            } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_Y.getCode())) {
                List<RDimBusUpY> rDimBusUpDList = rDimBusUpYMapper.selectList(new LambdaQueryWrapper<RDimBusUpY>().eq(RDimBusUpY::getMidBusId, param.getBusId())
                        .eq(RDimBusUpY::getStatisticDate, param.getStartTime()).eq(RDimBusUpY::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpY::getBusId, RDimBusUpY::getEffectIds));
            }

            if (effectMap.containsKey(dimBusBarVO.getLineId())) {
                String effectIds = effectMap.get(dimBusBarVO.getLineId());
                if (StrUtil.isNotBlank(effectIds)) {
                    List<String> monitorIds = new ArrayList<>(Arrays.asList(effectIds.split(StrUtil.COMMA)));

                    List<Monitor> monitorList = monitorClient.getMonitorList(monitorIds).getData();
                    if (CollUtil.isNotEmpty(monitorList)) {
                        List<String> ids = monitorList.stream().map(Monitor::getId).collect(Collectors.toList());

                        QueryWrapper<RStatLimitRateDPO> queryWrapper = new QueryWrapper<>();
                        harmMonitorTarget(param, queryWrapper);
                        queryWrapper.in("my_index", ids);
                        List<RStatLimitRateDPO> rStatLimitRateDPOList = rStatLimitRateDMapper.selectList(queryWrapper);
                        if (CollUtil.isNotEmpty(rStatLimitRateDPOList)) {
                            Map<String, List<RStatLimitRateDPO>> map = rStatLimitRateDPOList.stream().collect(Collectors.groupingBy(RStatLimitRateDPO::getLineId));


                            if (CollUtil.isNotEmpty(monitorList)) {
                                DataQualityDetailsParam dataQualityDetailsParam = new DataQualityDetailsParam();
                                dataQualityDetailsParam.setCheckRules(monitorIds);
                                dataQualityDetailsParam.setStartTime(param.getStartTime());
                                dataQualityDetailsParam.setEndTime(param.getEndTime());
                                List<RStatIntegrityD> rStatIntegrityDList = lineIntegrityDataClient.getIntegrityData(dataQualityDetailsParam).getData();
                                Map<String, List<RStatIntegrityD>> stringListMap = rStatIntegrityDList.stream().collect(Collectors.groupingBy(RStatIntegrityD::getLineIndex));

                                List<DictData> voltageDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
                                Map<String, DictData> voltageMap = voltageDic.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

                                for (Monitor monitor : monitorList) {
                                    if (map.containsKey(monitor.getId())) {


                                        DimBusBarVO.DimBusBarMonitorVO tem = new DimBusBarVO.DimBusBarMonitorVO();
                                        tem.setMonitorId(monitor.getMonitorId());

                                        if (monitor.getId().equals(monitorIds.get(monitorIds.size() - 1))) {
                                            tem.setWhetherOptimal("1");
                                            tem.setWhetherOptimalName("是");
                                        } else {
                                            tem.setWhetherOptimal("0");
                                            tem.setWhetherOptimalName("否");
                                        }

                                        List<RStatIntegrityD> temR = stringListMap.get(monitor.getId());
                                        int due = temR.stream().mapToInt(RStatIntegrityD::getDueTime).sum();
                                        int real = temR.stream().mapToInt(RStatIntegrityD::getRealTime).sum();

                                        tem.setActualCollectNum(real);
                                        tem.setExpectCollectNum(due);
                                        if (due == 0) {
                                            tem.setDataFullRate(0.000f);
                                        } else {
                                            DecimalFormat decimalFormat = new DecimalFormat("#0.000");
                                            String rate = decimalFormat.format((float) real / due * 100);
                                            tem.setDataFullRate(Float.valueOf(rate));
                                        }
                                        tem.setBusId(dimBusBarVO.getMidId());
                                        tem.setBusName(dimBusBarVO.getBusName());
                                        tem.setId(IdUtil.simpleUUID());
                                        tem.setCityOrg(dimBusBarVO.getCityOrg());
                                        tem.setCityOrgName(dimBusBarVO.getCityOrgName());
                                        tem.setMaintOrg(dimBusBarVO.getCityOrg());
                                        tem.setMaintOrgName(dimBusBarVO.getCityOrgName());

                                        tem.setStationId(dimBusBarVO.getStationId());
                                        tem.setStationName(dimBusBarVO.getStationName());

                                        tem.setBusVoltageLevelName(voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getName());
                                        tem.setBusVoltageLevel(String.format("%02d", voltageMap.get(dimBusBarVO.getBusVoltageLevel()).getAlgoDescribe()));

                                        tem.setStatus("01");
                                        tem.setStatusName("运行");
                                        tem.setMonitorName(monitor.getName());
                                        tem.setStatDate(param.getStatDate());
                                        voList.add(tem);
                                    }
                                    result.setList(voList);
                                    result.setTotal(voList.size());
                                }
                            }
                        }
                    }
                }
            }
        }

        return result;
    }

    @Override
    public PmsPage<DimBusBarVO.DimBusBarMonitorAvgVO> getBusAvgListByMonitorId(DimBusBarParam param) {
        PmsPage<DimBusBarVO.DimBusBarMonitorAvgVO> result = new PmsPage<>(param.getPageNum(), param.getPageSize());
        if (StrUtil.isBlank(param.getBusId())) {
            return result;
        }
        List<DimBusBarVO.DimBusBarMonitorAvgVO> voList = new ArrayList<>();

        Page<DimBusBarVO> page = this.baseMapper.getBaseEvaOnlineBusDetail(new Page<>(param.getPageNum(), param.getPageSize()), param);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            Map<String, String> effectMap = new HashMap<>();
            if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_D.getCode())) {
                //具体日期投运,监测台账查询
                List<RDimBusUpD> rDimBusUpDList = rDimBusUpDMapper.selectList(new LambdaQueryWrapper<RDimBusUpD>().eq(RDimBusUpD::getMidBusId, param.getBusId())
                        .eq(RDimBusUpD::getStatisticDate, param.getStartTime()).eq(RDimBusUpD::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpD::getBusId, RDimBusUpD::getEffectIds));
            } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_M.getCode())) {
                List<RDimBusUpM> rDimBusUpDList = rDimBusUpMMapper.selectList(new LambdaQueryWrapper<RDimBusUpM>().eq(RDimBusUpM::getMidBusId, param.getBusId())
                        .eq(RDimBusUpM::getStatisticDate, param.getStartTime()).eq(RDimBusUpM::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpM::getBusId, RDimBusUpM::getEffectIds));
            } else if (param.getStatType().equals(DicDataEnum.STATISTICAL_TYPE_Y.getCode())) {
                List<RDimBusUpY> rDimBusUpDList = rDimBusUpYMapper.selectList(new LambdaQueryWrapper<RDimBusUpY>().eq(RDimBusUpY::getMidBusId, param.getBusId())
                        .eq(RDimBusUpY::getStatisticDate, param.getStartTime()).eq(RDimBusUpY::getPhasicType, "A"));
                effectMap = rDimBusUpDList.stream().collect(Collectors.toMap(RDimBusUpY::getBusId, RDimBusUpY::getEffectIds));
            }

            DimBusBarVO dimBusBarVO = page.getRecords().get(0);
            if (effectMap.containsKey(dimBusBarVO.getLineId())) {
                String effectIds = effectMap.get(dimBusBarVO.getLineId());
                if (StrUtil.isNotBlank(effectIds)) {
                    List<String> monitorIds = new ArrayList<>(Arrays.asList(effectIds.split(StrUtil.COMMA)));

                    List<Monitor> monitorList = monitorClient.getMonitorList(monitorIds).getData();
                    if (CollUtil.isNotEmpty(monitorList)) {
                        List<String> ids = monitorList.stream().map(Monitor::getId).collect(Collectors.toList());

                        Map<String, List<RStatLimitRateDPO>> map;
                        if (StrUtil.isNotBlank(param.getIndexType())) {
                            QueryWrapper<RStatLimitRateDPO> queryWrapper = new QueryWrapper<>();
                            harmMonitorTarget(param, queryWrapper);
                            queryWrapper.in("my_index", ids);
                            List<RStatLimitRateDPO> rStatLimitRateDPOList = rStatLimitRateDMapper.selectList(queryWrapper);
                            if (CollUtil.isNotEmpty(rStatLimitRateDPOList)) {
                                map = rStatLimitRateDPOList.stream().collect(Collectors.groupingBy(RStatLimitRateDPO::getLineId));
                            } else {
                                map = new HashMap<>();
                            }
                            monitorList = monitorList.stream().filter(item -> map.containsKey(item.getId())).collect(Collectors.toList());
                        }

                        if (CollUtil.isNotEmpty(monitorList)) {
                            List<String> temIds = monitorList.stream().map(Monitor::getId).collect(Collectors.toList());
                            QueryWrapper<RStatDataVD> queryWrapper = new QueryWrapper<>();
                            queryWrapper.select("avg(rms) as rms,line_id").in("line_id", temIds).between("time", param.getStartTime(), param.getEndTime()).in("phasic_type", Stream.of("A", "B", "C").collect(Collectors.toList())).eq("value_type", "AVG").groupBy("line_id");
                            List<RStatDataVD> rStatDataVDPOList = rStatDataVDMapper.selectList(queryWrapper);
                            Map<String, RStatDataVD> rStatDataVDMap = rStatDataVDPOList.stream().collect(Collectors.toMap(RStatDataVD::getLineId, Function.identity()));

                            List<DictData> dictDataList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_CONNECT.getCode()).getData();
                            Map<String, DictData> terminalWireMap = dictDataList.stream().collect(Collectors.toMap(DictData::getId, Function.identity()));

                            for (Monitor monitor : monitorList) {
                                DimBusBarVO.DimBusBarMonitorAvgVO vo = new DimBusBarVO.DimBusBarMonitorAvgVO();
                                vo.setBusName(dimBusBarVO.getBusName());
                                vo.setCityOrg(dimBusBarVO.getCityOrg());
                                vo.setCityOrgName(dimBusBarVO.getCityOrgName());
                                vo.setMaintOrg(dimBusBarVO.getMaintOrg());
                                vo.setMaintOrgName(dimBusBarVO.getMaintOrgName());
                                vo.setMonitorId(monitor.getMonitorId());
                                vo.setMonitorName(monitor.getName());
                                vo.setStationId(dimBusBarVO.getStationId());
                                vo.setStationName(dimBusBarVO.getStationName());
                                vo.setSeq(CollUtil.isNotEmpty(param.getSeqs()) ? String.join(StrUtil.COMMA, param.getSeqs()):"");
                                vo.setHarmonicNum(Objects.nonNull(param.getHarmonicNum())? param.getHarmonicNum().toString():"");
                                vo.setStatDate(param.getStatDate());
                                vo.setStatus("01");
                                vo.setStatusName("运行");
                                if (rStatDataVDMap.containsKey(monitor.getId())) {
                                    RStatDataVD rStatDataVD = rStatDataVDMap.get(monitor.getId());
                                    vo.setLineVoltage(rStatDataVD.getRms().setScale(4, RoundingMode.HALF_UP).toString());
                                    vo.setIndexValue(rStatDataVD.getRms().divide(BigDecimal.valueOf(Math.sqrt(3)), 4, RoundingMode.HALF_UP).toString());
                                }
                                DictData dictData = terminalWireMap.get(monitor.getTerminalWiringMethod());
                                vo.setTerminalConnect(dictData.getValue());
                                vo.setTerminalConnectName(dictData.getName());
                                voList.add(vo);

                            }
                        }
                    }
                }

            }

        }
        result.setTotal(voList.size());
        result.setList(voList);
        return result;
    }


    /**
     * 根据稳态指标筛选符合条件的母线
     *
     * @author cdf
     * @date 2024/5/14
     */
    private List<String> busTargetAss(DimBusBarParam param, List<String> temBusIds, List<RDimUpDTO> rDimUpDTOList) {
        String statisticType = param.getStatType();
        if (DicDataEnum.STATISTICAL_TYPE_D.getCode().equals(statisticType)) {
            QueryWrapper<RDimBusUpD> queryWrapper = new QueryWrapper<>();
            this.harmTarget(param, temBusIds, queryWrapper);
            List<RDimBusUpD> rDimBusUpDList = rDimBusUpDMapper.selectList(queryWrapper);
            Map<String, List<RDimBusUpD>> map = rDimBusUpDList.stream().collect(Collectors.groupingBy(RDimBusUpD::getBusId));
            map.forEach((key, val) -> {
                RDimUpDTO rDimUpDTO = new RDimUpDTO();
                rDimUpDTO.setBusMidId(val.get(0).getMidBusId());
                rDimUpDTO.setEffectId(val.get(0).getEffectId());
                rDimUpDTO.setEffectIds(val.get(0).getEffectIds());
                rDimUpDTO.setBusId(val.get(0).getBusId());
                rDimUpDTO.setV(val.stream().mapToDouble(RDimBusUpD::getV).filter(it -> it != 3.14159).average().orElse(3.14159));
                rDimUpDTOList.add(rDimUpDTO);
            });

            temBusIds = rDimBusUpDList.stream().map(RDimBusUpD::getMidBusId).distinct().collect(Collectors.toList());
            this.harmTarget(param, temBusIds, queryWrapper);
        } else if (DicDataEnum.STATISTICAL_TYPE_M.getCode().equals(statisticType)) {
            QueryWrapper<RDimBusUpM> queryWrapper = new QueryWrapper<>();
            this.harmTarget(param, temBusIds, queryWrapper);
            List<RDimBusUpM> rDimBusUpMList = rDimBusUpMMapper.selectList(queryWrapper);
            Map<String, List<RDimBusUpM>> map = rDimBusUpMList.stream().collect(Collectors.groupingBy(RDimBusUpM::getBusId));
            map.forEach((key, val) -> {
                RDimUpDTO rDimUpDTO = new RDimUpDTO();
                rDimUpDTO.setBusMidId(val.get(0).getMidBusId());
                rDimUpDTO.setBusId(val.get(0).getBusId());
                rDimUpDTO.setEffectId(val.get(0).getEffectId());
                rDimUpDTO.setEffectIds(val.get(0).getEffectIds());
                rDimUpDTO.setV(val.stream().mapToDouble(RDimBusUpM::getV).filter(it -> it != 3.14159).average().orElse(3.14159));
                rDimUpDTOList.add(rDimUpDTO);
            });
            temBusIds = rDimBusUpMList.stream().map(RDimBusUpM::getMidBusId).distinct().collect(Collectors.toList());
        } else if (DicDataEnum.STATISTICAL_TYPE_Y.getCode().equals(statisticType)) {
            QueryWrapper<RDimBusUpY> queryWrapper = new QueryWrapper<>();
            this.harmTarget(param, temBusIds, queryWrapper);
            List<RDimBusUpY> rDimBusUpYList = rDimBusUpYMapper.selectList(queryWrapper);
            Map<String, List<RDimBusUpY>> map = rDimBusUpYList.stream().collect(Collectors.groupingBy(RDimBusUpY::getBusId));
            map.forEach((key, val) -> {
                RDimUpDTO rDimUpDTO = new RDimUpDTO();
                rDimUpDTO.setBusMidId(val.get(0).getMidBusId());
                rDimUpDTO.setBusId(val.get(0).getBusId());
                rDimUpDTO.setEffectId(val.get(0).getEffectId());
                rDimUpDTO.setEffectIds(val.get(0).getEffectIds());
                rDimUpDTO.setV(val.stream().mapToDouble(RDimBusUpY::getV).filter(it -> it != 3.14159).average().orElse(3.14159));
                rDimUpDTOList.add(rDimUpDTO);
            });
            temBusIds = rDimBusUpYList.stream().map(RDimBusUpY::getMidBusId).distinct().collect(Collectors.toList());
        }
        return temBusIds;
    }


    private List<String> getOnlineBusIds(String nodeId, LocalDate begin, Class<?> clazz) {
        QueryWrapper<?> dayLam = new QueryWrapper<>();
        dayLam.eq("statistic_Date", begin).eq("dept_Id", nodeId);
        Object pmsRunStatistic = null;
        if (PmsRunStatisticD.class.equals(clazz)) {
            pmsRunStatistic = pmsRunStatisticDMapper.selectOne((QueryWrapper<PmsRunStatisticD>) dayLam);
        } else if (PmsRunStatisticM.class.equals(clazz)) {
            pmsRunStatistic = pmsRunStatisticMMapper.selectOne((QueryWrapper<PmsRunStatisticM>) dayLam);
        } else if (PmsRunStatisticY.class.equals(clazz)) {
            pmsRunStatistic = pmsRunStatisticYMapper.selectOne((QueryWrapper<PmsRunStatisticY>) dayLam);
        }
        if (Objects.nonNull(pmsRunStatistic)) {
            String onlineBusMidIds = null;
            if (pmsRunStatistic instanceof PmsRunStatisticD) {
                onlineBusMidIds = ((PmsRunStatisticD) pmsRunStatistic).getOnlineBusMidIds();
            } else if (pmsRunStatistic instanceof PmsRunStatisticM) {
                onlineBusMidIds = ((PmsRunStatisticM) pmsRunStatistic).getOnlineBusMidIds();
            } else {
                onlineBusMidIds = ((PmsRunStatisticY) pmsRunStatistic).getOnlineBusMidIds();
            }
            if (StrUtil.isNotBlank(onlineBusMidIds)) {
                return Arrays.asList(onlineBusMidIds.split(StrUtil.COMMA));
            }
        }
        return new ArrayList<>();
    }


    private void harmMonitorTarget(DimBusBarParam param, QueryWrapper queryWrapper) {
        //稳态指标条件筛选
        String target = "", harmV = "";
        switch (param.getIndexType()) {
            case "01":
                target = "voltage_dev_overtime";
                break;
            case "02":
                target = "flicker_overtime";
                break;
            case "03":
                target = "ubalance_overtime";
                break;
            case "04":
                target = "uaberrance_overtime";
                break;
            case "05":
                target = "harm_v";
                break;
        }
        if (CollectionUtil.isNotEmpty(param.getSeqs())) {
            queryWrapper.in("phasic_type", param.getSeqs());
        } else {
            queryWrapper.eq("phasic_type", "T");
        }

        queryWrapper.between("time_id", LocalDate.parse(param.getStartTime()), LocalDate.parse(param.getEndTime()));
        if (StrUtil.isNotBlank(param.getIndexType())) {
            if (param.getIndexType().equals("05")) {
                harmV = "uharm_" + param.getHarmonicNum() + "_overtime";
                queryWrapper.gt(harmV, 0);
            } else {
                queryWrapper.gt(target, 0);
            }
        }
        if (param.getIndexType().equals("05")) {
            queryWrapper.select("time_id", "phasic_type", "my_index as lineId", harmV);
        } else {
            queryWrapper.select("time_id", "phasic_type", "my_index as lineId", target);
        }
    }


    /**
     * 母线层级的
     *
     * @author cdf
     * @date 2024/6/17
     */

    private void harmTarget(DimBusBarParam param, List<String> temBusIds, QueryWrapper queryWrapper) {
        //稳态指标条件筛选
        String target = "", harmV = "";
        switch (param.getIndexType()) {
            case "01":
                target = "voltage_dev_overtime";
                break;
            case "02":
                target = "flicker_overtime";
                break;
            case "03":
                target = "ubalance_overtime";
                break;
            case "04":
                target = "uaberrance_overtime";
                break;
            case "05":
                target = "harm_v";
                break;
        }
        queryWrapper.select("statistic_date", "phasic_type", "bus_id", "mid_bus_id", "effect_id", "effect_ids", "voltage_level", "v");
        if (CollectionUtil.isNotEmpty(param.getSeqs())) {
            queryWrapper.in("phasic_type", param.getSeqs());
        }
        if (StrUtil.isNotBlank(param.getVoltageLevel())) {
            List<DictData> voltageDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DEV_VOLTAGE.getCode()).getData();
            Map<String, DictData> voltageMap = voltageDic.stream().collect(Collectors.toMap(item -> String.format("%02d", item.getAlgoDescribe()), Function.identity()));
            String voltage = voltageMap.get(param.getVoltageLevel()).getId();
            queryWrapper.in("voltage_level", voltage);
        }
        queryWrapper.in("mid_bus_id", temBusIds);
        queryWrapper.eq("statistic_date", LocalDate.parse(param.getStartTime()));

        if (StrUtil.isNotBlank(param.getIndexType())) {
            if (param.getIndexType().equals("05")) {
                harmV = "uharm_" + param.getHarmonicNum() + "_overtime";
                queryWrapper.gt(harmV, 0);
            } else {
                queryWrapper.gt(target, 0);
            }
        }
    }


    /**
     * 获取当前单位的层级
     */
    public LambdaQueryWrapper<RUploadEvaluationDataD> getDeptLevel(UploadDataParam param) {
        Dept dept = deptFeignClient.getDeptByCode(param.getOrgId()).getData();
        List<String> list = Arrays.stream(dept.getPids().split(",")).map(String::trim).collect(Collectors.toList());
        LambdaQueryWrapper<RUploadEvaluationDataD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String beginMonth = formatBeginMonth(param.getSearchBeginTime(), param.getDataType());
        switch (list.size()) {
            //国
            case 1:
                String orgId = getOrgIdForProvince(dept);
                addFiltersForProvince(lambdaQueryWrapper, orgId, beginMonth, param.getSearchState());
                break;
            //省
            case 2:
                addFilters(lambdaQueryWrapper, RUploadEvaluationDataD::getProvinceId, param.getOrgId(), beginMonth, param.getSearchState());
                break;
            //市
            case 3:
                addFilters(lambdaQueryWrapper, RUploadEvaluationDataD::getCityId, param.getOrgId(), beginMonth, param.getSearchState());
                break;
            //县
            case 4:
                addFilters(lambdaQueryWrapper, RUploadEvaluationDataD::getCountyId, param.getOrgId(), beginMonth, param.getSearchState());
                break;
            default:
                break;
        }
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(param.getVoltageLevel()), RUploadEvaluationDataD::getVoltageLevel, param.getVoltageLevel())
                .eq(StrUtil.isNotBlank(param.getTargetType()), RUploadEvaluationDataD::getIndexType, param.getTargetType())
                .eq(StrUtil.isNotBlank(param.getTargetType()) && param.getTargetType().equals("05"), RUploadEvaluationDataD::getHarmonicNum, param.getHarmCount());

        return lambdaQueryWrapper;
    }

    private String formatBeginMonth(String searchBeginTime, String dataType) {
        if (Objects.equals(dataType, "02")) {
            return DateUtil.format(DateUtil.beginOfMonth(DateUtil.parse(searchBeginTime, DatePattern.NORM_MONTH_PATTERN)), DatePattern.NORM_MONTH_PATTERN);
        } else if (Objects.equals(dataType, "01")) {
            return DateUtil.format(DateUtil.beginOfMonth(DateUtil.parse(searchBeginTime, DatePattern.NORM_YEAR_PATTERN)), DatePattern.NORM_YEAR_PATTERN);
        }
        return searchBeginTime;
    }

    private void addFiltersForProvince(LambdaQueryWrapper<RUploadEvaluationDataD> lambdaQueryWrapper, String orgId, String beginMonth, Integer searchState) {
        lambdaQueryWrapper.eq(RUploadEvaluationDataD::getProvinceId, orgId)
                .eq(RUploadEvaluationDataD::getStatisticalDate, beginMonth)
                .eq(!Objects.isNull(searchState), RUploadEvaluationDataD::getUploadStatus, searchState);
    }

    private void addFilters(LambdaQueryWrapper<RUploadEvaluationDataD> lambdaQueryWrapper, SFunction<RUploadEvaluationDataD, Object> idFunction, String orgId, String beginMonth, Integer searchState) {
        lambdaQueryWrapper.eq(idFunction, orgId)
                .eq(RUploadEvaluationDataD::getStatisticalDate, beginMonth)
                .eq(!Objects.isNull(searchState), RUploadEvaluationDataD::getUploadStatus, searchState);
    }

    private String getOrgIdForProvince(Dept dept) {
        List<Dept> l1 = deptFeignClient.getDirectSonSelf(dept.getId()).getData();
        return l1.stream()
                .filter(o -> !Objects.equals(o.getId(), dept.getId()))
                .findFirst()
                .map(Dept::getCode)
                .orElse(null);
    }

    /**
     * 国网上送返回信息
     *
     * @param step 分片上传当前阶段
     * @param ids  分片数据
     * @param send 上送结果
     * @return
     */
    private void returnInformation(Integer step, List<String> ids, Map<String, String> send, StrBuilder resultLog, AtomicBoolean resultFlag, LocalDate localDate) {
        int start = step * 100;
        int end = (step + 1) * 100;
        if (send.containsKey("succeed")) {
            String succeed = send.get("succeed");
            if (succeed.contains("\\\"")) {
                succeed = succeed.replace("\\\"", "\"");
            }
            Map mapData = JSON.parseObject(succeed, Map.class);
            String status = mapData.get("status").toString();

            if ("000000".equals(status)) {
                //修改数据上送状态
                updateState(ids);
                String result = mapData.get("result").toString();
                Map mapCount = JSON.parseObject(result, Map.class);
                String count = mapCount.get("count").toString();

            } else {
                resultFlag.set(false);
                String errors = mapData.get("errors").toString();
                String errorMsg = " 上送" + start + "条至" + end + "条数据,上送失败:" + status + "_" + errors + " ;";
                resultLog.append(errorMsg);
                assUploadLog(localDate, resultLog, resultFlag);
                throw new BusinessException(errorMsg);
            }
        } else {
            resultFlag.set(false);
            resultLog.append(" 上送" + start + "条至" + end + "条数据网络异常;");
            assUploadLog(localDate, resultLog, resultFlag);
            throw new BusinessException("当前时间段国网上送请求过多，请稍后再试");
        }


    }

    /**
     * 修改上送信息状态
     *
     * @param ids id集合
     */
    private void updateState(List<String> ids) {
        LambdaUpdateWrapper<RUploadEvaluationDataD> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(RUploadEvaluationDataD::getId, ids)
                .set(RUploadEvaluationDataD::getUploadStatus, 1);
        this.update(lambdaUpdateWrapper);
    }

    /**
     * 电压等级转换
     */
    public String getVoltage(String voltage) {
        DictData dictData = dicDataFeignClient.getDicDataById(voltage).getData();
        Integer code = dictData.getAlgoDescribe();
        if (Objects.isNull(code)) {
            return "99";
        }
        return (code < 10) ? "0" + code : String.valueOf(code);
    }

}
