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

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.pojo.dto.PmsMonitorDTO;
import com.njcn.device.pms.pojo.param.PmsMonitorParam;
import com.njcn.harmonic.pojo.po.RMpIntegrityDPO;
import com.njcn.harmonic.pojo.po.RMpPartHarmonicDetailD;
import com.njcn.harmonic.pojo.po.RMpSurplusHarmonicDetailD;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpPartHarmonicDetailDMapper;
import com.njcn.prepare.harmonic.mapper.mysql.line.RMpSurplusHarmonicDetailDMapper;
import com.njcn.prepare.harmonic.pojo.mysql.po.line.RMpPassRateDPO;
import com.njcn.prepare.harmonic.pojo.mysql.po.line.RMpPassRateMPO;
import com.njcn.prepare.harmonic.pojo.mysql.po.line.RMpPassRateQPO;
import com.njcn.prepare.harmonic.pojo.mysql.po.line.RMpPassRateYPO;
import com.njcn.prepare.harmonic.pojo.param.LineParam;
import com.njcn.prepare.harmonic.service.mysql.area.RMpIntegrityDPOService;
import com.njcn.prepare.harmonic.service.mysql.line.*;
import com.njcn.prepare.harmonic.utils.PublicUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description:
 * 接口文档访问地址：http://serverIP:port/swagger-ui.html
 * Date: 2023/2/28  10:27【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class RmpPassRateServiceImpl implements RmpPassRateService {

    private final MonitorClient monitorClient;
    private final RMpIntegrityDPOService rMpIntegrityDPOService;
    private final RMpPartHarmonicDetailDMapper rMpPartHarmonicDetailDMapper;
    private final RMpSurplusHarmonicDetailDMapper rMpSurplusHarmonicDetailDMapper;
    private final RMpPassRateDService rmpPassRateDService;
    private final RMpPassRateMService rmpPassRateMService;
    private final RMpPassRateQService rmpPassRateQService;
    private final RMpPassRateYService rmpPassRateYService;


    DecimalFormat df = new DecimalFormat("0.00");


    /*接口重mysql中取数据不分oracle/Influxdb*/
    @Override
    public void rmpPassRateDHandler(LineParam lineParam) {
        Integer type = lineParam.getType ( );
        switch (type) {
            case 1:
                this.hanlderYear (lineParam);
                break;
            case 2:
                this.hanlderQtr (lineParam);
                break;
            case 3:
                this.hanlderMonth (lineParam);
                break;
            case 5:
                this.hanlderDay (lineParam);
                break;
            default:
                break;
        }
    }

    private void hanlderYear(LineParam lineParam) {
        String dataDate = lineParam.getDataDate();
        Date date = DateUtil.parse(lineParam.getDataDate());

        List<String> lineIds = lineParam.getLineIds();
        List<RMpPassRateYPO> rMpPassRateYPOList = new ArrayList<> ();
        lineIds.forEach (temp ->{
            QueryWrapper<RMpPassRateMPO> queryWrapper = new QueryWrapper<> ();
            queryWrapper.eq ("measurement_point_id", temp).
                    eq("YEAR( data_date )",dataDate.substring (0, 4));
            List<RMpPassRateMPO> list = rmpPassRateMService.list (queryWrapper);
            /*求平均值*/
            Double flickerPassRate = list.stream ( ).map (rMpPassRateMPO -> rMpPassRateMPO.getFlickerPassRate ( )).
                    collect (Collectors.averagingDouble (x -> x));
            Double freqPassRate = list.stream ( ).map (rMpPassRateMPO -> rMpPassRateMPO.getFreqPassRate ( )).
                    collect (Collectors.averagingDouble (x -> x));
            Double vDevPassRate =list.stream ( ).map (rMpPassRateMPO -> rMpPassRateMPO.getvDevPassRate ( )).
                    collect (Collectors.averagingDouble (x -> x));
            RMpPassRateYPO rMpPassRateYPO = new RMpPassRateYPO();
            rMpPassRateYPO.setMeasurementPointId (temp);
            rMpPassRateYPO.setDataDate (date);
            rMpPassRateYPO.setFlickerPassRate (
                    flickerPassRate            );
            rMpPassRateYPO.setFreqPassRate (
                    freqPassRate            );
            rMpPassRateYPO.setvDevPassRate (
                    vDevPassRate            );
            rMpPassRateYPOList.add (rMpPassRateYPO);
        });
        if(!CollectionUtils.isEmpty (rMpPassRateYPOList)){
            rmpPassRateYService.saveOrUpdateBatchByMultiId (rMpPassRateYPOList,500);
        }
    }

    private void hanlderQtr(LineParam lineParam) {
        String dataDate = lineParam.getDataDate();
        Date date = DateUtil.parse(lineParam.getDataDate());

        List<String> lineIds = lineParam.getLineIds();
        List<RMpPassRateQPO> rMpPassRateQPOList = new ArrayList<> ();
        lineIds.forEach (temp ->{
            QueryWrapper<RMpPassRateMPO> queryWrapper = new QueryWrapper<> ();
            queryWrapper.eq ("measurement_point_id", temp).
                    eq("QUARTER( data_date)", PublicUtil.getNowQuarter (dataDate));
            List<RMpPassRateMPO> list = rmpPassRateMService.list (queryWrapper);
            /*求平均值*/
            Double flickerPassRate = list.stream ( ).map (rMpPassRateMPO -> rMpPassRateMPO.getFlickerPassRate ( )).
                    collect (Collectors.averagingDouble (x -> x));
            Double freqPassRate = list.stream ( ).map (rMpPassRateMPO -> rMpPassRateMPO.getFreqPassRate ( )).
                    collect (Collectors.averagingDouble (x -> x));
            Double vDevPassRate =list.stream ( ).map (rMpPassRateMPO -> rMpPassRateMPO.getvDevPassRate ( )).
                    collect (Collectors.averagingDouble (x -> x));
            RMpPassRateQPO rMpPassRateQPO = new RMpPassRateQPO();
            rMpPassRateQPO.setMeasurementPointId (temp);
            rMpPassRateQPO.setDataDate (date);
            rMpPassRateQPO.setFlickerPassRate (
                    flickerPassRate            );
            rMpPassRateQPO.setFreqPassRate (
                    freqPassRate            );
            rMpPassRateQPO.setvDevPassRate (
                    vDevPassRate            );
            rMpPassRateQPOList.add (rMpPassRateQPO);
        });
        if(!CollectionUtils.isEmpty (rMpPassRateQPOList)){
            rmpPassRateQService.saveOrUpdateBatchByMultiId (rMpPassRateQPOList,500);
        }
    }

    /**
    * @Description: 月表为日表累计
    * @Param: [lineParam] 
    * @return: void 
    * @Author: clam
    * @Date: 2023/2/28 
    */ 
    private void hanlderMonth(LineParam lineParam) {
        String dataDate = lineParam.getDataDate();
        Date date = DateUtil.parse(lineParam.getDataDate());

        List<String> lineIds = lineParam.getLineIds();
        List<RMpPassRateMPO> rMpPassRateMPOList = new ArrayList<> ();
        lineIds.forEach (temp ->{
            QueryWrapper<RMpPassRateDPO> queryWrapper = new QueryWrapper<> ();
            queryWrapper.eq ("measurement_point_id", temp).
                    eq("DATE_FORMAT( data_date ,'%Y-%m')",dataDate.substring (0, 7));
            List<RMpPassRateDPO> list = rmpPassRateDService.list (queryWrapper);
            Integer effectiveTime = Integer.valueOf (
                    list.stream ( ).mapToLong (RMpPassRateDPO::getEffectiveTime).sum ( ) + ""
            );
            Integer flickerTime = Integer.valueOf (
                    list.stream ( ).mapToLong (RMpPassRateDPO::getFlickerTime).sum ( ) + ""
            );
            Integer freqTime = Integer.valueOf (
                    list.stream ( ).mapToLong (RMpPassRateDPO::getFreqTime).sum ( ) + ""
            );
            Integer vDevTime = Integer.valueOf (
                    list.stream ( ).mapToLong (RMpPassRateDPO::getvDevTime).sum ( ) + ""
            );
            RMpPassRateMPO rMpPassRateMPO = new RMpPassRateMPO();
            rMpPassRateMPO.setMeasurementPointId (temp);
            rMpPassRateMPO.setDataDate (date);
            rMpPassRateMPO.setFlickerPassRate (
                    Double.valueOf (df.format ((float) flickerTime / effectiveTime))
            );
            rMpPassRateMPO.setFreqPassRate (
                    Double.valueOf (df.format ((float) freqTime / effectiveTime))
            );
            rMpPassRateMPO.setvDevPassRate (
                    Double.valueOf (df.format ((float) vDevTime / effectiveTime))
            );
            rMpPassRateMPOList.add (rMpPassRateMPO);
        });
        if(!CollectionUtils.isEmpty (rMpPassRateMPOList)){
            rmpPassRateMService.saveOrUpdateBatchByMultiId (rMpPassRateMPOList,500);
        }
    }

    /** 
    * @Description: 1.    日有效监测时长(min)：表1的统计间隔*表2的有效接入分钟数量。
     * 2.	频率偏差超标时长(min)：表1的统计间隔*表3的频率偏差超标次数。
     * 3.	电压偏差超标时长(min)：表1的统计间隔*表3的电压偏差超标次数。
     * 4.	闪变超标时长(min)：2*60*闪变发生次数 
    * @Param: [lineParam] 
    * @return: void 
    * @Author: clam
    * @Date: 2023/2/28 
    */ 
    private void hanlderDay(LineParam lineParam) {

        Date date = DateUtil.parse(lineParam.getDataDate());
        List<String> lineIds = lineParam.getLineIds();
        Integer type = lineParam.getType();
        Integer lineType = lineParam.getLineType();
        PmsMonitorParam pmsMonitorParam = new PmsMonitorParam();
        pmsMonitorParam.setMonitorIds (lineIds);
        List<RMpPassRateDPO> rMpPassRateDPOList = new ArrayList<> ();
        List<PmsMonitorDTO>  data = monitorClient.getMonitorInfoListByCond (pmsMonitorParam).getData ( );
        data.forEach (temp ->{
            RMpPassRateDPO rMpPassRateDPO = new RMpPassRateDPO();
            Integer statisticalInterval = temp.getStatisticalInterval ( );
            String id = temp.getId ( );
            QueryWrapper<RMpIntegrityDPO> rMpIntegrityDPOQueryWrapper = new QueryWrapper();

            rMpIntegrityDPOQueryWrapper.eq ("measurement_point_id", id).
                    eq ("data_date", date);

            RMpIntegrityDPO rMpIntegrityDPO = rMpIntegrityDPOService.getOne (rMpIntegrityDPOQueryWrapper);

            QueryWrapper<RMpPartHarmonicDetailD> rMpPartHarmonicDetailDQueryWrapper = new QueryWrapper();
            rMpPartHarmonicDetailDQueryWrapper.eq ("measurement_point_id", id).
                    eq ("data_date", date);
            RMpPartHarmonicDetailD rMpPartHarmonicDetailD = rMpPartHarmonicDetailDMapper.selectOne (rMpPartHarmonicDetailDQueryWrapper);

            QueryWrapper<RMpSurplusHarmonicDetailD> rMpSurplusHarmonicDetailDQueryWrapper = new QueryWrapper();
            rMpSurplusHarmonicDetailDQueryWrapper.eq ("measurement_point_id", id).
                    eq ("data_date", date);
            RMpSurplusHarmonicDetailD rMpSurplusHarmonicDetailD = rMpSurplusHarmonicDetailDMapper.selectOne (rMpSurplusHarmonicDetailDQueryWrapper);
            rMpPassRateDPO.setMeasurementPointId (id);
            rMpPassRateDPO.setDataDate (date);
            rMpPassRateDPO.setEffectiveTime (rMpIntegrityDPO.getEffectiveMinuteCount ()*statisticalInterval);
            rMpPassRateDPO.setFlickerTime (2*60*rMpSurplusHarmonicDetailD.getFlickerTimes ());
            rMpPassRateDPO.setFreqTime (rMpPartHarmonicDetailD.getFreqTimes ()*statisticalInterval);
            rMpPassRateDPO.setvDevTime (rMpPartHarmonicDetailD.getVDevTimes ()*statisticalInterval);
            rMpPassRateDPOList.add (rMpPassRateDPO);
        });
        if(!CollectionUtils.isEmpty (rMpPassRateDPOList)){
            rmpPassRateDService.saveOrUpdateBatchByMultiId (rMpPassRateDPOList,500);
        }

    }
}
