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.event.pojo.po.RMpEventDetailD;
import com.njcn.event.pojo.po.RMpEventDetailM;
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.bo.CalculatedParam;
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.RStatEventDPO;
import com.njcn.prepare.harmonic.pojo.po.RStatEventMPO;
import com.njcn.prepare.harmonic.pojo.po.RStatEventQPO;
import com.njcn.prepare.harmonic.pojo.po.RStatEventYPO;
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.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 handleDay(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<RStatEventDPO> rStatEventDPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00000");
        LocalDate localDate = LocalDateTimeUtil.parseDate(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN);


        /*获取暂态统计指标*/
        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<RMpEventDetailD> rMpEventDetailDPOQueryWrapper = new QueryWrapper<>();
        QueryWrapper<RStatOrgDPO> rStatOrgDPOQueryWrapper = new QueryWrapper<>();

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

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

                    rMpEventDetailDPOQueryWrapper.clear();
                    rMpEventDetailDPOQueryWrapper.
                            in("measurement_point_id", collect1).
                            eq("data_date",localDate);
                    List<RMpEventDetailD> rMpEventDetailDS = rMpEventDetailDMapper.selectList(rMpEventDetailDPOQueryWrapper);

                    rStatOrgDPOQueryWrapper.clear();
                    rStatOrgDPOQueryWrapper.select("effective_measurement").
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            eq("measurement_type_class", k).
                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId()).
                            eq("data_date",localDate);
                    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, rMpEventDetailDS);
                                RStatEventDPO rStatEventDPO = new RStatEventDPO();
                                rStatEventDPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                                rStatEventDPO.setDataDate(localDate);
                                rStatEventDPO.setMeasurementTypeClass(k);
                                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(0.00f);
//                                } else {
//                                    if (rStatOrgDPO.getEffectiveMeasurement() == 0) {
//                                        rStatEventDPO.setEventMeasurementRatio(0.00f);
//                                    } else {
                                        String value = df.format(Double.valueOf(rStatEventDPO.getEventMeasurement()) / collect1.size());
                                        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("data_date",localDate);
                    List<RMpEventDetailD> rMpEventDetailDS = 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("data_date",localDate);
                    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, rMpEventDetailDS);
                                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(0.00f);
//                                } else {
//                                    if (rStatOrgDPO.getEffectiveMeasurement() == 0) {
//                                        rStatEventDPO.setEventMeasurementRatio(0.00f);
//                                    } else {
                                        String value = df.format(Double.valueOf(rStatEventDPO.getEventMeasurement()) / collect1.size());
                                        rStatEventDPO.setEventMeasurementRatio(Float.parseFloat(value));
//                                    }
//                                }
                                rStatEventDPOList.add(rStatEventDPO);
                            }
                    );
                });
            }

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

    @Override
    public void handleMonth(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<RStatEventMPO> rStatEventMPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00000");

        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> 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<RMpEventDetailM> rMpEventDetailMPOQueryWrapper = new QueryWrapper<>();
        //org表
        QueryWrapper<RStatOrgMPO> rStatOrgMPOQueryWrapper = new QueryWrapper<>();
        //天表
        QueryWrapper<RStatEventDPO> rStatEventDPOQueryWrapper = new QueryWrapper<>();

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

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<String, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineTag));
                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",begin,end);
                    List<RMpEventDetailM> rMpEventDetailMS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

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

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date",begin,end).
                            eq("measurement_type_class",k).
                            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.averagingDouble(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, rMpEventDetailMS);
                        if(statisData>0){
                            System.out.println("1");
                        }

                        RStatEventMPO rStatEventMPO = new RStatEventMPO();
                        rStatEventMPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventMPO.setDataDate(localDate);
                        rStatEventMPO.setMeasurementTypeClass(k);
                        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())*100)));
                        rStatEventMPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventMPO.setEventFreq(0.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(0.00f);
//                        } else {
//                            if (rStatOrgMPO.getEffectiveMeasurementAccrued() == 0) {
//                                rStatEventMPO.setEventMeasurementRatioAccrued(0.00f);
//                            } else {
                                String value = df.format(Double.valueOf(statisData) / collect1.size());
                                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).
                            between("data_date",begin,end);
                    List<RMpEventDetailM> rMpEventDetailMS = 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()).
                            between("data_date",begin,end);
                    RStatOrgMPO rStatOrgMPO = rStatOrgMMapper.selectOne(rStatOrgMPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date",begin,end).
                            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.averagingDouble(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, rMpEventDetailMS);

                        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())*100)));
                        rStatEventMPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventMPO.setEventFreq(0.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(0.00f);
//                        } else {
//                            if (rStatOrgMPO.getEffectiveMeasurementAccrued() == 0) {
//                                rStatEventMPO.setEventMeasurementRatioAccrued(0.00f);
//                            } else {
                                String value = df.format(Double.valueOf(statisData) / collect1.size());
                                rStatEventMPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
//                            }
//                        }
                        rStatEventMPOList.add(rStatEventMPO);
                    });
                });
            }

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

    @Override
    public void handleQtr(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<RStatEventQPO> rStatEventQPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00000");

        DateTime begin = DateUtil.beginOfQuarter(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfQuarter(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> 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<RMpEventDetailM> rMpEventDetailMPOQueryWrapper = new QueryWrapper<>();
        //org季表
        QueryWrapper<RStatOrgQPO> rStatOrgQPOQueryWrapper = new QueryWrapper<>();
        //天表
        QueryWrapper<RStatEventDPO> rStatEventDPOQueryWrapper = new QueryWrapper<>();
        //月表
        QueryWrapper<RStatEventMPO> rStatEventMPOQueryWrapper = new QueryWrapper<>();

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

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<String, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineTag));
                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", begin, end);
                    List<RMpEventDetailM> rMpEventDetailMS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

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

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", begin, end).
                            eq("measurement_type_class", k).
                            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", begin, end).
                            eq("measurement_type_class", k).
                            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, rMpEventDetailMS);

                        RStatEventQPO rStatEventQPO = new RStatEventQPO();
                        rStatEventQPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventQPO.setDataDate(localDate);
                        rStatEventQPO.setMeasurementTypeClass(k);
                        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())*100)));
                        rStatEventQPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventQPO.setEventFreq(0.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(0.00f);
//                        } else {
//                            if (rStatOrgQPO.getEffectiveMeasurementAccrued() == 0) {
//                                rStatEventQPO.setEventMeasurementRatioAccrued(0.00f);
//                            } else {
                                String value = df.format(Double.valueOf(statisData) / collect1.size());
                                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", begin, end);
                    List<RMpEventDetailM> rMpEventDetailMS = 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", begin, end);
                    ;
                    RStatOrgQPO rStatOrgQPO = rStatOrgQMapper.selectOne(rStatOrgQPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", begin, end).
                            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", begin, end).
                            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, rMpEventDetailMS);

                        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())*100)));
                        rStatEventQPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventQPO.setEventFreq(0.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(0.00f);
//                        } else {
//                            if (rStatOrgQPO.getEffectiveMeasurementAccrued() == 0) {
//                                rStatEventQPO.setEventMeasurementRatioAccrued(0.00f);
//                            } else {
                                String value = df.format(Double.valueOf(statisData) / collect1.size());
                                rStatEventQPO.setEventMeasurementRatioAccrued(Float.parseFloat(value));
//                            }
//                        }
                        rStatEventQPOList.add(rStatEventQPO);
                    });
                });
            }

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

    }

    @Override
    public void handleYear(CalculatedParam<DeptGetChildrenMoreDTO> calculatedParam) {
        List<RStatEventYPO> rStatEventYPOList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00000");

        DateTime begin = DateUtil.beginOfYear(DateUtil.parse(calculatedParam.getDataDate(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfYear(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> 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<RMpEventDetailM> rMpEventDetailMPOQueryWrapper = new QueryWrapper<>();
        //org年表
        QueryWrapper<RStatOrgYPO> rStatOrgYPOQueryWrapper = new QueryWrapper<>();
        //天表
        QueryWrapper<RStatEventDPO> rStatEventDPOQueryWrapper = new QueryWrapper<>();
        //月表
        QueryWrapper<RStatEventMPO> rStatEventMPOQueryWrapper = new QueryWrapper<>();

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

            /*主网*/
            if (!CollectionUtils.isEmpty(deptGetChildrenMoreDTO.getLineBaseList())) {
                List<LineDevGetDTO> lineBaseList = deptGetChildrenMoreDTO.getLineBaseList();
                Map<String, List<LineDevGetDTO>> collect = lineBaseList.stream().collect(Collectors.groupingBy(LineDevGetDTO::getLineTag));
                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", begin, end);
                    List<RMpEventDetailM> rMpEventDetailMS = rMpEventDetailMMapper.selectList(rMpEventDetailMPOQueryWrapper);

//                    //年表
//                    rStatOrgYPOQueryWrapper.clear();
//                    rStatOrgYPOQueryWrapper.select("effective_measurement_accrued").
//                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
//                            eq("measurement_type_class", k).
//                            eq("data_type", dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId()).
//                            between("data_date", begin, end);
//
//                    RStatOrgYPO rStatOrgYPO = rStatOrgYMapper.selectOne(rStatOrgYPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", begin, end).
                            eq("measurement_type_class",k).
                            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", begin, end).
                            eq("measurement_type_class",k).
                            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, rMpEventDetailMS);

                        RStatEventYPO rStatEventYPO = new RStatEventYPO();
                        rStatEventYPO.setOrgNo(deptGetChildrenMoreDTO.getUnitId());
                        rStatEventYPO.setDataDate(localDate);
                        rStatEventYPO.setMeasurementTypeClass(k);
                        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())*100)));
                        rStatEventYPO.setDataType(dataTypeMap.get(DicDataEnum.MAINNET_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventYPO.setEventFreq(0.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(0.00f);
//                        } else {
//                            if (rStatOrgYPO.getEffectiveMeasurementAccrued() == 0) {
//                                rStatEventYPO.setEventMeasurementRatioAccrued(0.00f);
//                            } else {
                                String value = df.format(Double.valueOf(statisData) / collect1.size());
                                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", begin, end);
                    List<RMpEventDetailM> rMpEventDetailMS = 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", begin, end);

                    RStatOrgYPO rStatOrgYPO = rStatOrgYMapper.selectOne(rStatOrgYPOQueryWrapper);

                    //天表
                    rStatEventDPOQueryWrapper.clear();
                    rStatEventDPOQueryWrapper.
                            eq("org_no", deptGetChildrenMoreDTO.getUnitId()).
                            between("data_date", begin, end).
                            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", begin, end).
                            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, rMpEventDetailMS);

                        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())*100)));
                        rStatEventYPO.setDataType(dataTypeMap.get(DicDataEnum.DISTRIBUTION_POINT.getCode()).getId());

                        if (sumEM.get(dictData.getId()) == 0) {
                            rStatEventYPO.setEventFreq(0.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(0.00f);
//                        } else {
//                            if (rStatOrgYPO.getEffectiveMeasurementAccrued() == 0) {
//                                rStatEventYPO.setEventMeasurementRatioAccrued(0.00f);
//                            } else {
                                String value = df.format(Double.valueOf(statisData) / collect1.size());
                                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<RMpEventDetailD> 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(RMpEventDetailD::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(RMpEventDetailD::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(RMpEventDetailD::getInterruptTimes).sum() + "");
        }
        result.add(value);
        result.add(count);
        return result;

    }

    //获取暂态各个类型发生的监测点数量
    private Integer getStatisData(DictData dictData, List<RMpEventDetailM> 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<RMpEventDetailM> list) {
        Integer value = 0;
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_DIP.getCode())) {
            Map<String, RMpEventDetailM> idToObjectMap = list.stream()
                    .filter(obj -> obj.getSagTimes() > 0) // 筛选count大于0的对象
                    .collect(Collectors.toMap(RMpEventDetailM::getMeasurementPointId, Function.identity(),
                            (existing, replacement) -> existing.getSagTimes() > 0 ? existing : replacement)); // 对id去重，仅保留计数大于0的对象
            for (RMpEventDetailM obj : idToObjectMap.values()) {
                value += (obj.getSagTimes() > 0 ? 1 : 0);
            }
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.VOLTAGE_RISE.getCode())) {
            Map<String, RMpEventDetailM> idToObjectMap = list.stream()
                    .filter(obj -> obj.getSwellTimes() > 0) // 筛选count大于0的对象
                    .collect(Collectors.toMap(RMpEventDetailM::getMeasurementPointId, Function.identity(),
                            (existing, replacement) -> existing.getSwellTimes() > 0 ? existing : replacement)); // 对id去重，仅保留计数大于0的对象
            for (RMpEventDetailM obj : idToObjectMap.values()) {
                value += (obj.getSwellTimes() > 0 ? 1 : 0);
            }
        }
        if (Objects.equals(dictData.getCode(), DicDataEnum.SHORT_INTERRUPTIONS.getCode())) {
            Map<String, RMpEventDetailM> idToObjectMap = list.stream()
                    .filter(obj -> obj.getInterruptTimes() > 0) // 筛选count大于0的对象
                    .collect(Collectors.toMap(RMpEventDetailM::getMeasurementPointId, Function.identity(),
                            (existing, replacement) -> existing.getInterruptTimes() > 0 ? existing : replacement)); // 对id去重，仅保留计数大于0的对象
            for (RMpEventDetailM obj : idToObjectMap.values()) {
                value += (obj.getInterruptTimes() > 0 ? 1 : 0);
            }
        }

        return value;

    }
}
