package com.njcn.harmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloud.apigateway.sdk.utils.Client;
import com.cloud.apigateway.sdk.utils.Request;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.biz.commApi.CommTerminalGeneralClient;
import com.njcn.device.biz.pojo.dto.LineDevGetDTO;
import com.njcn.device.biz.pojo.po.Overlimit;
import com.njcn.device.biz.pojo.po.PqsDeviceUnit;
import com.njcn.device.biz.utils.COverlimitUtil;
import com.njcn.event.api.EventDetailFeignClient;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.harmonic.mapper.HistoryDataMapper;
import com.njcn.harmonic.pojo.QueryResultLimitVO;
import com.njcn.harmonic.pojo.param.HarmonicHistoryParam;
import com.njcn.harmonic.pojo.param.HistoryParam;
import com.njcn.harmonic.pojo.po.zt.HarmonicHistoryC;
import com.njcn.harmonic.pojo.po.zt.HarmonicHistoryP;
import com.njcn.harmonic.pojo.po.zt.HarmonicHistoryV;
import com.njcn.harmonic.pojo.vo.EventDetailVO;
import com.njcn.harmonic.pojo.vo.HistoryDataResultVO;
import com.njcn.harmonic.service.OracleResultService;
import com.njcn.influx.pojo.bo.HarmonicHistoryData;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wr
 * @description
 * @date 2024/1/11 16:15
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OracleResultServiceImpl implements OracleResultService {
    private final EventDetailFeignClient eventDetailFeignClient;
    private final CommTerminalGeneralClient commTerminalGeneralClient;
    private final DicDataFeignClient dicDataFeignClient;
    private final HistoryDataMapper HistoryDataMapper;

    @Override
    public List<HistoryDataResultVO> getHistoryResult(HistoryParam historyParam) {
        List<HistoryDataResultVO> historyDataResultVOList = new ArrayList<>();
        //获取监测点
        String[] points = historyParam.getLineId();
        Integer number = 0;
        for (int i = 0; i < points.length; i++) {
            HistoryDataResultVO historyDataResultVO;
            List<EventDetail> eventDetailList = eventDetailFeignClient.getEventDetailData(points[i], historyParam.getSearchBeginTime(), historyParam.getSearchEndTime()).getData();
            List<EventDetailVO> eventDetailVOList = new ArrayList<>();
            if (!eventDetailList.isEmpty()) {
                for (EventDetail eventdetail : eventDetailList) {
                    String timeText = eventdetail.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
                    EventDetailVO eventDetailVO = new EventDetailVO();
                    eventDetailVO.setId(eventdetail.getEventId());
                    eventDetailVO.setTime(timeText);
                    eventDetailVOList.add(eventDetailVO);
                }
            }
            //获取指标
            String[] contions = historyParam.getCondition();
            for (int j = 0; j < contions.length; j++) {
                if ("40".equals(contions[j]) || "41".equals(contions[j]) || "42".equals(contions[j]) || "43".equals(contions[j])
                        || "44".equals(contions[j]) || "45".equals(contions[j]) || "50".equals(contions[j]) || "51".equals(contions[j])
                        || "52".equals(contions[j])) {
                    number = historyParam.getHarmonic();
                }
                if ("46".equals(contions[j]) || "47".equals(contions[j]) || "48".equals(contions[j]) || "49".equals(contions[j])) {
                    number = historyParam.getInHarmonic();
                }
                historyDataResultVO = getCondition(historyParam.getSearchBeginTime(), historyParam.getSearchEndTime(), points[i], contions[j], number, historyParam.getValueType(), historyParam.getPtType());
                historyDataResultVO.setEventDetail(eventDetailVOList);
                historyDataResultVOList.add(historyDataResultVO);
            }
        }
        return historyDataResultVOList;
    }


    @SneakyThrows
    private HistoryDataResultVO getCondition(String startTime, String endTime, String lineId, String contion, Integer number, Integer valueType, Integer ptType) {
        HistoryDataResultVO historyDataResultVO = new HistoryDataResultVO();
        QueryResultLimitVO queryResultLimitVO = getQueryResult(startTime, endTime, lineId, contion, number, valueType, ptType);
        List<HarmonicHistoryData> harmonicHistoryDataList = queryResultLimitVO.getHarmonicHistoryDataList();
        BeanUtil.copyProperties(queryResultLimitVO, historyDataResultVO);
        //时间轴
        List<Date> time = new ArrayList<>();
        //A相值
        List<Float> aValue;
        //B相值
        List<Float> bValue = new ArrayList<>();
        //C相值
        List<Float> cValue = new ArrayList<>();
        //针对统计相别为T时存放的数据
        List<Float> fValue = new ArrayList<>();
        List<List<Object>> objectListData = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(harmonicHistoryDataList)) {
            //相别统计为T时，业务数据处理
            if (StrUtil.isBlank(harmonicHistoryDataList.get(0).getPhasicType()) || harmonicHistoryDataList.get(0).getPhasicType().equalsIgnoreCase("t")) {
                for (HarmonicHistoryData harmonicHistoryData : harmonicHistoryDataList) {
                    time.add(PubUtils.instantToDate(harmonicHistoryData.getTime()));
                    fValue.add(BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP).floatValue());
                    //返回结果有多个值，需要额外处理下
                    if (Integer.parseInt(contion) == 14) {
                        bValue.add(BigDecimal.valueOf(harmonicHistoryData.getBValue()).setScale(4, RoundingMode.HALF_UP).floatValue());
                        cValue.add(BigDecimal.valueOf(harmonicHistoryData.getCValue()).setScale(4, RoundingMode.HALF_UP).floatValue());
                    }
                }
                //组装二维数组
                for (int i = 0; i < time.size(); i++) {
                    List<Object> objects = new ArrayList<>();
                    objects.add(time.get(i));
                    objects.add(fValue.get(i));
                    if (Integer.parseInt(contion) == 14) {
                        objects.add(bValue.get(i));
                        objects.add(cValue.get(i));
                    }
                    objectListData.add(objects);
                }
                historyDataResultVO.setTopLimit(queryResultLimitVO.getTopLimit());
                historyDataResultVO.setLowerLimit(queryResultLimitVO.getLowerLimit());
                historyDataResultVO.setMinValue(Collections.min(fValue));
                historyDataResultVO.setMaxValue(Collections.max(fValue));
                historyDataResultVO.setValue(objectListData);
            } else {
                //按时间分组
                Map<Instant,List<HarmonicHistoryData>> map = harmonicHistoryDataList.stream().collect(Collectors.groupingBy(HarmonicHistoryData::getTime,TreeMap::new, Collectors.toList()));

                Float maxI = null;
                Float minI = null;
                for (Map.Entry<Instant, List<HarmonicHistoryData>> entry : map.entrySet()) {
                    List<HarmonicHistoryData> val = entry.getValue();
                    Object[] objects = {PubUtils.instantToDate(entry.getKey()),0,0,0};
                    //需要保证val的长度为3
                    if(val.size()!=3){
                        for(int i =0;i<3-val.size();i++){
                            HarmonicHistoryData tem = new HarmonicHistoryData();
                            tem.setAValue(0f);
                            val.add(tem);
                        }
                    }
                    for (HarmonicHistoryData harmonicHistoryData : val) {
                        if (InfluxDBTableConstant.PHASE_TYPE_A.equalsIgnoreCase(harmonicHistoryData.getPhasicType())) {

                            BigDecimal a = BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP);
                            objects[1] =a;
                            maxI = max(maxI, a.floatValue());
                            minI = min(minI, a.floatValue());

                        } else if (InfluxDBTableConstant.PHASE_TYPE_B.equalsIgnoreCase(harmonicHistoryData.getPhasicType())) {
                            BigDecimal b = BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP);
                            objects[2] = b;
                            maxI = max(maxI, b.floatValue());
                            minI = min(minI, b.floatValue());

                        } else if (InfluxDBTableConstant.PHASE_TYPE_C.equalsIgnoreCase(harmonicHistoryData.getPhasicType())) {
                            BigDecimal c = BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, RoundingMode.HALF_UP);
                            objects[3] = c;
                            maxI = max(maxI, c.floatValue());
                            minI = min(minI, c.floatValue());

                        }
                    }
                    List<Object> list = new ArrayList<>(Arrays.asList(objects));
                    objectListData.add(list);
                }
                historyDataResultVO.setMaxValue(maxI);
                historyDataResultVO.setMinValue(minI);
                historyDataResultVO.setTopLimit(queryResultLimitVO.getTopLimit());
                historyDataResultVO.setLowerLimit(queryResultLimitVO.getLowerLimit());
                historyDataResultVO.setValue(objectListData);
            }

        } else {
            historyDataResultVO.setTopLimit(queryResultLimitVO.getTopLimit());
            historyDataResultVO.setLowerLimit(queryResultLimitVO.getLowerLimit());
            historyDataResultVO.setValue(objectListData);
            return historyDataResultVO;
        }
        return historyDataResultVO;
    }


    private QueryResultLimitVO getQueryResult(String startTime, String endTime, String lineId, String contion, Integer number, Integer valueType, Integer ptType) {
        PqsDeviceUnit pqsDeviceUnit = commTerminalGeneralClient.lineUnitDetail(lineId).getData();

        QueryResultLimitVO queryResultLimitVO = new QueryResultLimitVO();
        if (!lineId.isEmpty()) {
            Float topLimit = 0f;
            Float lowerLimit = 0f;
            //获取监测点信息
            LineDevGetDTO lineDetailDataVO = commTerminalGeneralClient.getMonitorDetail(lineId).getData();
            //获取限值
            Overlimit overlimit = commTerminalGeneralClient.getOverLimitData(lineId).getData();
            if(Objects.isNull(overlimit)){
                //对配网没有限值的统一处理
                DictData dictData = dicDataFeignClient.getDicDataById(lineDetailDataVO.getVoltageLevel()).getData();
                float voltageLevel = Float.parseFloat(dictData.getValue());
                float shortVal = COverlimitUtil.getDlCapByVoltageLevel(voltageLevel);
                overlimit = COverlimitUtil.globalAssemble(voltageLevel,10f,10f,shortVal,1,1);
            }

            String valueTypeName = "";
            switch (valueType) {
                case 1:
                    valueTypeName = "";
                    break;
                case 2:
                    valueTypeName = "MIN";
                    break;
                case 3:
                    valueTypeName = "MAX";
                    break;
                case 4:
                    valueTypeName = "CP95";
                    break;
                default:
                    break;
            }
            List<String> phasicType = new ArrayList<>();
            List<String> unit = new ArrayList<>();
            String targetName = "";
            switch (Integer.parseInt(contion)) {
                case 10:
                    //相电压有效值
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getPhaseVoltage());
                    targetName = "相电压有效值";
                    break;
                case 11:
                    //线电压有效值
                    phasicType.add("AB相");
                    phasicType.add("BC相");
                    phasicType.add("CA相");
                    unit.add(pqsDeviceUnit.getLineVoltage());
                    targetName = "线电压有效值";
                    break;
                case 12:
                    //电压偏差
                    topLimit = overlimit.getVoltageDev();
                    lowerLimit = overlimit.getUvoltageDev();
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add("%");
                    targetName = "电压偏差";
                    break;
                case 13:
                    //三相电压不平衡度
                    topLimit = overlimit.getUbalance();
                    phasicType.add("三相电压不平衡度");
                    unit.add("%");
                    targetName = "三相电压不平衡度";
                    break;
                case 14:
                    //电压不平衡
                    phasicType.add("零序电压");
                    phasicType.add("正序电压");
                    phasicType.add("负序电压");
                    unit.add(pqsDeviceUnit.getNoPositiveV());
                    unit.add(pqsDeviceUnit.getPositiveV());
                    unit.add(pqsDeviceUnit.getNoPositiveV());
                    targetName = "电压不平衡";
                    break;
                case 15:
                    //电压总谐波畸变率
                    topLimit = overlimit.getUaberrance();
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add("%");
                    targetName = "电压总谐波畸变率";
                    break;
                case 20:
                    //电流有效值
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("A");
                    targetName = "电流有效值";
                    break;
                case 21:
                    //电流总畸变率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("%");
                    targetName = "电流总谐波畸变率";
                    break;
                case 22:
                    //负序电流
                    topLimit = overlimit.getINeg();
                    phasicType.add("负序电流");
                    unit.add("A");
                    targetName = "负序电流";
                    break;
                case 30:
                    //频率 V9暂时代表Freq
                    topLimit = 50 + overlimit.getFreqDev();
                    lowerLimit = 50 - overlimit.getFreqDev();
                    phasicType.add("频率");
                    unit.add("Hz");
                    targetName = "频率";
                    break;
                case 40:
                    //谐波电压含有率
                    if (number != 1) {
                        if (number < 26) {
                            topLimit = PubUtils.getValueByMethod(overlimit, "getUharm", number);
                        }
                    }
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add("%");
                    targetName = "谐波电压含有率";
                    break;
                case 41:
                    //谐波电流含有率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("%");
                    targetName = "谐波电流含有率";
                    break;
                case 42:
                    //谐波电压幅值
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getVfundEffective());
                    } else {
                        unit.add("V");
                    }
                    targetName = "谐波电压幅值";
                    break;
                case 43:
                    //谐波电流幅值
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("A");
                    targetName = "谐波电流幅值";
                    break;
                case 44:
                    //谐波电压相角
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add("°");
                    targetName = "谐波电压相角";
                    break;
                case 45:
                    //谐波电流相角
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("°");
                    targetName = "谐波电流相角";
                    break;
                case 46:
                    //间谐波电压含有率
                    topLimit = PubUtils.getValueByMethod(overlimit, "getInuharm", number);
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add("%");
                    targetName = "间谐波电压含有率";
                    break;
                case 47:
                    //间谐波电流含有率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("%");
                    targetName = "间谐波电流含有率";
                    break;
                case 48:
                    //间谐波电压幅值
                    targetName = "间谐波电压幅值";
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add(pqsDeviceUnit.getPhaseVoltage());
                    break;
                case 49:
                    //间谐波电流幅值
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("A");
                    targetName = "间谐波电流幅值";
                    break;
                case 50:
                    //谐波有功功率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getFundActiveP());
                    } else {
                        unit.add("W");
                    }
                    targetName = "谐波有功功率";
                    break;
                case 51:
                    //谐波无功功率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getTotalNoP());
                    } else {
                        unit.add("Var");
                    }
                    targetName = "谐波无功功率";
                    break;
                case 52:
                    //谐波视在功率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getTotalViewP());
                    } else {
                        unit.add("VA");
                    }
                    targetName = "谐波视在功率";
                    break;
                case 53:
                    //三相有功功率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getTotalActiveP());
                    targetName = "三相有功功率";
                    break;
                case 54:
                    //三相无功功率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getTotalNoP());
                    targetName = "三相无功功率";
                    break;
                case 55:
                    //三相视在功率
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getTotalViewP());
                    targetName = "三相视在功率";
                    break;
                case 56:
                    //三相总有功功率
                    phasicType.add("三相总有功功率");
                    unit.add(pqsDeviceUnit.getTotalActiveP());
                    targetName = "三相总有功功率";
                    break;
                case 57:
                    //三相总无功功率
                    phasicType.add("三相总无功功率");
                    unit.add(pqsDeviceUnit.getTotalNoP());
                    targetName = "三相总无功功率";
                    break;
                case 58:
                    //三相总视在功率
                    phasicType.add("三相总视在功率");
                    unit.add(pqsDeviceUnit.getTotalViewP());
                    targetName = "三相总视在功率";
                    break;
                case 59:
                    //视在功率因数
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    targetName = "视在功率因数";
                    break;
                case 591:
                    //位移功率因数
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    targetName = "位移功率因数";
                    break;
                case 592:
                    //总视在功率因数
                    phasicType.add("总视在功率因数");
                    targetName = "总视在功率因数";
                    break;
                case 593:
                    //总位移功率因数
                    phasicType.add("总位移功率因数");
                    targetName = "总位移功率因数";
                    break;
                case 61:
                    //长时闪变
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    topLimit = overlimit.getFlicker();
                    targetName = "长时闪变";
                    break;
                case 60:
                    //短时闪变
                    topLimit = overlimit.getFlicker();
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    targetName = "短时闪变";
                    break;
                case 62:
                    //电压波动
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    targetName = "电压波动";
                    break;
                default:
                    break;
            }
            //大致有3种类型
            //1、一次查询返回3条记录，分别为A/B/C三相的结果
            //2、一次查询返回一条记录，以T相为条件，返回某3个指标值
            //3、一次查询返回一条记录，以T相为条件，返回某1个指标值
            HarmonicHistoryParam historyParam=new HarmonicHistoryParam();
            if(lineDetailDataVO.getOracleLineId()!=null){
                //当oracle监测点不为空说明是主网监测点
                historyParam.setStartTime(startTime+InfluxDBTableConstant.START_TIME);
                historyParam.setEndTime(endTime+InfluxDBTableConstant.END_TIME);
                historyParam.setValueTypeName(valueTypeName);
                historyParam.setLineId(lineDetailDataVO.getOracleLineId().toString());
            }else{
                //就是配网监测点
                historyParam.setStartTime(startTime.replace("-",""));
                historyParam.setEndTime(endTime.replace("-",""));
                historyParam.setValueTypeName(valueTypeName);
                historyParam.setLineId(lineId);
            }
            queryResultLimitVO.setHarmonicHistoryDataList(setHistoryDataList(historyParam, contion, number,lineDetailDataVO.getType()));
            queryResultLimitVO.setTopLimit(topLimit);
            queryResultLimitVO.setLowerLimit(lowerLimit);
            queryResultLimitVO.setPhaiscType(phasicType);
            queryResultLimitVO.setUnit(unit);
            queryResultLimitVO.setLineName(lineDetailDataVO.getPointName());
            queryResultLimitVO.setHarmNum(number);
            queryResultLimitVO.setTargetName(targetName);
        } else {
            return queryResultLimitVO;
        }
        return queryResultLimitVO;
    }

    /**
     * 数值赋值
     * @param historyParam
     * @param contion
     * @param number
     * @param type 区分主配网
     * @return
     */
    private List<HarmonicHistoryData> setHistoryDataList(HarmonicHistoryParam historyParam,String contion,Integer number,Integer type){
        List<HarmonicHistoryData> harmonicHistoryData = new ArrayList<>();
        switch (Integer.parseInt(contion)) {
            case 10:
                //相电压有效值
                if(type==0){
                    harmonicHistoryData=HistoryDataMapper.getDataV(historyParam);
                }else{
                    harmonicHistoryData=ztHarmonicHistoryV(historyParam);
                }
                break;
            case 11:
                //线电压有效值
                harmonicHistoryData=HistoryDataMapper.getDataV_lvr(historyParam);
                break;
            case 12:
                //电压偏差
                harmonicHistoryData=HistoryDataMapper.getDataV_vu_dev(historyParam);
                break;
            case 13:
                //三相电压不平衡度
                harmonicHistoryData=HistoryDataMapper.getDataV_v_unbalance(historyParam);
                break;
            case 14:
                //电压不平衡
                harmonicHistoryData=HistoryDataMapper.getDataV_v_zero(historyParam);
                break;
            case 15:
                //电压总谐波畸变率
                harmonicHistoryData=HistoryDataMapper.getDataV_v_thd(historyParam);
                break;
            case 20:
                //电流有效值
                harmonicHistoryData=HistoryDataMapper.getDataI_rms(historyParam);
                break;
            case 21:
                //电流总畸变率
                harmonicHistoryData=HistoryDataMapper.getDataI_i_thd(historyParam);
                break;
            case 22:
                //负序电流
                harmonicHistoryData=HistoryDataMapper.getDataI_i_neg(historyParam);
                break;
            case 30:
                //频率 V9暂时代表Freq
                harmonicHistoryData=HistoryDataMapper.getDataV_i_neg(historyParam);
                break;
            case 40:
                //谐波电压含有率
                harmonicHistoryData=HistoryDataMapper.getDataHarmratV_v(historyParam,number);
                break;
            case 41:
                //谐波电流含有率
                harmonicHistoryData=HistoryDataMapper.getDataHarmratI_i(historyParam,number);
                break;
            case 42:
                //谐波电压幅值
                harmonicHistoryData=HistoryDataMapper.getDataV_v(historyParam,number);
                break;
            case 43:
                //谐波电流幅值
                harmonicHistoryData=HistoryDataMapper.getDataI_i(historyParam,number);
                break;
            case 44:
                //谐波电压相角
                harmonicHistoryData=HistoryDataMapper.getDataHarmphasic_v(historyParam,number);
                break;
            case 45:
                //谐波电流相角
                harmonicHistoryData=HistoryDataMapper.getDataHarmphasic_i(historyParam,number);
                break;
            case 46:
                //todo 间谐波电压含有率
                harmonicHistoryData=HistoryDataMapper.getDataInharmrateV_v(historyParam,number);
                break;
            case 47:
                //todo 间谐波电流含有率
                harmonicHistoryData=HistoryDataMapper.getDataInharmrateI_i(historyParam,number);
                break;
            case 48:
                //间谐波电压幅值
                harmonicHistoryData=HistoryDataMapper.getDataInharmrateV_v(historyParam,number);
                break;
            case 49:
                //间谐波电流幅值
                harmonicHistoryData=HistoryDataMapper.getDataInharmrateI_i(historyParam,number);
                break;
            case 50:
                //谐波有功功率
                harmonicHistoryData = HistoryDataMapper.getDataHarmpowerP_p(historyParam, number);
                break;
            case 51:
                //谐波无功功率
                harmonicHistoryData=HistoryDataMapper.getDataHarmpowerQ_q(historyParam,number);

                break;
            case 52:
                //谐波视在功率
                harmonicHistoryData=HistoryDataMapper.getDataHarmpowerS_s(historyParam,number);
                break;
            case 53:
                //三相有功功率
                if(type==0) {
                    harmonicHistoryData=HistoryDataMapper.getDataHarmpowerP(historyParam);
                }else{
                    harmonicHistoryData =ztHarmonicHistoryP(historyParam,1);
                }
                break;
            case 54:
                //三相无功功率
                if(type==0) {
                    harmonicHistoryData=HistoryDataMapper.getDataHarmpowerQ(historyParam);
                }else{
                    harmonicHistoryData =ztHarmonicHistoryP(historyParam,2);
                }
                break;
            case 55:
                //三相视在功率
                harmonicHistoryData=HistoryDataMapper.getDataHarmpowerS(historyParam);
                break;
            case 56:
                //三相总有功功率
                if(type==0) {
                    harmonicHistoryData=HistoryDataMapper.getDataHarmpowerP_t(historyParam);
                }else{
                    harmonicHistoryData =ztHarmonicHistoryP(historyParam,3);
                }
                break;
            case 57:
                //三相总无功功率
                if(type==0) {
                    harmonicHistoryData=HistoryDataMapper.getDataHarmpowerQ_t(historyParam);
                }else{
                    harmonicHistoryData =ztHarmonicHistoryP(historyParam,4);
                }
                break;
            case 58:
                //三相总视在功率
                harmonicHistoryData=HistoryDataMapper.getDataHarmpowerS_t(historyParam);
                break;
            case 59:
                //视在功率因数
                if(type==0) {
                    harmonicHistoryData=HistoryDataMapper.getDataHarmpowerP_pf(historyParam);
                }else{
                    harmonicHistoryData =ztHarmonicHistoryC(historyParam,1);
                }
                break;
            case 591:
                //位移功率因数
                harmonicHistoryData=HistoryDataMapper.getDataHarmpowerP_df(historyParam);
                break;
            case 592:
                //总视在功率因数
                if(type==0) {
                    harmonicHistoryData=HistoryDataMapper.getDataHarmpowerP_pf_T(historyParam);
                }else{
                    harmonicHistoryData =ztHarmonicHistoryC(historyParam,2);
                }
                break;
            case 593:
                //总位移功率因数
                harmonicHistoryData=HistoryDataMapper.getDataHarmpowerP_df_T(historyParam);
                break;
            case 61:
                //长时闪变
                harmonicHistoryData=HistoryDataMapper.getDataPlt(historyParam);
                break;
            case 60:
                //短时闪变
                harmonicHistoryData=HistoryDataMapper.getDataFlicker(historyParam);
                break;
            case 62:
                //电压波动
                harmonicHistoryData=HistoryDataMapper.getDataFluc(historyParam);
                break;
            default:
                break;
        }
        return harmonicHistoryData;
    }

    private Float max(Float ding,Float a){
        if(Objects.isNull(ding)){
            ding = a;
        }
        if(a>ding){
            ding = a;
        }
        return  ding;
    }

    private Float min(Float ding,Float a){
        if(Objects.isNull(ding)){
            ding = a;
        }
        if(a<ding){
            ding = a;
        }
        return  ding;
    }
    //电压
    private List<HarmonicHistoryData> ztHarmonicHistoryV(HarmonicHistoryParam historyParam) {
        String id = historyParam.getLineId();
        String starTime = historyParam.getStartTime();
        String endTime = historyParam.getEndTime();
        String key = "a1a69c93c11e4910aa247087c261bec5";
        String secret = "038de3c27cc54489862d181470e3ad92";
        String url = "http://25.37.90.72/ast/ydxxcjxt/dws/get_e_mp_TGvol_zl_ds";
        String apiId = "0644f1c6abd65d3a3a81eb3314390e14";
        String apiName = "电能质量谐波监测系统_分布式光伏台区电压日数据_e_mp_TGvol_zl_时间";
        List<HarmonicHistoryV> harmonicHistory = adsDiList(HarmonicHistoryV.class, id, starTime, endTime, key, secret, url, apiId, apiName);
        return ztDataV(harmonicHistory);
    }
    //1:有功 0:无功
    private List<HarmonicHistoryData> ztHarmonicHistoryP(HarmonicHistoryParam historyParam,Integer type) {
        String id = historyParam.getLineId();
        String starTime = historyParam.getStartTime();
        String endTime = historyParam.getEndTime();
        String key = "a1a69c93c11e4910aa247087c261bec5";
        String secret = "038de3c27cc54489862d181470e3ad92";
        String url = "http://25.37.90.72/ast/ydxxcjxt/dws/get_e_mp_TGpower_zl_ds";
        String apiId = "f9f0eb9627410c0ad4a66ae33a75e2c9";
        String apiName = "get_电能质量谐波监测系统_分布式光伏台区功率日数据_e_mp_TGpower_zl_时间";
        List<HarmonicHistoryP> harmonicHistory = adsDiList(HarmonicHistoryP.class, id, starTime, endTime, key, secret, url, apiId, apiName);
        return ztDataP(harmonicHistory,type);
    }
    //功率因数
    private List<HarmonicHistoryData> ztHarmonicHistoryC(HarmonicHistoryParam historyParam,Integer type) {
        String id = historyParam.getLineId();
        String starTime = historyParam.getStartTime();
        String endTime = historyParam.getEndTime();
        String key = "a1a69c93c11e4910aa247087c261bec5";
        String secret = "038de3c27cc54489862d181470e3ad92";
        String url = "http://25.37.90.72/ast/ydxxcjxt/dws/get_e_mp_TGfactor_zl_ds";
        String apiId = "bf6cc99505f93c355baad9926b61f17e";
        String apiName = "get_电能质量谐波监测系统_分布式光伏台区功率因数日数据_e_mp_TGfactor_zl_时间";
        List<HarmonicHistoryC> harmonicHistory = adsDiList(HarmonicHistoryC.class, id, starTime, endTime, key, secret, url, apiId, apiName);
        return ztDataC(harmonicHistory,type);
    }

    /**
     * @Description: 河北华云中台远程访问信息
     * @return: java.util.List<com.njcn.harmonic.pojo.po.HarmonicHistory>
     * @Author: wr
     * @Date: 2024/1/15 10:20
     */
    private  <T> List<T>  adsDiList(Class<T> t,String id, String starTime, String endTime,String key,String secret, String url,String apiId,String apiName) {
        List<T> aas = new ArrayList<>();
        Request request = new Request();
        CloseableHttpClient client = null;
        try {
            request.setKey(key);
            request.setSecret(secret);
            //接口访问类型
            request.setMethod("GET");
            //接口访问url
            request.setUrl(url);
            //API中 header头传输的参数
            request.addHeader("x-api-id", apiId);
            //API中 Query传输的参数
            request.addQueryStringParam("tg_id", id);
            request.addQueryStringParam("startTime", starTime);
            request.addQueryStringParam("endTime",endTime);
            //API中 Body体参数
            //request.setBody("demo");
        } catch (Exception e) {
            log.error(Thread.currentThread().getName() + "链接" + apiName + "失败");
            e.printStackTrace();
        }
        try {
            HttpRequestBase signedRequest = Client.sign(request);
            Header[] authorization = signedRequest.getHeaders("Authorization");
            signedRequest.addHeader("x-Authorization", authorization[0].getValue());

            //Send the request.
            client = HttpClients.custom().build();
            HttpResponse response = client.execute(signedRequest);

            //Print the status line of the response.
            log.info(response.getStatusLine().toString());

            //Print the header fields of the response.
            Header[] resHeaders = response.getAllHeaders();
            for (Header h : resHeaders) {
                log.info(h.getName() + ":" + h.getValue());
            }

            //Print the body of the response.
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String s = EntityUtils.toString(resEntity, "UTF-8");
                log.info(System.getProperty("line.separator") + s);
                JSONObject jsonObject = JSON.parseObject(s);
                String errCode = jsonObject.getString("errCode");
                if(StrUtil.isBlank(errCode)){
                    Map data = jsonObject.getObject("data", Map.class);
                    aas = JSONArray.parseArray(data.get("data").toString(), t);
                    log.info(Thread.currentThread().getName() + "获取日报表数据多少条 adsDiList：" + aas.size() + "结束----！");
                }else if("DLM.4094".equals(errCode)){
                    log.info(Thread.currentThread().getName() + "数据链接超时" + s + "结束----！");
                }

            }
        } catch (Exception e) {
            log.error(Thread.currentThread().getName() + "链接" + apiName + "失败");
            e.printStackTrace();
        } finally {
            try {
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return aas;
    }

    /**
     * @Description: 中台电压信息格式转换
     * @param value
     * @return: java.util.List<com.njcn.influx.pojo.bo.HarmonicHistoryData>
     * @Author: wr
     * @Date: 2024/1/22 15:25
     */
    private  List<HarmonicHistoryData> ztDataV(List<HarmonicHistoryV> value) {
        List<HarmonicHistoryData> info=new ArrayList<>();
        HarmonicHistoryData d;
        //a
        List<HarmonicHistoryV> a = value.stream().filter(x -> x.getPhase_flag() == 1).distinct().collect(Collectors.toList());
        //b
        List<HarmonicHistoryV> b = value.stream().filter(x -> x.getPhase_flag() == 2).distinct().collect(Collectors.toList());
        //c
        List<HarmonicHistoryV> c = value.stream().filter(x -> x.getPhase_flag() == 3).distinct().collect(Collectors.toList());
        Integer num=97;
        //15分钟增加信息
        Duration duration = Duration.ofMinutes(15);
        //初始化是从0点开始，23:45结束
        //A相
        if(CollUtil.isNotEmpty(a)){
            for (HarmonicHistoryV harmonicHistoryV : a) {
                String ds = harmonicHistoryV.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    //A相
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("A");
                    d.setAValue(reflectDataV(harmonicHistoryV,"u"+i));
                    info.add(d);
                }
            }
        }
        //B相
        if(CollUtil.isNotEmpty(b)){
            for (HarmonicHistoryV harmonicHistoryV : b) {
                String ds = harmonicHistoryV.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("B");
                    d.setAValue(reflectDataV(harmonicHistoryV,"u"+i));
                    info.add(d);
                }

            }
        }
        //C相
        if(CollUtil.isNotEmpty(c)){
            for (HarmonicHistoryV harmonicHistoryV : c) {
                String ds = harmonicHistoryV.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("C");
                    d.setAValue(reflectDataV(harmonicHistoryV,"u"+i));
                    info.add(d);
                }

            }
        }
        return info;
    }

    private static Float reflectDataV(HarmonicHistoryV dateV, String attribute){
        Field field;
        try {
            field = dateV.getClass().getDeclaredField(attribute);
            field.setAccessible(true);
            Float aFloat = (Float) field.get(dateV);
            if(ObjectUtil.isNotNull(aFloat)){
                return aFloat;
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return 0.0F;
    }

    /**
     * 中台功率信息格式转换
     * @param value
     * @param type
     * @return
     */
    private  List<HarmonicHistoryData> ztDataP(List<HarmonicHistoryP> value,Integer type) {
        List<HarmonicHistoryData> info=new ArrayList<>();
        HarmonicHistoryData d;
        //a
        List<HarmonicHistoryP> a= new ArrayList<>();
        //b
        List<HarmonicHistoryP> b= new ArrayList<>();
        //c
        List<HarmonicHistoryP> c = new ArrayList<>();
        //1:三相有功
        if(type==1){
            a = value.stream().filter(x -> x.getData_type() == 2).distinct().collect(Collectors.toList());
            b = value.stream().filter(x -> x.getData_type() == 3).distinct().collect(Collectors.toList());
            c = value.stream().filter(x -> x.getData_type() == 4).distinct().collect(Collectors.toList());
        }
        //2:三相无功
        if(type==2){
            a = value.stream().filter(x -> x.getData_type() == 6).distinct().collect(Collectors.toList());
            b = value.stream().filter(x -> x.getData_type() == 7).distinct().collect(Collectors.toList());
            c = value.stream().filter(x -> x.getData_type() == 8).distinct().collect(Collectors.toList());
        }
        //3:总有功
        if(type==3){
            a = value.stream().filter(x -> x.getData_type() == 1).distinct().collect(Collectors.toList());
        }
        //4:总无功
        if(type==4){
            a = value.stream().filter(x -> x.getData_type() == 5).distinct().collect(Collectors.toList());
        }

        Integer num=97;
        //15分钟增加信息
        Duration duration = Duration.ofMinutes(15);
        //初始化是从0点开始，23:45结束
        //A相
        if(CollUtil.isNotEmpty(a)){
            for (HarmonicHistoryP harmonicHistoryP : a) {
                String ds = harmonicHistoryP.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    //A相
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("A");
                    d.setAValue(reflectDataP(harmonicHistoryP,"p"+i));
                    info.add(d);
                }
            }
        }
        //B相
        if(CollUtil.isNotEmpty(b)){
            for (HarmonicHistoryP harmonicHistoryP : b) {
                String ds = harmonicHistoryP.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("B");
                    d.setAValue(reflectDataP(harmonicHistoryP,"p"+i));
                    info.add(d);
                }

            }
        }
        //C相
        if(CollUtil.isNotEmpty(c)){
            for (HarmonicHistoryP harmonicHistoryP : c) {
                String ds = harmonicHistoryP.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("C");
                    d.setAValue(reflectDataP(harmonicHistoryP,"p"+i));
                    info.add(d);
                }

            }
        }
        return info;
    }

    private static Float reflectDataP(HarmonicHistoryP dateP, String attribute) {
        Field field;
        try {
            field = dateP.getClass().getDeclaredField(attribute);
            field.setAccessible(true);
            Float aFloat = (Float) field.get(dateP);
            if(ObjectUtil.isNotNull(aFloat)){
                return aFloat;
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        return 0.0F;
    }

    /**
     * 中台功率因数信息格式转换
     * @param value
     * @return
     */
    private  List<HarmonicHistoryData> ztDataC(List<HarmonicHistoryC> value,Integer type) {
        List<HarmonicHistoryData> info=new ArrayList<>();
        HarmonicHistoryData d;
        //a
        List<HarmonicHistoryC> a= new ArrayList<>();
        //b
        List<HarmonicHistoryC> b= new ArrayList<>();
        //c
        List<HarmonicHistoryC> c = new ArrayList<>();
        //1:视在功率因数
        if(type==1){
            a = value.stream().filter(x -> x.getPhase_flag() == 1).distinct().collect(Collectors.toList());
            b = value.stream().filter(x -> x.getPhase_flag() == 2).distinct().collect(Collectors.toList());
            c = value.stream().filter(x -> x.getPhase_flag() == 3).distinct().collect(Collectors.toList());
        }
        //2:总视在功率因数
        if(type==2){
            a = value.stream().filter(x -> x.getPhase_flag() == 0).distinct().collect(Collectors.toList());
        }

        Integer num=97;
        //15分钟增加信息
        Duration duration = Duration.ofMinutes(15);
        //初始化是从0点开始，23:45结束
        //A相
        if(CollUtil.isNotEmpty(a)){
            for (HarmonicHistoryC harmonicHistoryC : a) {
                String ds = harmonicHistoryC.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    //A相
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("A");
                    d.setAValue(reflectDataC(harmonicHistoryC,"c"+i));
                    info.add(d);
                }
            }
        }
        //B相
        if(CollUtil.isNotEmpty(b)){
            for (HarmonicHistoryC harmonicHistoryC : b) {
                String ds = harmonicHistoryC.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("B");
                    d.setAValue(reflectDataC(harmonicHistoryC,"c"+i));
                    info.add(d);
                }

            }
        }
        //C相
        if(CollUtil.isNotEmpty(c)){
            for (HarmonicHistoryC harmonicHistoryC : c) {
                String ds = harmonicHistoryC.getDs();
                LocalDateTime parse = LocalDateTimeUtil.parse(ds, DatePattern.PURE_DATE_PATTERN);
                for (Integer i = 1; i < num; i++) {
                    d=new HarmonicHistoryData();
                    if(i>1){
                        parse = parse.plus(duration);
                    }
                    d.setTimeId(parse.toInstant(ZoneOffset.UTC));
                    d.setPhasicType("C");
                    d.setAValue(reflectDataC(harmonicHistoryC,"c"+i));
                    info.add(d);
                }

            }
        }
        return info;
    }

    private static Float reflectDataC(HarmonicHistoryC dateC, String attribute) {
        Field field;
        try {
            field = dateC.getClass().getDeclaredField(attribute);
            field.setAccessible(true);
            Float aFloat = (Float) field.get(dateC);
            if(ObjectUtil.isNotNull(aFloat)){
                return aFloat;
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        return 0.0F;
    }
}
