package com.njcn.prepare.harmonic.service.mysql.newalgorithm.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.harmonic.pojo.po.*;
import com.njcn.prepare.harmonic.pojo.bo.CalculatedParam;
import com.njcn.prepare.harmonic.mapper.mysql.area.RMpMonitorAlarmCountMMapper;
import com.njcn.prepare.harmonic.mapper.mysql.area.RMpTargetWarnDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.area.RStatOrgMMapper;
import com.njcn.prepare.harmonic.pojo.po.*;
import com.njcn.prepare.harmonic.service.mysql.newalgorithm.*;
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 lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 指标告警统计
 * </p>
 *
 * @author zbj
 * @since 2023-06-12
 */
@Service
@RequiredArgsConstructor
public class RAlarmCountServiceImpl implements RAlarmCountService {

    private final RMpTargetWarnDMapper rMpTargetWarnDMapper;

    private final RMpMonitorAlarmCountMMapper rMpMonitorAlarmCountMMapper;

    private final RStatZwAlarmCountWPOService rStatZwAlarmCountWPOService;

    private final RStatPwAlarmCountWPOService rStatPwAlarmCountWPOService;

    private final RStatAreaAlarmCountMPOService rStatAreaAlarmCountMPOService;

    private final DicDataFeignClient dicDataFeignClient;

    private final RStatOrgMMapper rStatOrgMMapper;


    @Override
    public void handleDay(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<RStatZwAlarmCountWPO> rStatZwAlarmCountWPOS = new ArrayList<>();
        List<RStatPwAlarmCountWPO> rStatPwAlarmCountWPOS = new ArrayList<>();
        DateTime begin = DateUtil.beginOfWeek(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfWeek(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        LocalDate localDate = LocalDateTimeUtil.parseDate( DateUtil.format(begin, DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATE_PATTERN);


        QueryWrapper<RMpTargetWarnDPO> rMpTargetWarnDPOQueryWrapper = new QueryWrapper<>();

        calculatedParam.getIdList().forEach(deptGetChildrenMoreDTO -> {

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();

                List<String> collect1 = lineBaseList.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                rMpTargetWarnDPOQueryWrapper.clear();
                rMpTargetWarnDPOQueryWrapper.
                        in("measurement_point_id", collect1).
                        eq("is_effective", "1").
                        between("data_date", begin, end);

                List<RMpTargetWarnDPO> rMpTargetWarnDPOList = rMpTargetWarnDMapper.selectList(rMpTargetWarnDPOQueryWrapper);
                List<String> collect = rMpTargetWarnDPOList.stream().map(RMpTargetWarnDPO::getMeasurementPointId).distinct().collect(Collectors.toList());

                //告警4次及以上监测点数量
                long count = rMpTargetWarnDPOList.stream()
                        .filter(obj -> obj.getIsWarn() == 1)
                        .collect(Collectors.groupingBy(RMpTargetWarnDPO::getMeasurementPointId, Collectors.counting()))
                        .entrySet().stream()
                        .filter(e -> e.getValue() >= 4)
                        .count();

                // 使用 Stream API 进行流式处理，选择 status 为 1 的告警，按照 id 进行分组并统计个数
                Map<String, Double> avgStatusOneCountByAlarmId = rMpTargetWarnDPOList.stream()
                        .filter(alarm -> alarm.getIsWarn() == 1)
                        .collect(Collectors.groupingBy(RMpTargetWarnDPO::getMeasurementPointId, Collectors.counting()))
                        .entrySet().stream()
                        .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue() / 7.0));

                // 对 map 中的 value 进行从大到小的排序，并且排除 value 为 0 的元素
                Map<String, Double> sortedAvgStatusOneCountByAlarmId = avgStatusOneCountByAlarmId.entrySet().stream()
                        .filter(e -> e.getValue() != 0)
                        .sorted(Map.Entry.<String, Double>comparingByValue(Comparator.reverseOrder()))
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

                // 获取前 30% 的告警 id 数量
                double v = sortedAvgStatusOneCountByAlarmId.size() * 0.3;
                int top30PercentCount = (int) (v<1?Math.ceil(v):v);
                RStatZwAlarmCountWPO rStatZwAlarmCountWPO = new RStatZwAlarmCountWPO();
                rStatZwAlarmCountWPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                rStatZwAlarmCountWPO.setDataDate(localDate);
                rStatZwAlarmCountWPO.setMonitorEffectiveCount(collect.size());
                rStatZwAlarmCountWPO.setWarnMonitorCount(Integer.valueOf(count + ""));
                rStatZwAlarmCountWPO.setMonitorGradeCount(top30PercentCount);
                rStatZwAlarmCountWPOS.add(rStatZwAlarmCountWPO);

            }


            /*配网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getPwMonitorIds())) {
                List<LineDevGetDTO> pwMonitorIds = deptGetChildrenMoreDTO.getPwMonitorIds();
                List<String> collect1 = pwMonitorIds.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                rMpTargetWarnDPOQueryWrapper.clear();
                rMpTargetWarnDPOQueryWrapper.
                        in("measurement_point_id", collect1).
                        between("data_date", begin, end);

                List<RMpTargetWarnDPO> rMpTargetWarnDPOList = rMpTargetWarnDMapper.selectList(rMpTargetWarnDPOQueryWrapper);
                List<String> collect = rMpTargetWarnDPOList.stream().map(RMpTargetWarnDPO::getMeasurementPointId).distinct().collect(Collectors.toList());

                //获取告警监测点数
                long count = rMpTargetWarnDPOList.stream().filter(alarm -> alarm.getIsWarn() == 1).distinct().count();

                RStatPwAlarmCountWPO rStatPwAlarmCountWPO = new RStatPwAlarmCountWPO();
                rStatPwAlarmCountWPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                rStatPwAlarmCountWPO.setDataDate(localDate);
                rStatPwAlarmCountWPO.setOnlineMonitorCount(collect.size());
                rStatPwAlarmCountWPO.setAlarmMonitorCount(Integer.valueOf(count + ""));

                rStatPwAlarmCountWPOS.add(rStatPwAlarmCountWPO);
            }

        });
        if (!CollectionUtils.isEmpty(rStatZwAlarmCountWPOS)) {
            rStatZwAlarmCountWPOService.saveOrUpdateBatchByMultiId(rStatZwAlarmCountWPOS, 500);
        }
        if (!CollectionUtils.isEmpty(rStatPwAlarmCountWPOS)) {
            rStatPwAlarmCountWPOService.saveOrUpdateBatchByMultiId(rStatPwAlarmCountWPOS, 500);
        }

    }

    @Override
    public void handleMonth(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<RStatAreaAlarmCountMPO> rStatAreaAlarmCountMPOS = new ArrayList<>();

        DecimalFormat df = new DecimalFormat("0.00");

        //获取日期
        DateTime begin = DateUtil.beginOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfMonth(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        LocalDate localDate = LocalDateTimeUtil.parseDate( DateUtil.format(begin, DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATE_PATTERN);

        /*获取数据类型*/
        List<DictData> dataTypeList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.DATA_TYPE.getCode()).getData();
        Map<String, DictData> dataTypeMap = dataTypeList.stream().collect(Collectors.toMap(DictData::getCode, dictData -> dictData));

        QueryWrapper<RMpMonitorAlarmCountMPO> rMpMonitorAlarmCountMQueryWrapper = new QueryWrapper<>();
        //org表
        QueryWrapper<RStatOrgMPO> rStatOrgMPOQueryWrapper = new QueryWrapper<>();

        calculatedParam.getIdList().forEach(deptGetChildrenMoreDTO -> {

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                List<String> collect1 = lineBaseList.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

//                //日表
//                QueryWrapper<RMpTargetWarnDPO> rMpTargetWarnDPOQueryWrapper = new QueryWrapper<>();
//                rMpTargetWarnDPOQueryWrapper.clear();
//                rMpTargetWarnDPOQueryWrapper.
//                        in("measurement_point_id", collect1).
//                        between("data_date", begin, end);
//
//                List<RMpTargetWarnDPO> rMpTargetWarnDPOList = rMpTargetWarnDMapper.selectList(rMpTargetWarnDPOQueryWrapper);

                //月表
                rMpMonitorAlarmCountMQueryWrapper.clear();
                rMpMonitorAlarmCountMQueryWrapper.
                        in("measurement_point_id", collect1).
                        between("data_date", begin, end);
                List<RMpMonitorAlarmCountMPO> rMpMonitorAlarmCountMPOS = rMpMonitorAlarmCountMMapper.selectList(rMpMonitorAlarmCountMQueryWrapper);

                //org表
                rStatOrgMPOQueryWrapper.clear();
                rStatOrgMPOQueryWrapper.select("sum(effective_measurement_accrued) effective_measurement_accrued").
                        eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                        between("data_date", begin, end).
                        eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                RStatOrgMPO rStatOrgMPO = rStatOrgMMapper.selectOne(rStatOrgMPOQueryWrapper);

                //所有告警次数集合
                Map<String, Double> resultCount = new HashMap<>();
                long vdevAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getVdevAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long freqAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getFreqAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long unbalanceAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getUnbalanceAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long vAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getVAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long flickerAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getFlickerAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long sagAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getSagAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long interruptAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getInterruptAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                if (vdevAlarmInfoCount != 0){
                    resultCount.put("vdevAlarmInfo",vdevAlarmInfoCount*100.0);
                }
                if (freqAlarmInfoCount!=0){
                    resultCount.put("freqAlarmInfo",freqAlarmInfoCount*100.0);
                }
                if (unbalanceAlarmInfoCount!=0){
                    resultCount.put("unbalanceAlarmInfo",unbalanceAlarmInfoCount*100.0);
                }
                if (vAlarmInfoCount!=0){
                    resultCount.put("vAlarmInfo",vAlarmInfoCount*100.0);
                }
                if (flickerAlarmInfoCount!=0){
                    resultCount.put("flickerAlarmInfo",flickerAlarmInfoCount*100.0);
                }
                if (sagAlarmInfoCount!=0){
                    resultCount.put("sagAlarmInfo",sagAlarmInfoCount*100.0);
                }
                if (interruptAlarmInfoCount!=0){
                    resultCount.put("interruptAlarmInfo",interruptAlarmInfoCount*100.0);
                }


                //获取电压暂降告警次数
                long sagCount = rMpMonitorAlarmCountMPOS.stream().filter(alarm -> alarm.getSagAlarmInfo() == 1).count();
                //获取电压暂降监测点数(id去重)
                long sagMCount = rMpMonitorAlarmCountMPOS.stream().filter(obj -> obj.getSagAlarmInfo() == 1).map(obj -> obj.getMeasurementPointId()).distinct().count();

                //获取短时中断告警次数
                long iaaCount = rMpMonitorAlarmCountMPOS.stream().filter(alarm -> alarm.getInterruptAlarmInfo() == 1).count();
                //获取短时中断监测点数(id去重)
                long iaaMCount = rMpMonitorAlarmCountMPOS.stream().filter(obj -> obj.getInterruptAlarmInfo() == 1).map(obj -> obj.getMeasurementPointId()).distinct().count();

                //获取在线监测点数
                int size = rStatOrgMPO.getEffectiveMeasurementAccrued();
                //获取稳态告警监测点数
                long wtCount = rMpMonitorAlarmCountMPOS.stream()
                        .filter(obj -> obj.getVdevAlarmInfo() == 1 || obj.getFreqAlarmInfo() == 1 || obj.getUnbalanceAlarmInfo() == 1
                                || obj.getVAlarmInfo() == 1 || obj.getFlickerAlarmInfo() == 1).map(obj -> obj.getMeasurementPointId()).distinct().count();
                //获取暂态告警监测点数
                long ztCount = rMpMonitorAlarmCountMPOS.stream()
                        .filter(obj -> obj.getSagAlarmInfo() == 1 || obj.getInterruptAlarmInfo() == 1).map(obj -> obj.getMeasurementPointId()).distinct().count();

                RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO = new RStatAreaAlarmCountMPO();
                rStatAreaAlarmCountMPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                rStatAreaAlarmCountMPO.setDataDate(localDate);
                rStatAreaAlarmCountMPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                rStatAreaAlarmCountMPO.setVdevAlarmInfo(resultCount.containsKey("vdevAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setFreqAlarmInfo(resultCount.containsKey("freqAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setUnbalanceAlarmInfo(resultCount.containsKey("unbalanceAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setVAlarmInfo(resultCount.containsKey("vAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setFlickerAlarmInfo(resultCount.containsKey("flickerAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setSagAlarmInfo(resultCount.containsKey("sagAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setInterruptAlarmInfo(resultCount.containsKey("interruptAlarmInfo") ? 1 : 0);

                //稳态指标评级结果（0 较差 1中等 2较好）/ 暂态指标评级结果（0 较差 1中等 2较好）
                if (size == 0) {
                    rStatAreaAlarmCountMPO.setWtCount(0.00f);
                    rStatAreaAlarmCountMPO.setZtCount(0.00f);
                } else {
                    Float wtf = wtCount / Float.parseFloat(size + "");
                    rStatAreaAlarmCountMPO.setWtCount(wtf);
                    Float ztf = ztCount / Float.parseFloat(size + "");
                    rStatAreaAlarmCountMPO.setZtCount(ztf);
                }

                if (sagMCount == 0) {
                    rStatAreaAlarmCountMPO.setSagAlarmAvgCount(0);
                } else {
                    Float f = sagCount / Float.parseFloat(sagMCount + "");
                    rStatAreaAlarmCountMPO.setSagAlarmAvgCount(f.intValue());
                }
                if (iaaMCount == 0) {
                    rStatAreaAlarmCountMPO.setInterruptAlarmAvgCount(0);
                } else {
                    Float f = iaaCount / Float.parseFloat(iaaMCount + "");
                    rStatAreaAlarmCountMPO.setInterruptAlarmAvgCount(f.intValue());
                }

                if (Objects.isNull(rStatOrgMPO)) {
                    rStatAreaAlarmCountMPO.setVdevAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setFreqAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setVAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setFlickerAlarmRatio(0.00f);
                } else {
                    if (rStatOrgMPO.getEffectiveMeasurementAccrued() == 0) {
                        rStatAreaAlarmCountMPO.setVdevAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setFreqAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setVAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setFlickerAlarmRatio(0.00f);
                    } else {
                        //电压偏差告警占比
                        if (resultCount.containsKey("vdevAlarmInfo")) {
                            String value = df.format(resultCount.get("vdevAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setVdevAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setVdevAlarmRatio(0.00f);
                        }
                        //频率偏差告警占比
                        if (resultCount.containsKey("freqAlarmInfo")) {
                            String value = df.format(resultCount.get("freqAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setFreqAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setFreqAlarmRatio(0.00f);
                        }
                        //三项电压不平衡度告警占比
                        if (resultCount.containsKey("unbalanceAlarmInfo")) {
                            String value = df.format(resultCount.get("unbalanceAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(0.00f);
                        }
                        //谐波电压告警占比
                        if (resultCount.containsKey("vAlarmInfo")) {
                            String value = df.format(resultCount.get("vAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setVAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setVAlarmRatio(0.00f);
                        }
                        //闪変告警占比
                        if (resultCount.containsKey("flickerAlarmInfo")) {
                            String value = df.format(resultCount.get("flickerAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setFlickerAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setFlickerAlarmRatio(0.00f);
                        }
                    }
                }
                rStatAreaAlarmCountMPOS.add(rStatAreaAlarmCountMPO);
            }


            /*配网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getPwMonitorIds())) {
                List<LineDevGetDTO> pwMonitorIds = deptGetChildrenMoreDTO.getPwMonitorIds();
                List<String> collect1 = pwMonitorIds.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

//                //日表
//                QueryWrapper<RMpTargetWarnDPO> rMpTargetWarnDPOQueryWrapper = new QueryWrapper<>();
//                rMpTargetWarnDPOQueryWrapper.clear();
//                rMpTargetWarnDPOQueryWrapper.
//                        in("measurement_point_id", collect1).
//                        between("data_date", begin, end);
//
//                List<RMpTargetWarnDPO> rMpTargetWarnDPOList = rMpTargetWarnDMapper.selectList(rMpTargetWarnDPOQueryWrapper);

                //月表
                rMpMonitorAlarmCountMQueryWrapper.clear();
                rMpMonitorAlarmCountMQueryWrapper.
                        in("measurement_point_id", collect1).
                        between("data_date", begin, end);
                List<RMpMonitorAlarmCountMPO> rMpMonitorAlarmCountMPOS = rMpMonitorAlarmCountMMapper.selectList(rMpMonitorAlarmCountMQueryWrapper);

                //org表
                rStatOrgMPOQueryWrapper.clear();
                rStatOrgMPOQueryWrapper.select("sum(effective_measurement_accrued) effective_measurement_accrued").
                        eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                        between("data_date", begin, end).
                        eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                RStatOrgMPO rStatOrgMPO = rStatOrgMMapper.selectOne(rStatOrgMPOQueryWrapper);

                //所有告警次数集合
                Map<String, Double> resultCount = new HashMap<>();
                long vdevAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getVdevAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long freqAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getFreqAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long unbalanceAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getUnbalanceAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long vAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getVAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long flickerAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getFlickerAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long sagAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getSagAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                long interruptAlarmInfoCount = rMpMonitorAlarmCountMPOS.stream().filter(obj ->obj.getInterruptAlarmInfo() == 1).map(RMpMonitorAlarmCountMPO::getMeasurementPointId).distinct().count();
                if (vdevAlarmInfoCount != 0){
                    resultCount.put("vdevAlarmInfo",vdevAlarmInfoCount*100.0);
                }
                if (freqAlarmInfoCount!=0){
                    resultCount.put("freqAlarmInfo",freqAlarmInfoCount*100.0);
                }
                if (unbalanceAlarmInfoCount!=0){
                    resultCount.put("unbalanceAlarmInfo",unbalanceAlarmInfoCount*100.0);
                }
                if (vAlarmInfoCount!=0){
                    resultCount.put("vAlarmInfo",vAlarmInfoCount*100.0);
                }
                if (flickerAlarmInfoCount!=0){
                    resultCount.put("flickerAlarmInfo",flickerAlarmInfoCount*100.0);
                }
                if (sagAlarmInfoCount!=0){
                    resultCount.put("sagAlarmInfo",sagAlarmInfoCount*100.0);
                }
                if (interruptAlarmInfoCount!=0){
                    resultCount.put("interruptAlarmInfo",interruptAlarmInfoCount*100.0);
                }

                //获取电压暂降告警次数
                long sagCount = rMpMonitorAlarmCountMPOS.stream().filter(alarm -> alarm.getSagAlarmInfo() == 1).count();
                //获取电压暂降监测点数(id去重)
                long sagMCount = rMpMonitorAlarmCountMPOS.stream().filter(obj -> obj.getSagAlarmInfo() == 1).map(obj -> obj.getMeasurementPointId()).distinct().count();

                //获取短时中断告警次数
                long iaaCount = rMpMonitorAlarmCountMPOS.stream().filter(alarm -> alarm.getInterruptAlarmInfo() == 1).count();
                //获取短时中断监测点数(id去重)
                long iaaMCount = rMpMonitorAlarmCountMPOS.stream().filter(obj -> obj.getInterruptAlarmInfo() == 1).map(obj -> obj.getMeasurementPointId()).distinct().count();

                //获取在线监测点数
                int size = rStatOrgMPO.getEffectiveMeasurementAccrued();
                //获取稳态告警监测点数
                long wtCount = rMpMonitorAlarmCountMPOS.stream()
                        .filter(obj -> obj.getVdevAlarmInfo() == 1 || obj.getFreqAlarmInfo() == 1 || obj.getUnbalanceAlarmInfo() == 1
                                || obj.getVAlarmInfo() == 1 || obj.getFlickerAlarmInfo() == 1).count();
                //获取暂态告警监测点数
                long ztCount = rMpMonitorAlarmCountMPOS.stream()
                        .filter(obj -> obj.getSagAlarmInfo() == 1 || obj.getInterruptAlarmInfo() == 1).count();

                RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO = new RStatAreaAlarmCountMPO();
                rStatAreaAlarmCountMPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                rStatAreaAlarmCountMPO.setDataDate(localDate);
                rStatAreaAlarmCountMPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                rStatAreaAlarmCountMPO.setVdevAlarmInfo(resultCount.containsKey("vdevAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setFreqAlarmInfo(resultCount.containsKey("freqAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setUnbalanceAlarmInfo(resultCount.containsKey("unbalanceAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setVAlarmInfo(resultCount.containsKey("vAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setFlickerAlarmInfo(resultCount.containsKey("flickerAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setSagAlarmInfo(resultCount.containsKey("sagAlarmInfo") ? 1 : 0);
                rStatAreaAlarmCountMPO.setInterruptAlarmInfo(resultCount.containsKey("interruptAlarmInfo") ? 1 : 0);

                //稳态指标评级结果（0 较差 1中等 2较好）/ 暂态指标评级结果（0 较差 1中等 2较好）
                if (size == 0) {
                    rStatAreaAlarmCountMPO.setWtCount(0.00f);
                    rStatAreaAlarmCountMPO.setZtCount(0.00f);
                } else {
                    Float wtf = wtCount / Float.parseFloat(size + "");
                    rStatAreaAlarmCountMPO.setWtCount(wtf);
                    Float ztf = ztCount / Float.parseFloat(size + "");
                    rStatAreaAlarmCountMPO.setZtCount(ztf);
                }

                if (sagMCount == 0) {
                    rStatAreaAlarmCountMPO.setSagAlarmAvgCount(0);
                } else {
                    Float f = sagCount / Float.parseFloat(sagMCount + "");
                    rStatAreaAlarmCountMPO.setSagAlarmAvgCount(f.intValue());
                }
                if (iaaMCount == 0) {
                    rStatAreaAlarmCountMPO.setInterruptAlarmAvgCount(0);
                } else {
                    Float f = iaaCount / Float.parseFloat(iaaMCount + "");
                    rStatAreaAlarmCountMPO.setInterruptAlarmAvgCount(f.intValue());
                }

                if (Objects.isNull(rStatOrgMPO)) {
                    rStatAreaAlarmCountMPO.setVdevAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setFreqAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setVAlarmRatio(0.00f);
                    rStatAreaAlarmCountMPO.setFlickerAlarmRatio(0.00f);
                } else {
                    if (rStatOrgMPO.getEffectiveMeasurementAccrued() == 0) {
                        rStatAreaAlarmCountMPO.setVdevAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setFreqAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setVAlarmRatio(0.00f);
                        rStatAreaAlarmCountMPO.setFlickerAlarmRatio(0.00f);
                    } else {
                        //电压偏差告警占比
                        if (resultCount.containsKey("vdevAlarmInfo")) {
                            String value = df.format(resultCount.get("vdevAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setVdevAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setVdevAlarmRatio(0.00f);
                        }
                        //频率偏差告警占比
                        if (resultCount.containsKey("freqAlarmInfo")) {
                            String value = df.format(resultCount.get("freqAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setFreqAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setFreqAlarmRatio(0.00f);
                        }
                        //三项电压不平衡度告警占比
                        if (resultCount.containsKey("unbalanceAlarmInfo")) {
                            String value = df.format(resultCount.get("unbalanceAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setUnbalanceAlarmRatio(0.00f);
                        }
                        //谐波电压告警占比
                        if (resultCount.containsKey("vAlarmInfo")) {
                            String value = df.format(resultCount.get("vAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setVAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setVAlarmRatio(0.00f);
                        }
                        //闪変告警占比
                        if (resultCount.containsKey("flickerAlarmInfo")) {
                            String value = df.format(resultCount.get("flickerAlarmInfo") / rStatOrgMPO.getEffectiveMeasurementAccrued());
                            rStatAreaAlarmCountMPO.setFlickerAlarmRatio(Float.parseFloat(value));
                        } else {
                            rStatAreaAlarmCountMPO.setFlickerAlarmRatio(0.00f);
                        }
                    }
                }
                rStatAreaAlarmCountMPOS.add(rStatAreaAlarmCountMPO);
            }
        });

        if (!CollectionUtils.isEmpty(rStatAreaAlarmCountMPOS)) {
            //主网集合
            //稳态数据排序(大->小)
            List<RStatAreaAlarmCountMPO> zwwtResult = rStatAreaAlarmCountMPOS.stream().filter(obj -> obj.getDataType().equals(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId())).sorted(Comparator.comparing(RStatAreaAlarmCountMPO::getWtCount).reversed()).collect(Collectors.toList());
            List<RStatAreaAlarmCountMPO> zwztResult = rStatAreaAlarmCountMPOS.stream().filter(obj -> obj.getDataType().equals(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId())).sorted(Comparator.comparing(RStatAreaAlarmCountMPO::getZtCount).reversed()).collect(Collectors.toList());
            List<RStatAreaAlarmCountMPO> zwResult = new ArrayList<>();
            //配网集合
            List<RStatAreaAlarmCountMPO> pwwtResult = rStatAreaAlarmCountMPOS.stream().filter(obj -> obj.getDataType().equals(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId())).sorted(Comparator.comparing(RStatAreaAlarmCountMPO::getWtCount).reversed()).collect(Collectors.toList());
            List<RStatAreaAlarmCountMPO> pwztResult = rStatAreaAlarmCountMPOS.stream().filter(obj -> obj.getDataType().equals(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId())).sorted(Comparator.comparing(RStatAreaAlarmCountMPO::getZtCount).reversed()).collect(Collectors.toList());
            List<RStatAreaAlarmCountMPO> pwResult = new ArrayList<>();

            int i = 0;
            //主网稳态
            if (!CollectionUtils.isEmpty(zwwtResult)) {
                if (zwwtResult.size() == 1) {
                    zwwtResult.get(0).setHarmonicTypeGrade(0);
                } else if (zwwtResult.size() == 2) {
                    zwwtResult.get(0).setHarmonicTypeGrade(0);
                    zwwtResult.get(1).setHarmonicTypeGrade(1);
                } else {
                    i = (int) (zwwtResult.size() * 0.3)+1;
                    if (i < 1) {
                        i = 1;
                    }
                    //循环较差的
                    for (int i1 = 0; i1 < i; i1++) {
                        zwwtResult.get(i1).setHarmonicTypeGrade(0);
                    }
                    //循环较好的
                    List<RStatAreaAlarmCountMPO> list = zwwtResult.subList(zwwtResult.size() - i, zwwtResult.size());
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : list) {
                        rStatAreaAlarmCountMPO.setHarmonicTypeGrade(2);
                    }
                    //循环中等的
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : zwwtResult) {
                        if (Objects.isNull(rStatAreaAlarmCountMPO.getHarmonicTypeGrade())) {
                            rStatAreaAlarmCountMPO.setHarmonicTypeGrade(1);
                        }
                    }
                }
                zwResult.addAll(zwwtResult);
            }
            //主网暂态
            if (!CollectionUtils.isEmpty(zwztResult)) {
                if (zwztResult.size() == 1) {
                    zwztResult.get(0).setEventTypeGrade(0);
                } else if (zwztResult.size() == 2) {
                    zwztResult.get(0).setEventTypeGrade(0);
                    zwztResult.get(1).setEventTypeGrade(1);
                } else {
                    i = (int) (zwztResult.size() * 0.3)+1;
                    if (i < 1) {
                        i = 1;
                    }
                    //循环较差的
                    for (int i1 = 0; i1 < i; i1++) {
                        zwztResult.get(i1).setEventTypeGrade(0);
                    }
                    //循环较好的
                    List<RStatAreaAlarmCountMPO> list = zwztResult.subList(zwztResult.size() - i, zwztResult.size());
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : list) {
                        rStatAreaAlarmCountMPO.setEventTypeGrade(2);
                    }
                    //循环中等的
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : zwztResult) {
                        if (Objects.isNull(rStatAreaAlarmCountMPO.getEventTypeGrade())) {
                            rStatAreaAlarmCountMPO.setEventTypeGrade(1);
                        }
                    }
                }

                for (RStatAreaAlarmCountMPO po : zwResult) {
                    for (RStatAreaAlarmCountMPO po1 : zwztResult) {
                        if (Objects.equals(po.getOrgNo(), po1.getOrgNo())) {
                            po.setEventTypeGrade(po1.getEventTypeGrade());
                        }
                    }

                }
            }

            //配网稳态
            if (!CollectionUtils.isEmpty(pwwtResult)) {
                if (pwwtResult.size() == 1) {
                    pwwtResult.get(0).setHarmonicTypeGrade(0);
                } else if (pwwtResult.size() == 2) {
                    pwwtResult.get(0).setHarmonicTypeGrade(0);
                    pwwtResult.get(1).setHarmonicTypeGrade(1);
                } else {
                    i = (int) (pwwtResult.size() * 0.3)+1;
                    if (i < 1) {
                        i = 1;
                    }
                    //循环较差的
                    for (int i1 = 0; i1 < i; i1++) {
                        pwwtResult.get(i1).setHarmonicTypeGrade(0);
                    }
                    //循环较好的
                    List<RStatAreaAlarmCountMPO> list = pwwtResult.subList(pwwtResult.size() - i, pwwtResult.size());
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : list) {
                        rStatAreaAlarmCountMPO.setHarmonicTypeGrade(2);
                    }
                    //循环中等的
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : pwwtResult) {
                        if (Objects.isNull(rStatAreaAlarmCountMPO.getHarmonicTypeGrade())) {
                            rStatAreaAlarmCountMPO.setHarmonicTypeGrade(1);
                        }
                    }
                }
                pwResult.addAll(pwwtResult);
            }
            //配网暂态
            if (!CollectionUtils.isEmpty(pwztResult)) {
                if (pwztResult.size() == 1) {
                    pwztResult.get(0).setEventTypeGrade(0);
                } else if (pwztResult.size() == 2) {
                    pwztResult.get(0).setEventTypeGrade(0);
                    pwztResult.get(1).setEventTypeGrade(1);
                } else {
                    i = (int) (pwztResult.size() * 0.3)+1;
                    if (i < 1) {
                        i = 1;
                    }
                    //循环较差的
                    for (int i1 = 0; i1 < i; i1++) {
                        pwztResult.get(i1).setEventTypeGrade(0);
                    }
                    //循环较好的
                    List<RStatAreaAlarmCountMPO> list = pwztResult.subList(pwztResult.size() - i, pwztResult.size());
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : list) {
                        rStatAreaAlarmCountMPO.setEventTypeGrade(2);
                    }
                    //循环中等的
                    for (RStatAreaAlarmCountMPO rStatAreaAlarmCountMPO : pwztResult) {
                        if (Objects.isNull(rStatAreaAlarmCountMPO.getEventTypeGrade())) {
                            rStatAreaAlarmCountMPO.setEventTypeGrade(1);
                        }
                    }
                }
                for (RStatAreaAlarmCountMPO po : pwResult) {
                    for (RStatAreaAlarmCountMPO po1 : pwztResult) {
                        if (Objects.equals(po.getOrgNo(), po1.getOrgNo())) {
                            po.setEventTypeGrade(po1.getEventTypeGrade());
                        }
                    }
                }
            }

            zwResult.addAll(pwResult);


            if (!CollectionUtils.isEmpty(zwResult)) {
                rStatAreaAlarmCountMPOService.saveOrUpdateBatchByMultiId(zwResult, 500);
            }
        }

    }







}
