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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.DeptGetChildrenMoreDTO;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.harmonic.pojo.po.RMpEventDetailDPO;
import com.njcn.harmonic.pojo.po.RMpEventDetailMPO;
import com.njcn.harmonic.pojo.po.RStatOrgDPO;
import com.njcn.harmonic.pojo.po.RStatOrgMPO;
import com.njcn.prepare.harmonic.mapper.mysql.area.RStatOrgDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.area.RStatOrgMMapper;
import com.njcn.prepare.harmonic.mapper.mysql.area.RStatOrgQMapper;
import com.njcn.prepare.harmonic.mapper.mysql.area.RStatOrgYMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpEventDetailDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpEventDetailMMapper;
import com.njcn.prepare.harmonic.mapper.mysql.newalgorithm.RStatEventDPOMapper;
import com.njcn.prepare.harmonic.mapper.mysql.newalgorithm.RStatEventMPOMapper;
import com.njcn.prepare.harmonic.pojo.mysql.po.RStatOrgQPO;
import com.njcn.prepare.harmonic.pojo.mysql.po.RStatOrgYPO;
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.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 暂态指标统计
 * </p>
 *
 * @author zbj
 * @since 2023-06-06
 */
@Service
@RequiredArgsConstructor
public class RStatEventServiceImpl implements RStatEventService {

    private final DicDataFeignClient dicDataFeignClient;

    private final RMpEventDetailDMapper rMpEventDetailDMapper;

    private final RMpEventDetailMMapper rMpEventDetailMMapper;

    private final RStatEventDPOService rStatEventDPOService;

    private final RStatEventMPOService rStatEventMPOService;

    private final RStatEventDPOMapper rStatEventDPOMapper;

    private final RStatEventMPOMapper rStatEventMPOMapper;

    private final RStatEventQPOService rStatEventQPOService;

    private final RStatEventYPOService rStatEventYPOService;

    private final RStatOrgDMapper rStatOrgDMapper;

    private final RStatOrgMMapper rStatOrgMMapper;

    private final RStatOrgQMapper rStatOrgQMapper;

    private final RStatOrgYMapper rStatOrgYMapper;

    @Override
    public void handler(List<DeptGetChildrenMoreDTO> data, String dataDate, Integer type) {
        switch (type) {
            case 1:
                this.rStartEventYHandler (data, dataDate, type);
                break;
            case 2:
                this.rStartEventQHandler(data, dataDate, type);
                break;
            case 3:
                this.rStartEventMHandler(data, dataDate, type);
                break;
            case 5:
                this.rStartEventDHandler(data, dataDate, type);
                break;
            default:
                break;
        }
    }

    //天表
    public void rStartEventDHandler(List<DeptGetChildrenMoreDTO> data, String dataDate, Integer type) {
        List<RStatEventDPO> rStatEventDPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00");
        Date date = DateUtil.parse(dataDate);
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        /*获取暂态统计指标*/
        List<DictData> eventStatis = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();

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

        /*获取监测点类型类型*/
        List<DictData> lineSortList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_SORT.getCode()).getData();
        Map<String, DictData> lineSortMap = lineSortList.stream().collect(Collectors.toMap(DictData::getCode, dictData -> dictData));

        QueryWrapper<RMpEventDetailDPO> rMpEventDetailDPOQueryWrapper = new QueryWrapper<>();
        QueryWrapper<RStatOrgDPO> rStatOrgDPOQueryWrapper = new QueryWrapper<>();

        data.forEach(deptGetChildrenMoreDTO -> {

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<Integer, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailDPOQueryWrapper.clear();
                    rMpEventDetailDPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", dataDate);
                    List<RMpEventDetailDPO> rMpEventDetailDPOS = rMpEventDetailDMapper.selectList(rMpEventDetailDPOQueryWrapper);

                    rStatOrgDPOQueryWrapper.clear();
                    rStatOrgDPOQueryWrapper.select("effective_measurement").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId()).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", dataDate);
                    RStatOrgDPO rStatOrgDPO = rStatOrgDMapper.selectOne(rStatOrgDPOQueryWrapper);

                    eventStatis.forEach(dictData -> {
                                if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                        || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                        || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                        || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                                    return;
                                }
                                List<Integer> transientStatisData = getTransientStatisData(dictData, rMpEventDetailDPOS);
                                RStatEventDPO rStatEventDPO = new RStatEventDPO();
                                rStatEventDPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                                rStatEventDPO.setDataDate(localDate);
                                rStatEventDPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                                rStatEventDPO.setEventType(dictData.getId());
                                rStatEventDPO.setEventMeasurement(transientStatisData.get(0));
                                rStatEventDPO.setEventCount(transientStatisData.get(1));
                                rStatEventDPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                                if (Objects.isNull(rStatOrgDPO)) {
                                    rStatEventDPO.setEventMeasurementRatio(1.00f);
                                } else {
                                    if (rStatOrgDPO.getEffectiveMeasurement() == 0) {
                                        rStatEventDPO.setEventMeasurementRatio(1.00f);
                                    } else {
                                        String value = df.format(rStatEventDPO.getEventMeasurement() / rStatOrgDPO.getEffectiveMeasurement().floatValue());
                                        rStatEventDPO.setEventMeasurementRatio(Float.parseFloat(value));
                                    }
                                }

                                rStatEventDPOList.add(rStatEventDPO);
                            }
                    );
                });
            }

            /*配网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getPwMonitorIds())) {
                List<LineDevGetDTO> pwMonitorIds = deptGetChildrenMoreDTO.getPwMonitorIds();
                Map<Integer, List<LineDevGetDTO>> collect = pwMonitorIds.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailDPOQueryWrapper.clear();
                    rMpEventDetailDPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", dataDate);
                    List<RMpEventDetailDPO> rMpEventDetailDPOS = rMpEventDetailDMapper.selectList(rMpEventDetailDPOQueryWrapper);

                    rStatOrgDPOQueryWrapper.clear();
                    rStatOrgDPOQueryWrapper.select("effective_measurement").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId()).
                            eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", dataDate);
                    RStatOrgDPO rStatOrgDPO = rStatOrgDMapper.selectOne(rStatOrgDPOQueryWrapper);

                    eventStatis.forEach(dictData -> {
                                if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                        || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                        || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                        || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                                    return;
                                }
                                List<Integer> transientStatisData = getTransientStatisData(dictData, rMpEventDetailDPOS);
                                RStatEventDPO rStatEventDPO = new RStatEventDPO();
                                rStatEventDPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                                rStatEventDPO.setDataDate(localDate);
                                rStatEventDPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                                rStatEventDPO.setEventType(dictData.getId());
                                rStatEventDPO.setEventMeasurement(transientStatisData.get(0));
                                rStatEventDPO.setEventCount(transientStatisData.get(1));
                                rStatEventDPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                                if (Objects.isNull(rStatOrgDPO)) {
                                    rStatEventDPO.setEventMeasurementRatio(1.00f);
                                } else {
                                    if (rStatOrgDPO.getEffectiveMeasurement() == 0) {
                                        rStatEventDPO.setEventMeasurementRatio(1.00f);
                                    } else {
                                        String value = df.format(rStatEventDPO.getEventMeasurement() / rStatOrgDPO.getEffectiveMeasurement().floatValue());
                                        rStatEventDPO.setEventMeasurementRatio(Float.parseFloat(value));
                                    }
                                }
                                rStatEventDPOList.add(rStatEventDPO);
                            }
                    );
                });
            }

        });
        if (!CollectionUtils.isEmpty(rStatEventDPOList)) {
            rStatEventDPOService.saveOrUpdateBatchByMultiId(rStatEventDPOList, 500);
        }
    }

    //月表
    public void rStartEventMHandler(List<DeptGetChildrenMoreDTO> data, String dataDate, Integer type) {
        List<RStatEventMPO> rStatEventMPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00");
        Date date = DateUtil.parse(dataDate);
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        /*获取暂态统计指标*/
        List<DictData> eventStatis = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();

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

        /*获取监测点类型类型*/
        List<DictData> lineSortList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_SORT.getCode()).getData();
        Map<String, DictData> lineSortMap = lineSortList.stream().collect(Collectors.toMap(DictData::getCode, dictData -> dictData));

        //详情表
        QueryWrapper<RMpEventDetailMPO> rMpEventDetailMPOQueryWrapper = new QueryWrapper<>();
        //org表
        QueryWrapper<RStatOrgMPO> rStatOrgMPOQueryWrapper = new QueryWrapper<>();
        //天表
        QueryWrapper<RStatEventDPO> rStatEventDPOQueryWrapper = new QueryWrapper<>();

        data.forEach(deptGetChildrenMoreDTO -> {

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<Integer, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailMPOQueryWrapper.clear();
                    rMpEventDetailMPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            eq("DATE_FORMAT( data_date ,'%Y-%m')", dataDate.substring(0, 7));
                    List<RMpEventDetailMPO> rMpEventDetailMPOS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

                    rStatOrgMPOQueryWrapper.clear();
                    rStatOrgMPOQueryWrapper.select("effective_measurement_accrued").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId()).
                            eq("DATE_FORMAT( data_date ,'%Y-%m')", dataDate.substring(0, 7));
                    RStatOrgMPO rStatOrgMPO = rStatOrgMMapper.selectOne(rStatOrgMPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("DATE_FORMAT( data_date ,'%Y-%m')", dataDate.substring(0, 7)).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                    List<RStatEventDPO> rStatEventDPO = rStatEventDPOMapper.selectList(rStatEventDPOQueryWrapper);


                    //求各个类型的平均值
                    Map<String, Double> avgEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.averagingInt(RStatEventDPO::getEventMeasurement)));

                    //event_measurement的和
                    Map<String, Integer> sumEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventMeasurement)));

                    //event_count
                    Map<String, Integer> sumEC = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventCount)));

                    //event_measurement_ratio
                    Map<String, Double> avgEMR = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.averagingDouble(RStatEventDPO::getEventMeasurementRatio)));


                    eventStatis.forEach(dictData -> {
                        if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                            return;
                        }
                        //累计发生暂态监测点数
                        Integer statisData = getStatisData(dictData, rMpEventDetailMPOS);

                        RStatEventMPO rStatEventMPO = new RStatEventMPO();
                        rStatEventMPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventMPO.setDataDate(localDate);
                        rStatEventMPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                        rStatEventMPO.setEventType(dictData.getId());
                        rStatEventMPO.setEventMeasurementAverage(Float.parseFloat(df.format(avgEM.get(dictData.getId()))));
                        rStatEventMPO.setEventMeasurementAccrued(statisData);
                        rStatEventMPO.setEventCount(sumEC.get(dictData.getId()));
                        rStatEventMPO.setEventMeasurementRatioAverage(Float.parseFloat(df.format(avgEMR.get(dictData.getId()))));
                        rStatEventMPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventMPO.setEventFreq(1.00f);
                        } else {
                            String value = df.format(sumEC.get(dictData.getId()) / sumEM.get(dictData.getId()).floatValue());
                            rStatEventMPO.setEventFreq(Float.parseFloat(value));
                        }
                        if (Objects.isNull(rStatOrgMPO)) {
                            rStatEventMPO.setEventMeasurementRatioAccrued(1.00f);
                        } else {
                            if (rStatOrgMPO.getEffectiveMeasurementAccrued() == 0) {
                                rStatEventMPO.setEventMeasurementRatioAccrued(1.00f);
                            } else {
                                String value = df.format(statisData / rStatOrgMPO.getEffectiveMeasurementAccrued().floatValue());
                                rStatEventMPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
                            }
                        }
                        rStatEventMPOList.add(rStatEventMPO);
                    });
                });
            }

            /*配网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getPwMonitorIds())) {
                List<LineDevGetDTO> pwMonitorIds = deptGetChildrenMoreDTO.getPwMonitorIds();
                Map<Integer, List<LineDevGetDTO>> collect = pwMonitorIds.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailMPOQueryWrapper.clear();
                    rMpEventDetailMPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            eq("DATE_FORMAT( data_date ,'%Y-%m')", dataDate.substring(0, 7));
                    List<RMpEventDetailMPO> rMpEventDetailMPOS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

                    rStatOrgMPOQueryWrapper.clear();
                    rStatOrgMPOQueryWrapper.select("effective_measurement_accrued").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId()).
                            eq("DATE_FORMAT( data_date ,'%Y-%m')", dataDate.substring(0, 7));
                    RStatOrgMPO rStatOrgMPO = rStatOrgMMapper.selectOne(rStatOrgMPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("DATE_FORMAT( data_date ,'%Y-%m')", dataDate.substring(0, 7)).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                    List<RStatEventDPO> rStatEventDPO = rStatEventDPOMapper.selectList(rStatEventDPOQueryWrapper);


                    //求各个类型的平均值
                    Map<String, Double> avgEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.averagingInt(RStatEventDPO::getEventMeasurement)));

                    //event_measurement的和
                    Map<String, Integer> sumEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventMeasurement)));

                    //event_count
                    Map<String, Integer> sumEC = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventCount)));

                    //event_measurement_ratio
                    Map<String, Double> avgEMR = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.averagingDouble(RStatEventDPO::getEventMeasurementRatio)));


                    eventStatis.forEach(dictData -> {
                        if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                            return;
                        }
                        //累计发生暂态监测点数
                        Integer statisData = getStatisData(dictData, rMpEventDetailMPOS);

                        RStatEventMPO rStatEventMPO = new RStatEventMPO();
                        rStatEventMPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventMPO.setDataDate(localDate);
                        rStatEventMPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                        rStatEventMPO.setEventType(dictData.getId());
                        rStatEventMPO.setEventMeasurementAverage(Float.parseFloat(df.format(avgEM.get(dictData.getId()))));
                        rStatEventMPO.setEventMeasurementAccrued(statisData);
                        rStatEventMPO.setEventCount(sumEC.get(dictData.getId()));
                        rStatEventMPO.setEventMeasurementRatioAverage(Float.parseFloat(df.format(avgEMR.get(dictData.getId()))));
                        rStatEventMPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventMPO.setEventFreq(1.00f);
                        } else {
                            String value = df.format(sumEC.get(dictData.getId()) / sumEM.get(dictData.getId()).floatValue());
                            rStatEventMPO.setEventFreq(Float.parseFloat(value));
                        }
                        if (Objects.isNull(rStatOrgMPO)) {
                            rStatEventMPO.setEventMeasurementRatioAccrued(1.00f);
                        } else {
                            if (rStatOrgMPO.getEffectiveMeasurementAccrued() == 0) {
                                rStatEventMPO.setEventMeasurementRatioAccrued(1.00f);
                            } else {
                                String value = df.format(statisData / rStatOrgMPO.getEffectiveMeasurementAccrued().floatValue());
                                rStatEventMPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
                            }
                        }
                        rStatEventMPOList.add(rStatEventMPO);
                    });
                });
            }

        });
        if (!CollectionUtils.isEmpty(rStatEventMPOList)) {
            rStatEventMPOService.saveOrUpdateBatchByMultiId(rStatEventMPOList, 500);
        }
    }

    //季表
    public void rStartEventQHandler(List<DeptGetChildrenMoreDTO> data, String dataDate, Integer type) {
        List<RStatEventQPO> rStatEventQPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00");
        Date date = DateUtil.parse(dataDate);
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 计算季度的开始日期和结束日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int quarter = (calendar.get(Calendar.MONTH) / 3) + 1; // 计算日期所在的季度
        calendar.set(Calendar.MONTH, (quarter - 1) * 3); // 设置季度开始的月份
        calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置季度开始的日期
        Date startDate = calendar.getTime(); // 季度开始日期
        calendar.add(Calendar.MONTH, 2); // 添加两个月，使其到季度结束的月份
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); // 设置季度结束的日期 - 月份最后一天
        Date endDate = calendar.getTime(); // 季度结束日期

        /*获取暂态统计指标*/
        List<DictData> eventStatis = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();

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

        /*获取监测点类型类型*/
        List<DictData> lineSortList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_SORT.getCode()).getData();
        Map<String, DictData> lineSortMap = lineSortList.stream().collect(Collectors.toMap(DictData::getCode, dictData -> dictData));

        //详情表
        QueryWrapper<RMpEventDetailMPO> rMpEventDetailMPOQueryWrapper = new QueryWrapper<>();
        //org季表
        QueryWrapper<RStatOrgQPO> rStatOrgQPOQueryWrapper = new QueryWrapper<>();
        //天表
        QueryWrapper<RStatEventDPO> rStatEventDPOQueryWrapper = new QueryWrapper<>();
        //月表
        QueryWrapper<RStatEventMPO> rStatEventMPOQueryWrapper = new QueryWrapper<>();

        data.forEach(deptGetChildrenMoreDTO -> {

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<Integer, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailMPOQueryWrapper.clear();
                    rMpEventDetailMPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            between("data_date", startDate, endDate);
                    List<RMpEventDetailMPO> rMpEventDetailMPOS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

                    //季表
                    rStatOrgQPOQueryWrapper.clear();
                    rStatOrgQPOQueryWrapper.select("effective_measurement_accrued").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId()).
                            between("data_date", startDate, endDate);
                    ;
                    RStatOrgQPO rStatOrgQPO = rStatOrgQMapper.selectOne(rStatOrgQPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                    List<RStatEventDPO> rStatEventDPO = rStatEventDPOMapper.selectList(rStatEventDPOQueryWrapper);

                    //月表
                    rStatEventMPOQueryWrapper.clear();
                    rStatEventMPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                    List<RStatEventMPO> rStatEventMPO = rStatEventMPOMapper.selectList(rStatEventMPOQueryWrapper);

                    //求各个类型的平均值(月表）
                    Map<String, Double> avgEMM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementAverage)));

                    //event_measurement的和
                    Map<String, Integer> sumEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventMeasurement)));

                    //event_count（天表）
                    Map<String, Integer> sumEC = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventCount)));

                    //event_count（月表）
                    Map<String, Integer> sumECM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.summingInt(RStatEventMPO::getEventCount)));

                    //event_measurement_ratio_average（月表）
                    Map<String, Double> avgEMRM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementRatioAverage)));


                    eventStatis.forEach(dictData -> {
                        if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                            return;
                        }
                        //累计发生暂态监测点数
                        Integer statisData = getStatisQData(dictData, rMpEventDetailMPOS);

                        RStatEventQPO rStatEventQPO = new RStatEventQPO();
                        rStatEventQPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventQPO.setDataDate(localDate);
                        rStatEventQPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                        rStatEventQPO.setEventType(dictData.getId());
                        rStatEventQPO.setEventMeasurementAverage(Float.parseFloat(df.format(avgEMM.get(dictData.getId()))));
                        // todo
                        rStatEventQPO.setEventMeasurementAccrued(statisData);
                        rStatEventQPO.setEventCount(sumECM.get(dictData.getId()));
                        rStatEventQPO.setEventMeasurementRatioAverage(Float.parseFloat(df.format(avgEMRM.get(dictData.getId()))));
                        rStatEventQPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventQPO.setEventFreq(1.00f);
                        } else {
                            String value = df.format(sumEC.get(dictData.getId()) / sumEM.get(dictData.getId()).floatValue());
                            rStatEventQPO.setEventFreq(Float.parseFloat(value));
                        }
                        if (Objects.isNull(rStatOrgQPO)) {
                            rStatEventQPO.setEventMeasurementRatioAccrued(1.00f);
                        } else {
                            if (rStatOrgQPO.getEffectiveMeasurementAccrued() == 0) {
                                rStatEventQPO.setEventMeasurementRatioAccrued(1.00f);
                            } else {
                                String value = df.format(statisData / rStatOrgQPO.getEffectiveMeasurementAccrued().floatValue());
                                rStatEventQPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
                            }
                        }
                        rStatEventQPOList.add(rStatEventQPO);
                    });
                });
            }

            /*配网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getPwMonitorIds())) {
                List<LineDevGetDTO> pwMonitorIds = deptGetChildrenMoreDTO.getPwMonitorIds();
                Map<Integer, List<LineDevGetDTO>> collect = pwMonitorIds.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());
                    rMpEventDetailMPOQueryWrapper.clear();
                    rMpEventDetailMPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            between("data_date", startDate, endDate);
                    List<RMpEventDetailMPO> rMpEventDetailMPOS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

                    //季表
                    rStatOrgQPOQueryWrapper.clear();
                    rStatOrgQPOQueryWrapper.select("effective_measurement_accrued").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId()).
                            between("data_date", startDate, endDate);
                    ;
                    RStatOrgQPO rStatOrgQPO = rStatOrgQMapper.selectOne(rStatOrgQPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                    List<RStatEventDPO> rStatEventDPO = rStatEventDPOMapper.selectList(rStatEventDPOQueryWrapper);

                    //月表
                    rStatEventMPOQueryWrapper.clear();
                    rStatEventMPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                    List<RStatEventMPO> rStatEventMPO = rStatEventMPOMapper.selectList(rStatEventMPOQueryWrapper);

                    //求各个类型的平均值(月表）
                    Map<String, Double> avgEMM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementAverage)));

                    //event_measurement的和
                    Map<String, Integer> sumEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventMeasurement)));

                    //event_count（天表）
                    Map<String, Integer> sumEC = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventCount)));

                    //event_count（月表）
                    Map<String, Integer> sumECM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.summingInt(RStatEventMPO::getEventCount)));

                    //event_measurement_ratio_average（月表）
                    Map<String, Double> avgEMRM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementRatioAverage)));


                    eventStatis.forEach(dictData -> {
                        if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                            return;
                        }
                        //累计发生暂态监测点数
                        Integer statisData = getStatisQData(dictData, rMpEventDetailMPOS);

                        RStatEventQPO rStatEventQPO = new RStatEventQPO();
                        rStatEventQPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventQPO.setDataDate(localDate);
                        rStatEventQPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                        rStatEventQPO.setEventType(dictData.getId());
                        rStatEventQPO.setEventMeasurementAverage(Float.parseFloat(df.format(avgEMM.get(dictData.getId()))));
                        // todo
                        rStatEventQPO.setEventMeasurementAccrued(statisData);
                        rStatEventQPO.setEventCount(sumECM.get(dictData.getId()));
                        rStatEventQPO.setEventMeasurementRatioAverage(Float.parseFloat(df.format(avgEMRM.get(dictData.getId()))));
                        rStatEventQPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventQPO.setEventFreq(1.00f);
                        } else {
                            String value = df.format(sumEC.get(dictData.getId()) / sumEM.get(dictData.getId()).floatValue());
                            rStatEventQPO.setEventFreq(Float.parseFloat(value));
                        }
                        if (Objects.isNull(rStatOrgQPO)) {
                            rStatEventQPO.setEventMeasurementRatioAccrued(1.00f);
                        } else {
                            if (rStatOrgQPO.getEffectiveMeasurementAccrued() == 0) {
                                rStatEventQPO.setEventMeasurementRatioAccrued(1.00f);
                            } else {
                                String value = df.format(statisData / rStatOrgQPO.getEffectiveMeasurementAccrued().floatValue());
                                rStatEventQPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
                            }
                        }
                        rStatEventQPOList.add(rStatEventQPO);
                    });
                });
            }

        });
        if (!CollectionUtils.isEmpty(rStatEventQPOList)) {
            rStatEventQPOService.saveOrUpdateBatchByMultiId(rStatEventQPOList, 500);
        }
    }

    //年表
    public void rStartEventYHandler(List<DeptGetChildrenMoreDTO> data, String dataDate, Integer type) {
        List<RStatEventYPO> rStatEventYPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00");
        Date date = DateUtil.parse(dataDate);
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取当前年的起始日期和结束日期
        LocalDate date1 = LocalDate.parse(dataDate, DateTimeFormatter.ISO_LOCAL_DATE);
        LocalDate startDate = date1.withDayOfYear(1);
        LocalDate endDate = date1.withDayOfYear(365).plusDays(1);
        /*获取暂态统计指标*/
        List<DictData> eventStatis = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();

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

        /*获取监测点类型类型*/
        List<DictData> lineSortList = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.LINE_SORT.getCode()).getData();
        Map<String, DictData> lineSortMap = lineSortList.stream().collect(Collectors.toMap(DictData::getCode, dictData -> dictData));

        //详情表
        QueryWrapper<RMpEventDetailMPO> rMpEventDetailMPOQueryWrapper = new QueryWrapper<>();
        //org年表
        QueryWrapper<RStatOrgYPO> rStatOrgYPOQueryWrapper = new QueryWrapper<>();
        //天表
        QueryWrapper<RStatEventDPO> rStatEventDPOQueryWrapper = new QueryWrapper<>();
        //月表
        QueryWrapper<RStatEventMPO> rStatEventMPOQueryWrapper = new QueryWrapper<>();

        data.forEach(deptGetChildrenMoreDTO -> {

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<Integer, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailMPOQueryWrapper.clear();
                    rMpEventDetailMPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            between("data_date", startDate, endDate);
                    List<RMpEventDetailMPO> rMpEventDetailMPOS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

                    //年表
                    rStatOrgYPOQueryWrapper.clear();
                    rStatOrgYPOQueryWrapper.select("effective_measurement_accrued").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId()).
                            between("data_date", startDate, endDate);

                    RStatOrgYPO rStatOrgYPO = rStatOrgYMapper.selectOne(rStatOrgYPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                    List<RStatEventDPO> rStatEventDPO = rStatEventDPOMapper.selectList(rStatEventDPOQueryWrapper);

                    //月表
                    rStatEventMPOQueryWrapper.clear();
                    rStatEventMPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());
                    List<RStatEventMPO> rStatEventMPO = rStatEventMPOMapper.selectList(rStatEventMPOQueryWrapper);

                    //求各个类型的平均值(月表）
                    Map<String, Double> avgEMM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementAverage)));

                    //event_measurement的和
                    Map<String, Integer> sumEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventMeasurement)));

                    //event_count（天表）
                    Map<String, Integer> sumEC = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventCount)));

                    //event_count（月表）
                    Map<String, Integer> sumECM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.summingInt(RStatEventMPO::getEventCount)));

                    //event_measurement_ratio_average（月表）
                    Map<String, Double> avgEMRM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementRatioAverage)));


                    eventStatis.forEach(dictData -> {
                        if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                            return;
                        }
                        //累计发生暂态监测点数
                        Integer statisData = getStatisQData(dictData, rMpEventDetailMPOS);

                        RStatEventYPO rStatEventYPO = new RStatEventYPO();
                        rStatEventYPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventYPO.setDataDate(localDate);
                        rStatEventYPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                        rStatEventYPO.setEventType(dictData.getId());
                        rStatEventYPO.setEventMeasurementAverage(Float.parseFloat(df.format(avgEMM.get(dictData.getId()))));
                        // todo
                        rStatEventYPO.setEventMeasurementAccrued(statisData);
                        rStatEventYPO.setEventCount(sumECM.get(dictData.getId()));
                        rStatEventYPO.setEventMeasurementRatioAverage(Float.parseFloat(df.format(avgEMRM.get(dictData.getId()))));
                        rStatEventYPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventYPO.setEventFreq(1.00f);
                        } else {
                            String value = df.format(sumEC.get(dictData.getId()) / sumEM.get(dictData.getId()).floatValue());
                            rStatEventYPO.setEventFreq(Float.parseFloat(value));
                        }
                        if (Objects.isNull(rStatOrgYPO)) {
                            rStatEventYPO.setEventMeasurementRatioAccrued(1.00f);
                        } else {
                            if (rStatOrgYPO.getEffectiveMeasurementAccrued() == 0) {
                                rStatEventYPO.setEventMeasurementRatioAccrued(1.00f);
                            } else {
                                String value = df.format(statisData / rStatOrgYPO.getEffectiveMeasurementAccrued().floatValue());
                                rStatEventYPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
                            }
                        }
                        rStatEventYPOList.add(rStatEventYPO);
                    });
                });
            }

            /*配网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getPwMonitorIds())) {
                List<LineDevGetDTO> pwMonitorIds = deptGetChildrenMoreDTO.getPwMonitorIds();
                Map<Integer, List<LineDevGetDTO>> collect = pwMonitorIds.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineType));
                collect.forEach((k, v) -> {
                    List<String> collect1 = v.stream().map(LineDevGetDTO::getPointId).collect(Collectors.toList());

                    rMpEventDetailMPOQueryWrapper.clear();
                    rMpEventDetailMPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            between("data_date", startDate, endDate);
                    List<RMpEventDetailMPO> rMpEventDetailMPOS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

                    //年表
                    rStatOrgYPOQueryWrapper.clear();
                    rStatOrgYPOQueryWrapper.select("effective_measurement_accrued").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId()).
                            between("data_date", startDate, endDate);

                    RStatOrgYPO rStatOrgYPO = rStatOrgYMapper.selectOne(rStatOrgYPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                    List<RStatEventDPO> rStatEventDPO = rStatEventDPOMapper.selectList(rStatEventDPOQueryWrapper);

                    //月表
                    rStatEventMPOQueryWrapper.clear();
                    rStatEventMPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", startDate, endDate).
                            eq("measurement_type_class", getmeasurementType(k, lineSortMap)).
                            eq("data_type", dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());
                    List<RStatEventMPO> rStatEventMPO = rStatEventMPOMapper.selectList(rStatEventMPOQueryWrapper);

                    //求各个类型的平均值(月表）
                    Map<String, Double> avgEMM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementAverage)));

                    //event_measurement的和
                    Map<String, Integer> sumEM = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventMeasurement)));

                    //event_count（天表）
                    Map<String, Integer> sumEC = rStatEventDPO.stream()
                            .collect(Collectors.groupingBy(RStatEventDPO::getEventType, Collectors.summingInt(RStatEventDPO::getEventCount)));

                    //event_count（月表）
                    Map<String, Integer> sumECM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.summingInt(RStatEventMPO::getEventCount)));

                    //event_measurement_ratio_average（月表）
                    Map<String, Double> avgEMRM = rStatEventMPO.stream()
                            .collect(Collectors.groupingBy(RStatEventMPO::getEventType, Collectors.averagingDouble(RStatEventMPO::getEventMeasurementRatioAverage)));


                    eventStatis.forEach(dictData -> {
                        if (Objects.equals(dictData.getCode(), DicDataEnum.DISTURBANCE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.OTHER.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.RECORDING_WAVE.getCode())
                                || Objects.equals(dictData.getCode(), DicDataEnum.TOTAL_INDICATORS.getCode())) {
                            return;
                        }
                        //累计发生暂态监测点数
                        Integer statisData = getStatisQData(dictData, rMpEventDetailMPOS);

                        RStatEventYPO rStatEventYPO = new RStatEventYPO();
                        rStatEventYPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventYPO.setDataDate(localDate);
                        rStatEventYPO.setMeasurementTypeClass(getmeasurementType(k, lineSortMap));
                        rStatEventYPO.setEventType(dictData.getId());
                        rStatEventYPO.setEventMeasurementAverage(Float.parseFloat(df.format(avgEMM.get(dictData.getId()))));
                        // todo
                        rStatEventYPO.setEventMeasurementAccrued(statisData);
                        rStatEventYPO.setEventCount(sumECM.get(dictData.getId()));
                        rStatEventYPO.setEventMeasurementRatioAverage(Float.parseFloat(df.format(avgEMRM.get(dictData.getId()))));
                        rStatEventYPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventYPO.setEventFreq(1.00f);
                        } else {
                            String value = df.format(sumEC.get(dictData.getId()) / sumEM.get(dictData.getId()).floatValue());
                            rStatEventYPO.setEventFreq(Float.parseFloat(value));
                        }
                        if (Objects.isNull(rStatOrgYPO)) {
                            rStatEventYPO.setEventMeasurementRatioAccrued(1.00f);
                        } else {
                            if (rStatOrgYPO.getEffectiveMeasurementAccrued() == 0) {
                                rStatEventYPO.setEventMeasurementRatioAccrued(1.00f);
                            } else {
                                String value = df.format(statisData / rStatOrgYPO.getEffectiveMeasurementAccrued().floatValue());
                                rStatEventYPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
                            }
                        }
                        rStatEventYPOList.add(rStatEventYPO);
                    });
                });
            }

        });
        if (!CollectionUtils.isEmpty(rStatEventYPOList)) {
            rStatEventYPOService.saveOrUpdateBatchByMultiId(rStatEventYPOList, 500);
        }
    }

    //获取监测点类型 1/2/3类字典id
    private String getmeasurementType(Integer k, Map<String, DictData> lineSortMap) {
        String value = "";
        switch (k) {
            case 1:
                value = lineSortMap.get(DicDataEnum.ONE_LINE.getCode()).getId();
                break;
            case 2:
                value = lineSortMap.get(DicDataEnum.TWO_LINE.getCode()).getId();
                break;
            case 3:
                value = lineSortMap.get(DicDataEnum.THREE_LINE.getCode()).getId();
                break;
            default:
                break;
        }
        return value;
    }

    //获取暂态各个类型发生的监测点数量及发生次数
    private List<Integer> getTransientStatisData(DictData dictData, List<RMpEventDetailDPO> list) {
        List<Integer> result = new ArrayList<>(2);
        Integer value = 0;
        Integer count = 0;
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_DIP.getCode())) {
            value = Integer.valueOf(list.stream().filter(temp -> temp.getSagTimes() > 0).count() + "");
            count = Integer.valueOf(list.stream().mapToInt(RMpEventDetailDPO::getSagTimes).sum() + "");
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_RISE.getCode())) {
            value = Integer.valueOf(list.stream().filter(temp -> temp.getSwellTimes() > 0).count() + "");
            count = Integer.valueOf(list.stream().mapToInt(RMpEventDetailDPO::getSwellTimes).sum() + "");
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.SHORT_INTERRUPTIONS.getCode())) {
            value = Integer.valueOf(list.stream().filter(temp -> temp.getInterruptTimes() > 0).count() + "");
            count = Integer.valueOf(list.stream().mapToInt(RMpEventDetailDPO::getInterruptTimes).sum() + "");
        }
        result.add(value);
        result.add(count);
        return result;

    }

    //获取暂态各个类型发生的监测点数量
    private Integer getStatisData(DictData dictData, List<RMpEventDetailMPO> list) {
        Integer value = 0;
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_DIP.getCode())) {
            value = Integer.valueOf(list.stream().filter(temp -> temp.getSagTimes() > 0).count() + "");
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_RISE.getCode())) {
            value = Integer.valueOf(list.stream().filter(temp -> temp.getSwellTimes() > 0).count() + "");
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.SHORT_INTERRUPTIONS.getCode())) {
            value = Integer.valueOf(list.stream().filter(temp -> temp.getInterruptTimes() > 0).count() + "");
        }

        return value;

    }

    //季表（月表相同id去重）
    private Integer getStatisQData(DictData dictData, List<RMpEventDetailMPO> list) {
        Integer value = 0;
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_DIP.getCode())) {
            Map<String, RMpEventDetailMPO> idToObjectMap = list.stream()
                    .filter(obj -> obj.getSagTimes() > 0) // 筛选count大于0的对象
                    .collect(Collectors.toMap(RMpEventDetailMPO::getMeasurementPointId, Function.identity(),
                            (existing, replacement) -> existing.getSagTimes() > 0 ? existing : replacement)); // 对id去重，仅保留计数大于0的对象
            for (RMpEventDetailMPO obj : idToObjectMap.values()) {
                value += (obj.getSagTimes() > 0 ? 1 : 0);
            }
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_RISE.getCode())) {
            Map<String, RMpEventDetailMPO> idToObjectMap = list.stream()
                    .filter(obj -> obj.getSwellTimes() > 0) // 筛选count大于0的对象
                    .collect(Collectors.toMap(RMpEventDetailMPO::getMeasurementPointId, Function.identity(),
                            (existing, replacement) -> existing.getSwellTimes() > 0 ? existing : replacement)); // 对id去重，仅保留计数大于0的对象
            for (RMpEventDetailMPO obj : idToObjectMap.values()) {
                value += (obj.getSwellTimes() > 0 ? 1 : 0);
            }
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.SHORT_INTERRUPTIONS.getCode())) {
            Map<String, RMpEventDetailMPO> idToObjectMap = list.stream()
                    .filter(obj -> obj.getInterruptTimes() > 0) // 筛选count大于0的对象
                    .collect(Collectors.toMap(RMpEventDetailMPO::getMeasurementPointId, Function.identity(),
                            (existing, replacement) -> existing.getInterruptTimes() > 0 ? existing : replacement)); // 对id去重，仅保留计数大于0的对象
            for (RMpEventDetailMPO obj : idToObjectMap.values()) {
                value += (obj.getInterruptTimes() > 0 ? 1 : 0);
            }
        }

        return value;

    }
}
