package com.njcn.prepare.harmonic.service.mysql.Impl.area;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.pms.pojo.po.Monitor;
import com.njcn.harmonic.pojo.po.*;
import com.njcn.prepare.harmonic.constant.AlgorithmParam;
import com.njcn.prepare.harmonic.constant.PqsPrepareExceptionEnum;
import com.njcn.prepare.harmonic.mapper.mysql.area.RStatAbnormalDPOMapper;
import com.njcn.prepare.harmonic.pojo.dto.MonitorDataIntegrityDTO;
import com.njcn.prepare.harmonic.pojo.oracle.PqLinedetailPO;
import com.njcn.prepare.harmonic.pojo.param.PrimaryGridDataIntegrityParam;
import com.njcn.prepare.harmonic.pojo.param.PrimaryGridParam;
import com.njcn.prepare.harmonic.service.influxdb.DataVInfluxdbService;
import com.njcn.prepare.harmonic.service.mysql.area.*;
import com.njcn.prepare.harmonic.service.oracle.DataVOraclePOService;
import com.njcn.prepare.harmonic.service.oracle.PqLinedetailPOService;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.njcn.system.pojo.constant.DicDataConstant.NAME_KEY;
import static com.njcn.system.pojo.constant.DicDataConstant.SPLIT_SIGN;

/**
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2022/11/25  8:54【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class PrimaryGridDataServiceImpl implements PrimaryGridDataService {

    private final PmsMonitorPOService pmsMonitorPOService;

    private final PmsTerminalPOService pmsTerminalPOService;

    private final DataVInfluxdbService dataVInfluxdbService;

    private final PqLinedetailPOService pqLinedetailPOService;

    private final DataVOraclePOService dataVOraclePOService;

    private final RMpIntegrityDPOService rMpIntegrityDPOService;

    private final RStatAbnormalDPOMapper rStatAbnormalDPOMapper;

    private final  ROperatingIndexDPOService rOperatingIndexDPOService;

    private final ROperatingIndexMPOService rOperatingIndexMPOService;

    private final ROperatingIndexQPOService rOperatingIndexQPOService;

    private final ROperatingIndexYPOService rOperatingIndexYPOService;

    private final RMpDevEvaluateDetailPOService rMpDevEvaluateDetailPOService;

    private final RedisUtil redisUtil;

    private final CommTerminalGeneralClient commTerminalGeneralClient;



    /**
     * @param primaryGridParam
     * @Description: primaryGridDataHanlder
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    @Override
    @Async("asyncExecutor")
    public void primaryGridDataHanlder(PrimaryGridParam primaryGridParam) {
        if (Objects.equals(primaryGridParam.getDataSource(), AlgorithmParam.ORACLE_DATA)) {
            hanlderOracleData(primaryGridParam);
        } else if (Objects.equals(primaryGridParam.getDataSource(), AlgorithmParam.INFLUX_DATA)) {
            hanlderInfludxbData(primaryGridParam);
        }

    }

    /**
     * @param primaryGridDataIntegrityParam
     * @Description: 主网终端数据完整率月统计只做月统计，且重mysql查数据不分数据源
     * @Param: [primaryGridDataIntegrityParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/30
     */
    @Override
    @Async
    @SneakyThrows
    public void primaryGridDataIntegrityHanlder(PrimaryGridDataIntegrityParam primaryGridDataIntegrityParam) {
        List<String> deviceIds = primaryGridDataIntegrityParam.getDeviceId();
        String dataDate = primaryGridDataIntegrityParam.getDataDate();
        List<RMpDevEvaluateDetailPO> rMpDevEvaluateDetailPOList = new ArrayList<>();
        deviceIds.forEach(deviceId -> {
            double dev_data_rate = 0.00;
            /*获取终端下的监测点集合*/
            QueryWrapper<Monitor> queryWrapper = new QueryWrapper<>();
            String state = redisUtil.getStringByKey(NAME_KEY +
                    SPLIT_SIGN + DicDataTypeEnum.LINE_STATE.getCode() +
                    SPLIT_SIGN + DicDataEnum.RUN.getCode());
            if (StringUtils.isEmpty(state)) {
                throw new BusinessException(PqsPrepareExceptionEnum.REDIS_NULL_EXCEPTION);
            }
            queryWrapper.lambda().eq(Monitor::getTerminalId, deviceId).
                    eq(Monitor::getMonitorState, state);
            List<Monitor> list = pmsMonitorPOService.list(queryWrapper);
            List<String> mysqlIndexList = list.stream().map(Monitor::getId).collect(Collectors.toList());
            /*获取检测点的月平均数据完整率*/
            List<MonitorDataIntegrityDTO> monitorDataIntegrityDTOList = rMpIntegrityDPOService.calculateMouthDataIntegrity(mysqlIndexList, dataDate);
            /*求平均值*/
            if (!CollectionUtils.isEmpty(monitorDataIntegrityDTOList)) {
                dev_data_rate = monitorDataIntegrityDTOList.stream().mapToDouble(monitorDataIntegrityDTO -> {
                    return monitorDataIntegrityDTO.getDataIntegrity().doubleValue();
                }).average().getAsDouble();
            }
            RMpDevEvaluateDetailPO rMpDevEvaluateDetailPO = new RMpDevEvaluateDetailPO();
            rMpDevEvaluateDetailPO.setDeviceId(deviceId);
            rMpDevEvaluateDetailPO.setDataDate(LocalDateTimeUtil.parseDate(dataDate, DatePattern.NORM_DATE_FORMATTER));
            rMpDevEvaluateDetailPO.setDevDataRate(dev_data_rate);
            rMpDevEvaluateDetailPOList.add(rMpDevEvaluateDetailPO);
        });
        rMpDevEvaluateDetailPOService.saveOrUpdateBatchByMultiId(rMpDevEvaluateDetailPOList, 500);
    }

    /**
     * @Description: 处理influxdb数据 todo 本次不做处理
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    private void hanlderInfludxbData(PrimaryGridParam primaryGridParam) {
        Integer type = primaryGridParam.getType();
        /*月表，季表，年表都是重日表生成，不区分oralce，influxdb*/
        switch (type) {
            case 1:
                this.hanlderOracleYear(primaryGridParam);
                break;
            case 2:
                this.hanlderOracleQtr(primaryGridParam);
                break;
            case 3:
                this.hanlderOracleMonth(primaryGridParam);
                break;
            case 5:
                this.hanlderInfluxdbDay(primaryGridParam);
                break;
            default:
                break;
        }
    }

    @SneakyThrows
    private void hanlderInfluxdbDay(PrimaryGridParam primaryGridParam) {
        List<String> orgIdList = primaryGridParam.getOrgIdList();
        String dataDate = primaryGridParam.getDataDate();
        List<ROperatingIndexDPO> rOperatingIndexDPOList = new ArrayList<>();

        final Date tempDate = new SimpleDateFormat("yyyy-MM-dd").parse(dataDate);
        orgIdList.forEach(orgid -> {

            /*measurement_run_points:在运监测点个数*/
            //获取终端信息，和包含的终端下监测点
            List<LineDevGetDTO> runTerminalAndLine = pmsTerminalPOService.getRunTerminalAndLine(orgid);
            //终端数量
            Integer online_measurement_points = runTerminalAndLine.size();
            /*在运监测终端个数 online_measurement_count*/
            Long online_measurement_count = runTerminalAndLine.stream().filter(x -> x.getComFlag() == 1).collect(Collectors.counting());

            /*监测终端数量 online_measurement_points*/
            List<String> runMonitor = runTerminalAndLine.stream().flatMap(x -> x.getMonitorIds().stream()).collect(Collectors.toList());

//            List<String> runMonitor = pmsMonitorPOService.getRunMonitor(orgid);
            Integer measurement_run_points = runMonitor.size();


            /*主网单位在线监测点数 transit_measurement_points*/
            Integer transit_measurement_points = dataVInfluxdbService.queryTransitMeasurementPoints(runMonitor, primaryGridParam.getDataDate(), "A");

            /*主网单位有效接入监测点个数 effective_access_measurement_count*/
            Integer effective_access_measurement_count = this.queryEffectiveAccessMeasurementCount(runMonitor, primaryGridParam.getDataDate());
//            List<PmsTerminalPO> pmsTerminalPOS = pmsTerminalPOService.queryOnlineMeasurementPoints(orgid);

            /*主网单位数据完整率 data_integrity_rate*/
            double data_integrity_rate = 0.00;
            List<MonitorDataIntegrityDTO> monitorDataIntegrityDTOList = rMpIntegrityDPOService.calculateDataIntegrity(runMonitor, dataDate);
            /*求平均值*/
            if (!CollectionUtils.isEmpty(monitorDataIntegrityDTOList)) {
                data_integrity_rate = monitorDataIntegrityDTOList.stream().mapToDouble(temp -> {
                    return temp.getDataIntegrity().doubleValue();
                }).average().getAsDouble();
            }

            /*主网单位数据异常监测点数日统计 is_unusual*/
            Integer is_unusual = this.queryIsUnusualCount(runMonitor, primaryGridParam.getDataDate());

            ROperatingIndexDPO rOperatingIndexDPO = new ROperatingIndexDPO();
            rOperatingIndexDPO.setOrgNo(orgid);

            rOperatingIndexDPO.setDataDate(LocalDate.parse(primaryGridParam.getDataDate()));
            rOperatingIndexDPO.setMeasurementRunPoints(measurement_run_points);
            rOperatingIndexDPO.setTransitMeasurementPoints(transit_measurement_points);
            rOperatingIndexDPO.setEffectiveAccessMeasurementCount(effective_access_measurement_count);
            rOperatingIndexDPO.setOnlineMeasurementPoints(online_measurement_points);
            rOperatingIndexDPO.setOnlineMeasurementCount(Math.toIntExact(online_measurement_count));
            rOperatingIndexDPO.setDataIntegrityRate(data_integrity_rate);
            rOperatingIndexDPO.setIsUnusual(is_unusual > 0 ? 1 : 0);
            rOperatingIndexDPOList.add(rOperatingIndexDPO);
        });
        if (!CollectionUtils.isEmpty(rOperatingIndexDPOList)) {
            rOperatingIndexDPOService.saveOrUpdateBatchByMultiId(rOperatingIndexDPOList, 30);
        }
    }


    /**
     * @Description: 处理Oracle数据
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    private void hanlderOracleData(PrimaryGridParam primaryGridParam) {
        Integer type = primaryGridParam.getType();
        switch (type) {
            case 1:
                this.hanlderOracleYear(primaryGridParam);
                break;
            case 2:
                this.hanlderOracleQtr(primaryGridParam);
                break;
            case 3:
                this.hanlderOracleMonth(primaryGridParam);
                break;
            case 5:
                this.hanlderOracleDay(primaryGridParam);
                break;
            default:
                break;
        }


    }

    /**
     * @Description: hanlderOracleMonth
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    @SneakyThrows
    private void hanlderOracleMonth(PrimaryGridParam primaryGridParam) {

        List<String> orgIdList = primaryGridParam.getOrgIdList();
        String beginTime = primaryGridParam.getBeginTime();
        String endTime = primaryGridParam.getEndTime();
        List<ROperatingIndexMPO> rOperatingIndexMPOList = new ArrayList<>();

        orgIdList.forEach(orgid -> {
            /*查询day表数据生成月表数据*/
            List<ROperatingIndexDPO> list = rOperatingIndexDPOService.queryOneMothData(orgid, beginTime,endTime);
            /*求平均值*/
            int measurement_run_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getMeasurementRunPoints()).
                    average().
                    getAsDouble());
            int transit_measurement_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getTransitMeasurementPoints()).
                    average().
                    getAsDouble());
            int effective_access_measurement_count = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getEffectiveAccessMeasurementCount()).
                    average().
                    getAsDouble());
            int online_measurement_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getOnlineMeasurementPoints()).
                    average().
                    getAsDouble());

            int online_measurement_count = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getOnlineMeasurementCount()).
                    average().
                    getAsDouble());
            /*double保留2位小数*/
            Double data_integrity_rate = Math.round(list.stream().
                    mapToDouble(temp -> temp.getDataIntegrityRate()).
                    average().
                    getAsDouble() * 100) * 0.01;
            /*看day表is_unusual时候存在1存在返回1，数据否异常(0:正常 1:异常)*/
            Integer is_unusual = list.stream().
                    map(ROperatingIndexDPO::getIsUnusual).
                    collect(Collectors.toList())
                    .contains(1) ? 1 : 0;


            ROperatingIndexMPO rOperatingIndexMPO = new ROperatingIndexMPO();
            rOperatingIndexMPO.setOrgNo(orgid);
            rOperatingIndexMPO.setDataDate(LocalDate.parse(primaryGridParam.getDataDate()));
            rOperatingIndexMPO.setMeasurementRunPoints(measurement_run_points);
            rOperatingIndexMPO.setTransitMeasurementPoints(transit_measurement_points);
            rOperatingIndexMPO.setEffectiveAccessMeasurementCount(effective_access_measurement_count);
            rOperatingIndexMPO.setOnlineMeasurementPoints(online_measurement_points);
            rOperatingIndexMPO.setOnlineMeasurementCount(online_measurement_count);
            rOperatingIndexMPO.setDataIntegrityRate(data_integrity_rate);
            rOperatingIndexMPO.setIsUnusual(is_unusual);
            rOperatingIndexMPOList.add(rOperatingIndexMPO);
        });
        if (!CollectionUtils.isEmpty(rOperatingIndexMPOList)) {
            rOperatingIndexMPOService.saveOrUpdateBatchByMultiId(rOperatingIndexMPOList, 30);
        }
    }

    /**
     * @Description: hanlderOracleDay
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    @SneakyThrows
    private void hanlderOracleDay(PrimaryGridParam primaryGridParam) {
        List<String> orgIdList = primaryGridParam.getOrgIdList();
        String dataDate = primaryGridParam.getDataDate();
        List<ROperatingIndexDPO> rOperatingIndexDPOList = new ArrayList<>();

        final Date tempDate = new SimpleDateFormat("yyyy-MM-dd").parse(dataDate);

        orgIdList.forEach(orgid -> {

            /*measurement_run_points:在运监测点个数*/
            List<Monitor> pmsMonitorPOS = pmsMonitorPOService.qurymeasurementRunPoints(orgid);
            Integer measurement_run_points = pmsMonitorPOS.size();
            /*获取mysql与Oracle监测点id对应关系*/
            List<String> mysqlIndexList = pmsMonitorPOS.stream().map(Monitor::getId).collect(Collectors.toList());

            List<PqLinedetailPO> pqLinedetailPOS = pqLinedetailPOService.queryOracleIndexIdByMysqlIndexId(mysqlIndexList);
            List<Integer> oracleIndexlist = pqLinedetailPOS.stream().map(PqLinedetailPO::getLineIndex).collect(Collectors.toList());

            /*主网单位在线监测点数 transit_measurement_points*/
            Integer transit_measurement_points = dataVOraclePOService.queryTransitMeasurementPoints(oracleIndexlist, primaryGridParam.getDataDate());

            /*主网单位有效接入监测点个数 effective_access_measurement_count*/
            Integer effective_access_measurement_count = this.queryEffectiveAccessMeasurementCount(mysqlIndexList, primaryGridParam.getDataDate());

            /*监测终端数量 online_measurement_points*/
            List<PmsTerminalPO> pmsTerminalPOS = pmsTerminalPOService.queryOnlineMeasurementPoints(orgid);
            Integer online_measurement_points = pmsTerminalPOS.size();

            /*在运监测终端个数 online_measurement_count*/
            String state = redisUtil.getStringByKey(NAME_KEY +
                    SPLIT_SIGN + DicDataTypeEnum.DEV_STATUS.getCode() +
                    SPLIT_SIGN + DicDataEnum.RUNNING.getCode());
            Integer online_measurement_count = Integer.valueOf(pmsTerminalPOS.stream().filter(temp -> Objects.equals(temp.getTerminalState(), state)).count() + "");

            /*主网单位数据完整率 data_integrity_rate*/
            double data_integrity_rate = 0.00;
            List<MonitorDataIntegrityDTO> monitorDataIntegrityDTOList = rMpIntegrityDPOService.calculateDataIntegrity(mysqlIndexList, dataDate);
            /*求平均值*/
            if (!CollectionUtils.isEmpty(monitorDataIntegrityDTOList)) {
                data_integrity_rate = monitorDataIntegrityDTOList.stream().mapToDouble(temp -> {
                    return temp.getDataIntegrity().doubleValue();
                }).average().getAsDouble();
            }


            /*主网单位数据异常监测点数日统计 is_unusual*/
            Integer is_unusual = this.queryIsUnusualCount(mysqlIndexList, primaryGridParam.getDataDate());

            ROperatingIndexDPO rOperatingIndexDPO = new ROperatingIndexDPO();
            rOperatingIndexDPO.setOrgNo(orgid);
            rOperatingIndexDPO.setDataDate(LocalDate.parse(primaryGridParam.getDataDate()));
            rOperatingIndexDPO.setMeasurementRunPoints(measurement_run_points);
            rOperatingIndexDPO.setTransitMeasurementPoints(transit_measurement_points);
            rOperatingIndexDPO.setEffectiveAccessMeasurementCount(effective_access_measurement_count);
            rOperatingIndexDPO.setOnlineMeasurementPoints(online_measurement_points);
            rOperatingIndexDPO.setOnlineMeasurementCount(online_measurement_count);
            rOperatingIndexDPO.setDataIntegrityRate(data_integrity_rate);
            rOperatingIndexDPO.setIsUnusual(is_unusual > 0 ? 1 : 0);
            rOperatingIndexDPOList.add(rOperatingIndexDPO);
        });
        if (!CollectionUtils.isEmpty(rOperatingIndexDPOList)) {
            rOperatingIndexDPOService.saveOrUpdateBatchByMultiId(rOperatingIndexDPOList, 30);
        }

    }

    /**
     * @Description: queryIsUnusualCount :用监测点id在r_stat_abnormal_d表中查找value_alarm为0的监测点个数
     * @Param: [mysqlIndexList, dataDate]
     * @return: java.lang.Integer
     * @Author: clam
     * @Date: 2022/11/28
     */
    private Integer queryIsUnusualCount(List<String> mysqlIndexList, String dataDate) {

        if (CollectionUtils.isEmpty(mysqlIndexList)) {
            return 0;
        }

        QueryWrapper<RStatAbnormalDPO> rStatAbnormalDPOLambdaQueryWrapper = new QueryWrapper();
        rStatAbnormalDPOLambdaQueryWrapper.
                in("measurement_point_id", mysqlIndexList).
                eq("value_alarm", 0).
                eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", dataDate);
        Integer integer = rStatAbnormalDPOMapper.selectCount(rStatAbnormalDPOLambdaQueryWrapper);

        return integer;
    }


    /**
     * @Description: 主网单位有效接入监测点个数
     * 1.获取pms_monitor表中监测点状态为投运的监测点id列表
     * 2.根据id查询r_mp_integrity_d表中当天各项指标个数，采用以下公式计算数据完整率
     * 3.〖数据完整率〗_日统计=(频率+相电压+线电压+畸变率+不平衡度)/(有效值数据个数*5)*100%
     * 判定监测点数据完整率是否大于95%
     * 4、根据id查询r_stat_abnormal_d表，value_alarm为1。
     * 5、以上两个条件满足表明该监测点为有效监测点。
     * 6、统计有效监测点个数
     * @Param: [indexlist, dataDate]
     * @return: java.lang.String
     * @Author: clam
     * @Date: 2022/11/25
     */
    private Integer queryEffectiveAccessMeasurementCount(List<String> indexlist, String dataDate) {

        /*获取监测点的数据完整性*/
        List<MonitorDataIntegrityDTO> monitorDataIntegrityDTOList = rMpIntegrityDPOService.calculateDataIntegrity(indexlist, dataDate);
        /*获取完整率>0.95的监测点id*/
        List<String> collect = monitorDataIntegrityDTOList.stream().
                filter(temp -> temp.getDataIntegrity().compareTo(new BigDecimal(0.95)) == 1
                ).map(MonitorDataIntegrityDTO::getId).collect(Collectors.toList());
        /*获取完整率>0.95条件下value_alarm为1的监测点id*/
        if (CollectionUtils.isEmpty(collect)) {
            return 0;
        }
        QueryWrapper<RStatAbnormalDPO> rStatAbnormalDPOLambdaQueryWrapper = new QueryWrapper();
        rStatAbnormalDPOLambdaQueryWrapper.select("measurement_point_id").
                in("measurement_point_id", collect).
                eq("value_alarm", 1).
                eq("DATE_FORMAT( data_date ,'%Y-%m-%d')", dataDate);
        List<RStatAbnormalDPO> rStatAbnormalDPOS = rStatAbnormalDPOMapper.selectList(rStatAbnormalDPOLambdaQueryWrapper);

        return rStatAbnormalDPOS.size();

    }


    /**
     * @Description: hanlderOracleQtr
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    @SneakyThrows
    private void hanlderOracleQtr(PrimaryGridParam primaryGridParam) {

        List<String> orgIdList = primaryGridParam.getOrgIdList();
        String beginTime = primaryGridParam.getBeginTime();
        String endTime = primaryGridParam.getEndTime();
        List<ROperatingIndexQPO> rOperatingIndexQPOList = new ArrayList<>();

        orgIdList.forEach(orgid -> {
            /*查询Mouth表数据生成季表数据*/
            List<ROperatingIndexMPO> list = rOperatingIndexMPOService.queryOneQtrData(orgid, beginTime,endTime);
            /*求平均值*/
            int measurement_run_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getMeasurementRunPoints()).
                    average().
                    getAsDouble());
            int transit_measurement_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getTransitMeasurementPoints()).
                    average().
                    getAsDouble());
            int effective_access_measurement_count = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getEffectiveAccessMeasurementCount()).
                    average().
                    getAsDouble());
            int online_measurement_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getOnlineMeasurementPoints()).
                    average().
                    getAsDouble());

            int online_measurement_count = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getOnlineMeasurementCount()).
                    average().
                    getAsDouble());
            /*double保留2位小数*/
            Double data_integrity_rate = Math.round(list.stream().
                    mapToDouble(temp -> temp.getDataIntegrityRate()).
                    average().
                    getAsDouble() * 100) * 0.01;
            /*看day表is_unusual时候存在1存在返回1，数据否异常(0:正常 1:异常)*/
            Integer is_unusual = list.stream().
                    map(ROperatingIndexMPO::getIsUnusual).
                    collect(Collectors.toList())
                    .contains(1) ? 1 : 0;


            ROperatingIndexQPO rOperatingIndexQPO = new ROperatingIndexQPO();
            rOperatingIndexQPO.setOrgNo(orgid);
            rOperatingIndexQPO.setDataDate(LocalDate.parse(primaryGridParam.getDataDate()));
            rOperatingIndexQPO.setMeasurementRunPoints(measurement_run_points);
            rOperatingIndexQPO.setTransitMeasurementPoints(transit_measurement_points);
            rOperatingIndexQPO.setEffectiveAccessMeasurementCount(effective_access_measurement_count);
            rOperatingIndexQPO.setOnlineMeasurementPoints(online_measurement_points);
            rOperatingIndexQPO.setOnlineMeasurementCount(online_measurement_count);
            rOperatingIndexQPO.setDataIntegrityRate(data_integrity_rate);
            rOperatingIndexQPO.setIsUnusual(is_unusual);
            rOperatingIndexQPOList.add(rOperatingIndexQPO);
        });
        if (!CollectionUtils.isEmpty(rOperatingIndexQPOList)) {
            rOperatingIndexQPOService.saveOrUpdateBatchByMultiId(rOperatingIndexQPOList, 30);
        }
    }

    /**
     * @Description: hanlderOracleYear
     * @Param: [primaryGridParam]
     * @return: void
     * @Author: clam
     * @Date: 2022/11/25
     */
    @SneakyThrows
    private void hanlderOracleYear(PrimaryGridParam primaryGridParam) {

        List<String> orgIdList = primaryGridParam.getOrgIdList();
        String beginTime = primaryGridParam.getBeginTime();
        String endTime = primaryGridParam.getEndTime();
        List<ROperatingIndexYPO> rOperatingIndexYPOList = new ArrayList<>();

        orgIdList.forEach(orgid -> {
            /*查询Mouth表数据生成年表数据*/
            List<ROperatingIndexMPO> list = rOperatingIndexMPOService.queryOneYearData(orgid, beginTime,endTime);
            /*求平均值*/
            int measurement_run_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getMeasurementRunPoints()).
                    average().
                    getAsDouble());
            int transit_measurement_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getTransitMeasurementPoints()).
                    average().
                    getAsDouble());
            int effective_access_measurement_count = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getEffectiveAccessMeasurementCount()).
                    average().
                    getAsDouble());
            int online_measurement_points = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getOnlineMeasurementPoints()).
                    average().
                    getAsDouble());

            int online_measurement_count = (int) Math.round(list.stream().
                    mapToDouble(temp -> temp.getOnlineMeasurementCount()).
                    average().
                    getAsDouble());
            /*double保留2位小数*/
            Double data_integrity_rate = Math.round(list.stream().
                    mapToDouble(temp -> temp.getDataIntegrityRate()).
                    average().
                    getAsDouble() * 100) * 0.01;
            /*看day表is_unusual时候存在1存在返回1，数据否异常(0:正常 1:异常)*/
            Integer is_unusual = list.stream().
                    map(ROperatingIndexMPO::getIsUnusual).
                    collect(Collectors.toList())
                    .contains(1) ? 1 : 0;


            ROperatingIndexYPO rOperatingIndexYPO = new ROperatingIndexYPO();
            rOperatingIndexYPO.setOrgNo(orgid);
            rOperatingIndexYPO.setDataDate(LocalDate.parse(primaryGridParam.getDataDate()));
            rOperatingIndexYPO.setMeasurementRunPoints(measurement_run_points);
            rOperatingIndexYPO.setTransitMeasurementPoints(transit_measurement_points);
            rOperatingIndexYPO.setEffectiveAccessMeasurementCount(effective_access_measurement_count);
            rOperatingIndexYPO.setOnlineMeasurementPoints(online_measurement_points);
            rOperatingIndexYPO.setOnlineMeasurementCount(online_measurement_count);
            rOperatingIndexYPO.setDataIntegrityRate(data_integrity_rate);
            rOperatingIndexYPO.setIsUnusual(is_unusual);
            rOperatingIndexYPOList.add(rOperatingIndexYPO);
        });
        if (!CollectionUtils.isEmpty(rOperatingIndexYPOList)) {
            rOperatingIndexYPOService.saveOrUpdateBatchByMultiId(rOperatingIndexYPOList, 30);
        }

    }

}
