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.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.constant.BizParamConstant;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.param.StatisticsBizBaseParam;
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.enums.HarmonicResponseEnum;
import com.njcn.harmonic.mapper.*;
import com.njcn.harmonic.pojo.QueryResultLimitVO;
import com.njcn.harmonic.pojo.param.HistoryHarmParam;
import com.njcn.harmonic.pojo.param.HistoryParam;
import com.njcn.harmonic.pojo.param.NormHistoryParam;
import com.njcn.harmonic.pojo.po.RStatDataVD;
import com.njcn.harmonic.pojo.po.day.*;
import com.njcn.harmonic.pojo.vo.AssessEvaluation;
import com.njcn.harmonic.pojo.vo.EventDetailVO;
import com.njcn.harmonic.pojo.vo.HistoryDataResultVO;
import com.njcn.harmonic.pojo.vo.StatHarmonicOrgVO;
import com.njcn.harmonic.common.mapper.RStatDataHarmRateVDMapper;
import com.njcn.harmonic.common.mapper.RStatDataIDMapper;
import com.njcn.harmonic.common.mapper.RStatDataVDMapper;
import com.njcn.harmonic.service.HistoryResultService;
import com.njcn.influx.imapper.CommonMapper;
import com.njcn.influx.imapper.DataHarmRateVMapper;
import com.njcn.influx.imapper.DataIMapper;
import com.njcn.influx.pojo.bo.HarmonicHistoryData;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.influx.pojo.dto.HarmData;
import com.njcn.influx.pojo.dto.HarmHistoryDataDTO;
import com.njcn.influx.pojo.po.DataHarmRateV;
import com.njcn.influx.pojo.po.DataI;
import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.pojo.po.DictData;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.dto.DeptDTO;
import com.njcn.web.utils.WebUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author denghuajun
 * @date 2022/3/14
 */
@Slf4j
@Service
@AllArgsConstructor
public class HistoryResultServiceImpl implements HistoryResultService {

    private final EventDetailFeignClient eventDetailFeignClient;

    private final DeptFeignClient deptFeignClient;

    private final StatHarmonicOrgYMapper statHarmonicOrgYMapper;

    private final StatHarmonicOrgQMapper statHarmonicOrgQMapper;

    private final StatHarmonicOrgMMapper statHarmonicOrgMMapper;

    private final StatHarmonicOrgDMapper statHarmonicOrgDMapper;

    private final CommonMapper commonMapper;

    private final DataIMapper dataIMapper;

    private final DataHarmRateVMapper dataHarmRateVMapper;

    private final CommTerminalGeneralClient commTerminalGeneralClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final RStatDataIDMapper dataIDMapper;
    private final RStatDataVDMapper dataVDMapper;
    private final RStatDataHarmRateVDMapper dataHarmRateVDMapper;
    private final RStatDataHarmRateIDMapper dataHarmRateIDMapper;
    @Autowired
    @Qualifier("asyncExecutor")
    private Executor asyncExecutor;


    @Override
    public List<HistoryDataResultVO> getHistoryResult(HistoryParam historyParam) {
        System.out.println("begin============================="+ LocalDateTime.now());
        TimeInterval timeInterval = new TimeInterval();
        List<HistoryDataResultVO> historyDataResultVOList = new ArrayList<>();
        //获取监测点
        String[] points = historyParam.getLineId();

        for (int i = 0; i < points.length; i++) {
            long a = timeInterval.intervalMs();

            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);
                }
            }

            //获取监测点的数据单位，kV还是v  kW还是w
            PqsDeviceUnit pqsDeviceUnit = commTerminalGeneralClient.lineUnitDetail(points[i]).getData();
            //获取监测点信息
            LineDevGetDTO lineDetailDataVO = commTerminalGeneralClient.getMonitorDetail(points[i]).getData();
            //获取限值
            Overlimit overlimit = commTerminalGeneralClient.getOverLimitData(points[i]).getData();
            long b = timeInterval.intervalMs();
            System.out.println("feign调用："+(b-a));
            //获取指标
            String[] contions = historyParam.getCondition();
            List<CompletableFuture<Void>> futures = new ArrayList<>();
            for (int j = 0; j < contions.length; j++) {
                Integer number = 0;

                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();
                }
                //每个指标独立一个线程去查库，针对现场网络环境比较复杂的场景，正常场景看不太出来效果
                asyncMethodWithCustomExecutor(j,contions[j],number,historyParam,eventDetailVOList,points[i],pqsDeviceUnit,lineDetailDataVO,overlimit,historyDataResultVOList,futures);
            }
            // 等待所有任务完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        }
        historyDataResultVOList.sort(Comparator.comparing(HistoryDataResultVO::getSort));
        System.out.println("end============================="+LocalDateTime.now());
        System.out.println("共计耗时："+timeInterval.intervalMs()/1000.0);

        return historyDataResultVOList;
    }


    //处理指标查询
    public void asyncMethodWithCustomExecutor(Integer sort,String target,Integer number,HistoryParam historyParam,List<EventDetailVO> eventDetailVOList,String point,PqsDeviceUnit pqsDeviceUnit,LineDevGetDTO lineDetailDataVO,Overlimit overlimit,List<HistoryDataResultVO> historyDataResultVOList,List<CompletableFuture<Void>> futures) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            HistoryDataResultVO historyDataResultVO = getCondition(historyParam.getSearchBeginTime(), historyParam.getSearchEndTime(), point, target, number, historyParam.getValueType(), historyParam.getPtType(),pqsDeviceUnit,lineDetailDataVO,overlimit);
            historyDataResultVO.setEventDetail(eventDetailVOList);
            historyDataResultVO.setSort(sort);
            synchronized (historyDataResultVOList) { // 同步块保证线程安全
                historyDataResultVOList.add(historyDataResultVO);
            }
            System.out.println("执行异步任务，线程名：" + Thread.currentThread().getName());
        }, asyncExecutor);
        futures.add(future);
    }

    @Override
    public List<HistoryDataResultVO> getHistoryLineData(NormHistoryParam normHistoryParam) {
        List<HistoryDataResultVO> historyDataResultVOList = new ArrayList<>();
        HistoryDataResultVO historyDataResultVO = getNormCondition(normHistoryParam);
        historyDataResultVOList.add(historyDataResultVO);
        return historyDataResultVOList;
    }

    /**
     * influxDB相关操作
     * 查询稳态数据分析
     */
    @SneakyThrows
    public HistoryDataResultVO getCondition(String startTime, String endTime, String lineId, String contion, Integer number, Integer valueType, Integer ptType,PqsDeviceUnit pqsDeviceUnit,LineDevGetDTO lineDetailDataVO,Overlimit overlimit) {
        HistoryDataResultVO historyDataResultVO = new HistoryDataResultVO();
        QueryResultLimitVO queryResultLimitVO = getQueryResult(startTime, endTime, lineId, contion, number, valueType, ptType,pqsDeviceUnit,lineDetailDataVO,overlimit);
        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 {
            return historyDataResultVO;
        }
        return historyDataResultVO;
    }


    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 QueryResultLimitVO getQueryResult(String startTime, String endTime, String lineId, String contion, Integer number, Integer valueType, Integer ptType,PqsDeviceUnit pqsDeviceUnit,LineDevGetDTO lineDetailDataVO,Overlimit overlimit) {
        QueryResultLimitVO queryResultLimitVO = new QueryResultLimitVO();
        if (!lineId.isEmpty()) {
            Float topLimit = 0f;
            Float lowerLimit = 0f;

            if (Objects.isNull(overlimit)) {
                //对配网没有限值的统一处理
                DictData dictData = dicDataFeignClient.getDicDataById(lineDetailDataVO.getVoltageLevel()).getData();
                float voltageLevel = Float.parseFloat(dictData.getValue());
                float shortVal = COverlimitUtil.getDlCapByVoltageLevel(voltageLevel);
                float devVal = COverlimitUtil.getDefaultDevCapacity(voltageLevel);
                overlimit = COverlimitUtil.globalAssemble(voltageLevel, devVal, devVal, shortVal, 1, 0);
            }

            //组装sql语句
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(InfluxDBTableConstant.TIME + " >= '").append(startTime).append(InfluxDBTableConstant.START_TIME).append("' and ").append(InfluxDBTableConstant.TIME).append(" <= '").append(endTime).append(InfluxDBTableConstant.END_TIME).append("' and (");
            //sql语句
            stringBuilder.append(InfluxDBTableConstant.LINE_ID + "='").append(lineId).append("')");
            String valueTypeName = "";
            switch (valueType) {
                case 1:
                    valueTypeName = "AVG";
                    break;
                case 2:
                    valueTypeName = "MIN";
                    break;
                case 3:
                    valueTypeName = "MAX";
                    break;
                case 4:
                    valueTypeName = "CP95";
                    break;
                default:
                    break;
            }
            if (!Integer.valueOf(contion).equals(60) && !Integer.valueOf(contion).equals(61) && !Integer.valueOf(contion).equals(62)) {
                stringBuilder.append(" and ").append(InfluxDBTableConstant.VALUE_TYPE + "='").append(valueTypeName).append("'");
            }
            String sql = "";
            List<String> phasicType = new ArrayList<>();
            List<String> unit = new ArrayList<>();
            String targetName = "";
            switch (Integer.parseInt(contion)) {
                case 10:
                    //相电压有效值
                    sql = "SELECT time as time, rms as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getPhaseVoltage());
                    targetName = "相电压有效值";
                    break;
                case 11:
                    //线电压有效值
                    sql = "SELECT time as time, rms_lvr as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + "  FROM data_v WHERE " + stringBuilder +
                            " and (phasic_type ='A'  or phasic_type ='B' or phasic_type ='C')order by time asc tz('Asia/Shanghai');";
                    phasicType.add("AB相");
                    phasicType.add("BC相");
                    phasicType.add("CA相");
                    unit.add(pqsDeviceUnit.getLineVoltage());
                    targetName = "线电压有效值";
                    break;
                case 12:
                    //电压偏差
                    sql = "SELECT time as time, vu_dev as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + "  FROM data_v WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    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:
                    //三相电压不平衡度
                    sql = "SELECT time as time, v_unbalance as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + "  FROM data_v WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    topLimit = overlimit.getUbalance();
                    phasicType.add("三相电压不平衡度");
                    unit.add("%");
                    targetName = "三相电压不平衡度";
                    break;
                case 14:
                    //电压不平衡
                    sql = "SELECT time as time, v_zero as aValue, v_pos as bValue, v_neg as cValue  ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder +
                            " and (phasic_type ='T') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("零序电压");
                    phasicType.add("正序电压");
                    phasicType.add("负序电压");
                    unit.add(pqsDeviceUnit.getNoPositiveV());
                    unit.add(pqsDeviceUnit.getPositiveV());
                    unit.add(pqsDeviceUnit.getNoPositiveV());
                    targetName = "电压不平衡";
                    break;
                case 15:
                    //电压总谐波畸变率
                    sql = "SELECT time as time, v_thd as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + "  FROM data_v WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    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:
                    //电流有效值
                    sql = "SELECT time as time, rms as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("A");
                    targetName = "电流有效值";
                    break;
                case 21:
                    //电流总畸变率
                    sql = "SELECT time as time, i_thd as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("%");
                    targetName = "电流总谐波畸变率";
                    break;
                case 22:
                    //负序电流
                    sql = "SELECT time as time, i_neg as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    topLimit = overlimit.getINeg();
                    phasicType.add("负序电流");
                    unit.add("A");
                    targetName = "负序电流";
                    break;
                case 30:
                    //频率 V9暂时代表Freq
                    sql = "SELECT time as time, freq as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    topLimit = 50 + overlimit.getFreqDev();
                    lowerLimit = 50 - overlimit.getFreqDev();
                    phasicType.add("频率");
                    unit.add("Hz");
                    targetName = "频率";
                    break;
                case 40:
                    //谐波电压含有率
                    if (number == 1) {
                        targetName = "基波电压幅值";
                        //修改幅值表
                        sql = "SELECT time as time, v_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        unit.add(pqsDeviceUnit.getPhaseVoltage());
                    } else {
                        targetName = "谐波电压含有率";
                        sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmrate_v WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        if (number < 26) {
                            topLimit = PubUtils.getValueByMethod(overlimit, "getUharm", number);
                        }
                        unit.add("%");
                    }
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }


                    break;
                case 41:
                    //谐波电流含有率
                    if (number == 1) {
                        targetName = "谐波电流幅值";
                        sql = "SELECT time as time, i_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmrate_i WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";

                        unit.add("A");
                    } else {
                        targetName = "谐波电流含有率";
                        sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmrate_i WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        unit.add("%");
                    }
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");


                    break;
                case 42:
                    //谐波电压幅值
                    if (number == 1) {
                        sql = "SELECT time as time, v_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    } else {
                        sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_v WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    }
                    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());
                        targetName = "基波电压幅值";

                    } else {
                        unit.add("V");
                        targetName = "谐波电压幅值";

                    }
                    break;
                case 43:
                    //谐波电流幅值
                    if (number == 1) {
                        sql = "SELECT time as time, i_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        targetName = "基波电流幅值";

                    } else {
                        sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_i WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        if (number < 26) {
                            topLimit = PubUtils.getValueByMethod(overlimit, "getIharm", number);
                        }
                        targetName = "谐波电流幅值";

                    }
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("A");
                    break;
                case 44:
                    //谐波电压相角
                    if (number == 1) {
                        targetName = "基波电压相角";

                        sql = "SELECT time as time, v_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_v WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    } else {
                        targetName = "谐波电压相角";
                        sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_v WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    }
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    unit.add("°");
                    break;
                case 45:
                    //谐波电流相角
                    if (number == 1) {
                        sql = "SELECT time as time, i_1 as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_i WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        targetName = "基波电流相角";

                    } else {
                        sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmphasic_i WHERE " + stringBuilder +
                                " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                        targetName = "谐波电流相角";

                    }
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("°");
                    break;
                case 46:
                    //间谐波电压含有率
                    sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_v WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    if(number<17){
                        topLimit = PubUtils.getValueByMethod(overlimit, "getInuharm", number);
                    }else {
                        topLimit = 0.0f;
                    }
                    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:
                    //间谐波电流含有率
                    sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_i WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("%");
                    targetName = "间谐波电流含有率";
                    break;
                case 48:
                    //间谐波电压幅值
                    sql = "SELECT time as time, v_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_v WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    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:
                    //间谐波电流幅值
                    sql = "SELECT time as time, i_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_inharm_i WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add("A");
                    targetName = "间谐波电流幅值";
                    break;
                case 50:
                    //谐波有功功率
                    sql = "SELECT time as time, p_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getFundActiveP());
                    } else {
                        unit.add("W");
                    }
                    targetName = "谐波有功功率";
                    break;
                case 51:
                    //谐波无功功率
                    sql = "SELECT time as time, q_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_q WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getTotalNoP());
                    } else {
                        unit.add("Var");
                    }
                    targetName = "谐波无功功率";
                    break;
                case 52:
                    //谐波视在功率
                    sql = "SELECT time as time, s_" + number + " as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_s WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    if (number == 1) {
                        unit.add(pqsDeviceUnit.getTotalViewP());
                    } else {
                        unit.add("VA");
                    }
                    targetName = "谐波视在功率";
                    break;
                case 53:
                    //三相有功功率
                    sql = "SELECT time as time, p as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getTotalActiveP());
                    targetName = "三相有功功率";
                    break;
                case 54:
                    //三相无功功率
                    sql = "SELECT time as time, q as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_q WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getTotalNoP());
                    targetName = "三相无功功率";
                    break;
                case 55:
                    //三相视在功率
                    sql = "SELECT time as time, s as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_s WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    unit.add(pqsDeviceUnit.getTotalViewP());
                    targetName = "三相视在功率";
                    break;
                case 56:
                    //三相总有功功率
                    sql = "SELECT time as time, p as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    phasicType.add("三相总有功功率");
                    unit.add(pqsDeviceUnit.getTotalActiveP());
                    targetName = "三相总有功功率";
                    break;
                case 57:
                    //三相总无功功率
                    sql = "SELECT time as time, q as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_q WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    phasicType.add("三相总无功功率");
                    unit.add(pqsDeviceUnit.getTotalNoP());
                    targetName = "三相总无功功率";
                    break;
                case 58:
                    //三相总视在功率
                    sql = "SELECT time as time, s as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_s WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    phasicType.add("三相总视在功率");
                    unit.add(pqsDeviceUnit.getTotalViewP());
                    targetName = "三相总视在功率";
                    break;
                case 59:
                    //视在功率因数
                    sql = "SELECT time as time, pf as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') group by phasic_type order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    targetName = "视在功率因数";
                    break;
                case 591:
                    //位移功率因数
                    sql = "SELECT time as time, df as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    phasicType.add("A相");
                    phasicType.add("B相");
                    phasicType.add("C相");
                    targetName = "位移功率因数";
                    break;
                case 592:
                    //总视在功率因数
                    sql = "SELECT time as time, pf as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    phasicType.add("总视在功率因数");
                    targetName = "总视在功率因数";
                    break;
                case 593:
                    //总位移功率因数
                    sql = "SELECT time as time, df as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_harmpower_p WHERE " + stringBuilder +
                            " and phasic_type ='T' order by time asc tz('Asia/Shanghai');";
                    phasicType.add("总位移功率因数");
                    targetName = "总位移功率因数";
                    break;
                case 61:
                    //长时闪变
                    sql = "SELECT time as time, plt as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_plt WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    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:
                    //短时闪变
                    sql = "SELECT time as time, pst as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_flicker WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    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:
                    //电压波动
                    sql = "SELECT time as time, fluc as aValue ," + InfluxDBTableConstant.PHASIC_TYPE + " FROM data_fluc WHERE " + stringBuilder +
                            " and (phasic_type ='A' or phasic_type ='B' or phasic_type ='C') order by time asc tz('Asia/Shanghai');";
                    if (ptType == 0) {
                        phasicType.add("A相");
                        phasicType.add("B相");
                        phasicType.add("C相");
                    } else {
                        phasicType.add("AB相");
                        phasicType.add("BC相");
                        phasicType.add("CA相");
                    }
                    targetName = "电压波动";
                    unit.add("%");
                    break;
                default:
                    break;
            }
            //大致有3种类型
            //1、一次查询返回3条记录，分别为A/B/C三相的结果
            //2、一次查询返回一条记录，以T相为条件，返回某3个指标值
            //3、一次查询返回一条记录，以T相为条件，返回某1个指标值
            List<HarmonicHistoryData> harmonicHistoryData = commonMapper.getHistoryResult(sql);
            queryResultLimitVO.setHarmonicHistoryDataList(harmonicHistoryData);
            queryResultLimitVO.setTopLimit(topLimit);
            queryResultLimitVO.setLowerLimit(lowerLimit);
            queryResultLimitVO.setPhaiscType(phasicType);
            queryResultLimitVO.setUnit(unit);
            queryResultLimitVO.setLineName(lineDetailDataVO.getPointName());
            queryResultLimitVO.setHarmNum(number);
            queryResultLimitVO.setTargetName(targetName);
            queryResultLimitVO.setWiringMethod(lineDetailDataVO.getWiringMethod());
        } else {
            return queryResultLimitVO;
        }
        return queryResultLimitVO;
    }


    private QueryResultLimitVO getQueryNormDataResult(NormHistoryParam normHistoryParam) {
        QueryResultLimitVO queryResultLimitVO = new QueryResultLimitVO();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (!normHistoryParam.getLineId().isEmpty()) {
            Float topLimit = 0f;
            Float lowerLimit = 0f;
            String lineList = normHistoryParam.getLineId();
            String startTime = sdf.format(DateUtil.beginOfDay(DateUtil.parse(normHistoryParam.getSearchTime())));
            String endTime = sdf.format(DateUtil.endOfDay(DateUtil.parse(normHistoryParam.getSearchTime())));
            Integer valueType = normHistoryParam.getValueType();
            //获取限值
            Overlimit overlimit = commTerminalGeneralClient.getOverLimitData(lineList).getData();
            //获取监测点信息
            LineDevGetDTO lineDetailDataVO = commTerminalGeneralClient.getMonitorDetail(lineList).getData();
            //组装sql语句
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(InfluxDBTableConstant.TIME + " >= '").append(startTime).append("' and ").append(InfluxDBTableConstant.TIME).append(" <= '").append(endTime).append("' and (");
            //sql语句
            stringBuilder.append(InfluxDBTableConstant.LINE_ID + "='").append(lineList).append("')");
            String valueTypeName = "";
            String phasicType = "";
            switch (valueType) {
                case 1:
                    valueTypeName = "AVG";
                    break;
                case 2:
                    valueTypeName = "MAX";
                    break;
                case 3:
                    valueTypeName = "MIN";
                    break;
                case 4:
                    valueTypeName = "CP95";
                    break;
                default:
                    break;
            }
            if ("A".equalsIgnoreCase(normHistoryParam.getPhaseType()) || "AB".equalsIgnoreCase(normHistoryParam.getPhaseType())) {
                phasicType = "A";
            } else if ("B".equalsIgnoreCase(normHistoryParam.getPhaseType()) || "BC".equalsIgnoreCase(normHistoryParam.getPhaseType())) {
                phasicType = "B";
            } else if ("C".equalsIgnoreCase(normHistoryParam.getPhaseType()) || "CA".equalsIgnoreCase(normHistoryParam.getPhaseType())) {
                phasicType = "C";
            }
            if (Integer.parseInt(normHistoryParam.getTargetCode()) != 60 || Integer.parseInt(normHistoryParam.getTargetCode()) != 61 || Integer.parseInt(normHistoryParam.getTargetCode()) != 62) {
                stringBuilder.append(" and ").append(InfluxDBTableConstant.VALUE_TYPE + "='").append(valueTypeName).append("'");
            }
            if (StrUtil.isNotBlank(phasicType)) {
                stringBuilder.append(" and ").append("phasic_type ='").append(phasicType).append("'");

            }
            String sql = "";
            List<String> unit = new ArrayList<>();
            Integer number = normHistoryParam.getNumber();
            String targetName = "";
            switch (Integer.parseInt(normHistoryParam.getTargetCode())) {
                case 12:
                    //电压偏差
                    sql = "SELECT time as time, vu_dev as aValue FROM data_v WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = overlimit.getVoltageDev();
                    lowerLimit = overlimit.getUvoltageDev();
                    unit.add("%");
                    targetName = "电压偏差";
                    break;
                case 13:
                    //三相电压不平衡度
                    sql = "SELECT time as time, v_unbalance as aValue FROM data_v WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = overlimit.getUbalance();
                    unit.add("%");
                    targetName = "三相电压不平衡度";
                    break;
                case 15:
                    //电压总谐波畸变率
                    sql = "SELECT time as time, v_thd as aValue FROM data_v WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = overlimit.getUaberrance();
                    unit.add("%");
                    targetName = "电压总谐波畸变率";
                    break;
                case 22:
                    //负序电流
                    sql = "SELECT time as time, i_neg as aValue FROM data_i WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = overlimit.getINeg();
                    unit.add("A");
                    targetName = "负序电流";
                    break;
                case 30:
                    //频率 V9暂时代表Freq
                    sql = "SELECT time as time, freq as aValue FROM data_v WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = 50 + overlimit.getFreqDev();
                    lowerLimit = 50 - overlimit.getFreqDev();
                    unit.add("Hz");
                    targetName = "频率";
                    break;
                case 40:
                    //谐波电压含有率
                    sql = "SELECT time as time, v_" + number + " as aValue FROM data_harmrate_v WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = PubUtils.getValueByMethod(overlimit, "getUharm", number);
                    unit.add("%");
                    targetName = "谐波电压含有率";
                    break;
                case 41:
                    //谐波电流含有率
                    sql = "SELECT time as time, i_" + number + " as aValue FROM data_harmrate_i WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    unit.add("%");
                    targetName = "谐波电流含有率";
                    break;
                case 43:
                    //谐波电流幅值
                    sql = "SELECT time as time, i_" + number + " as aValue FROM data_i WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = PubUtils.getValueByMethod(overlimit, "getIharm", number);
                    unit.add("A");
                    targetName = "谐波电流幅值";
                    break;

                case 46:
                    //间谐波电压含有率
                    sql = "SELECT time as time, v_" + number + " as aValue FROM data_inharm_v WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    topLimit = PubUtils.getValueByMethod(overlimit, "getInuharm", number);
                    unit.add("%");
                    targetName = "间谐波电压含有率";
                    break;
                case 61:
                    //长时闪变
                    sql = "SELECT time as time, plt as aValue FROM data_plt WHERE " + stringBuilder +
                            " order by time asc tz('Asia/Shanghai');";
                    targetName = "长时闪变";
                    topLimit = overlimit.getFlicker();
                    break;
                default:
                    break;
            }
            List<HarmonicHistoryData> harmonicHistoryData = commonMapper.getHistoryResult(sql);
            queryResultLimitVO.setHarmonicHistoryDataList(harmonicHistoryData);
            queryResultLimitVO.setTopLimit(topLimit);
            queryResultLimitVO.setLowerLimit(lowerLimit);
            queryResultLimitVO.setPhaiscType(Collections.singletonList(phasicType));
            queryResultLimitVO.setUnit(unit);
            queryResultLimitVO.setLineName(lineDetailDataVO.getPointName());
            queryResultLimitVO.setHarmNum(number);
            queryResultLimitVO.setTargetName(targetName);
        } else {
            return queryResultLimitVO;
        }
        return queryResultLimitVO;
    }

    /**
     * influxDB相关操作
     * 查询稳态数据分析
     */
    @SneakyThrows
    private HistoryDataResultVO getNormCondition(NormHistoryParam normHistoryParam) {
        HistoryDataResultVO historyDataResultVO = new HistoryDataResultVO();
        QueryResultLimitVO queryResultLimitVO = getQueryNormDataResult(normHistoryParam);
        BeanUtil.copyProperties(queryResultLimitVO, historyDataResultVO);
        //获取查询返回的结果集
        List<HarmonicHistoryData> harmonicHistoryDataList = queryResultLimitVO.getHarmonicHistoryDataList();
        List<Date> time = new ArrayList<>();
        List<Float> fValue = new ArrayList<>();
        List<List<Object>> objectListData = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(harmonicHistoryDataList)) {
            for (HarmonicHistoryData harmonicHistoryData : harmonicHistoryDataList) {
                time.add(new Date(harmonicHistoryData.getTime().toEpochMilli()));
                fValue.add(BigDecimal.valueOf(harmonicHistoryData.getAValue()).setScale(4, BigDecimal.ROUND_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));
                objectListData.add(objects);
            }
            historyDataResultVO.setTopLimit(queryResultLimitVO.getTopLimit());
            historyDataResultVO.setLowerLimit(queryResultLimitVO.getLowerLimit());
            historyDataResultVO.setValue(objectListData);
        } else {
            return historyDataResultVO;
        }
        return historyDataResultVO;
    }

    @Override
    public List<StatHarmonicOrgVO> getHarmonicProportion(StatisticsBizBaseParam statisticsBizBaseParam) {

        List<StatHarmonicOrgVO> statHarmonicOrgVOS = new ArrayList<>();
        //获取子部门
        List<DeptDTO> depts = deptFeignClient.getDeptDescendantIndexes(statisticsBizBaseParam.getId(), WebUtil.filterDeptType()).getData();

        if (depts.size() != 0) {
            //根据上层id，查询子数据并返回一个顺序流
            depts = depts.stream().filter(allItem -> allItem.getPid().equals(statisticsBizBaseParam.getId())).collect(Collectors.toList());
            //根据时间区分表查询
            //年 季 月 日
            switch (statisticsBizBaseParam.getType().toString()) {
                case BizParamConstant.STAT_BIZ_YEAR:
                    statHarmonicOrgVOS = statHarmonicOrgYMapper.listYearRatio(depts, statisticsBizBaseParam.getStartTime(), statisticsBizBaseParam.getEndTime());
                    break;
                case BizParamConstant.STAT_BIZ_QUARTER:
                    statHarmonicOrgVOS = statHarmonicOrgQMapper.listQuarterRatio(depts, statisticsBizBaseParam.getStartTime(), statisticsBizBaseParam.getEndTime());
                    break;
                case BizParamConstant.STAT_BIZ_MONTH:
                    statHarmonicOrgVOS = statHarmonicOrgMMapper.listMonthRatio(depts, statisticsBizBaseParam.getStartTime(), statisticsBizBaseParam.getEndTime());
                    break;
                case BizParamConstant.STAT_BIZ_DAY:
                    statHarmonicOrgVOS = statHarmonicOrgDMapper.listDayRatio(depts, statisticsBizBaseParam.getStartTime(), statisticsBizBaseParam.getEndTime());
                    break;
                default:
                    break;
            }
        }

        //使用流对象的方法插入name值
        if (statHarmonicOrgVOS.size() != 0) {
            statHarmonicOrgVOS = transName(statHarmonicOrgVOS, depts);
        }

        return statHarmonicOrgVOS;
    }

    @Override
    public HarmHistoryDataDTO getHistoryHarmData(HistoryHarmParam historyHarmParam) {
        List<HarmData> historyData;
        float overLimit;
        Overlimit overlimit = commTerminalGeneralClient.getOverLimitData(historyHarmParam.getLineId()).getData();
        //判断是电流还是电压谐波
        if (historyHarmParam.getType() == 0) {
            historyData = getIHistoryData(historyHarmParam);
            overLimit = PubUtils.getValueByMethod(overlimit, "getIharm", historyHarmParam.getTime());
        } else {
            historyData = getVHistoryData(historyHarmParam);
            overLimit = PubUtils.getValueByMethod(overlimit, "getUharm", historyHarmParam.getTime());
        }
        return new HarmHistoryDataDTO(historyData, overLimit);
    }

    @Override
    public AssessEvaluation getHarmIAndHarmVData(StatisticsBizBaseParam param) {
        String id = param.getId();
        String startTime = param.getStartTime();
        String endTime = param.getEndTime();
        List<RStatDataIDPO> rStatDataIDPOS = dataIDMapper.selectList(new LambdaQueryWrapper<RStatDataIDPO>()
                .eq(RStatDataIDPO::getLineId, id)
                .eq(RStatDataIDPO::getValueType,"CP95")
                .in(RStatDataIDPO::getPhaseType,Arrays.asList("A","B","C"))
                .ge(RStatDataIDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(RStatDataIDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );
        List<RStatDataVD> rStatDataVDS = dataVDMapper.selectList(new LambdaQueryWrapper<RStatDataVD>()
                .eq(RStatDataVD::getLineId, id)
                .eq(RStatDataVD::getValueType,"CP95")
                .in(RStatDataVD::getPhasicType,Arrays.asList("A","B","C"))
                .ge(RStatDataVD::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(RStatDataVD::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );
        List<RStatDataHarmrateVDPO> harmV = dataHarmRateVDMapper.selectList(new LambdaQueryWrapper<RStatDataHarmrateVDPO>()
                .eq(RStatDataHarmrateVDPO::getLineId, id)
                .eq(RStatDataHarmrateVDPO::getValueType,"CP95")
                .in(RStatDataHarmrateVDPO::getPhaseType,Arrays.asList("A","B","C"))
                .ge(RStatDataHarmrateVDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(RStatDataHarmrateVDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );

        List<RStatDataHarmrateIDPO> harmI = dataHarmRateIDMapper.selectList(new LambdaQueryWrapper<RStatDataHarmrateIDPO>()
                .eq(RStatDataHarmrateIDPO::getLineId, id)
                .eq(RStatDataHarmrateIDPO::getValueType,"CP95")
                .in(RStatDataHarmrateIDPO::getPhaseType,Arrays.asList("A","B","C"))
                .ge(RStatDataHarmrateIDPO::getTime, DateUtil.beginOfDay(DateUtil.parse(startTime)))
                .le(RStatDataHarmrateIDPO::getTime, DateUtil.endOfDay(DateUtil.parse(endTime)))
        );

        AssessEvaluation assessEvaluation=new AssessEvaluation();
        List<Double> iMax=new ArrayList<>();
        List<Double> uMax=new ArrayList<>();
        if(CollUtil.isNotEmpty(rStatDataIDPOS)&&CollUtil.isNotEmpty(rStatDataVDS)&&CollUtil.isNotEmpty(harmV)&&CollUtil.isNotEmpty(harmI)){
            Double iNeg = rStatDataIDPOS.stream().map(RStatDataIDPO::getINeg).max(Comparator.naturalOrder()).get();
            assessEvaluation.setINeg(iNeg);
            BigDecimal vUnbalance = rStatDataVDS.stream().map(RStatDataVD::getVUnbalance).max(Comparator.naturalOrder()).get();
            assessEvaluation.setUnbalance(vUnbalance.doubleValue());
            for (int i = 2; i < 51; i++) {
                uMax.add(reflectDataV(harmV,"v"+i).stream().max(Comparator.naturalOrder()).get());
                iMax.add(reflectDataI(harmI,"i"+i).stream().max(Comparator.naturalOrder()).get());
            }
            assessEvaluation.setIMax(iMax);
            assessEvaluation.setUMax(uMax);
        }else{
            return null;
        }
        return assessEvaluation;
    }

    private List<Double> reflectDataV(List<RStatDataHarmrateVDPO> harmVList,String attribute) {
        Field field;
        try {
            field = RStatDataHarmrateVDPO.class.getDeclaredField(attribute);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        field.setAccessible(true);
        return harmVList.stream().map(temp -> {
            Double o;
            try {
                o = (Double) field.get(temp);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            return o;
        }).collect(Collectors.toList());
    }

    private List<Double> reflectDataI(List<RStatDataHarmrateIDPO> harmIList,String attribute) {
        Field field;
        try {
            field = RStatDataHarmrateIDPO.class.getDeclaredField(attribute);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
        field.setAccessible(true);
        return harmIList.stream().map(temp -> {
            Double o;
            try {
                o = (Double) field.get(temp);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            return o;
        }).collect(Collectors.toList());
    }

    /***
     * 获取指定次数 监测点的历史谐波电流数据
     * @author hongawen
     * @date 2023/7/19 10:03
     */
    private List<HarmData> getIHistoryData(HistoryHarmParam historyHarmParam) {
        LineDevGetDTO lineDetailData = commTerminalGeneralClient.getMonitorDetail(historyHarmParam.getLineId()).getData();
        List<HarmData> historyData;
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class, HarmData.class);
        influxQueryWrapper
                .select(DataI::getTime)
                .max("i_" + historyHarmParam.getTime(), "value")
                .between(DataI::getTime, historyHarmParam.getSearchBeginTime().concat(" 00:00:00"), historyHarmParam.getSearchEndTime().concat(" 23:59:59"))
                .eq(DataI::getLineId, historyHarmParam.getLineId())
                .or(DataI::getPhaseType, Stream.of(InfluxDBTableConstant.PHASE_TYPE_A, InfluxDBTableConstant.PHASE_TYPE_B, InfluxDBTableConstant.PHASE_TYPE_C).collect(Collectors.toList()))
                //以时间分组时，需要加上时间间隔，比如此处需要加上监测点的采样间隔
                .groupBy("time(" + lineDetailData.getInterval() + "m)")
                .timeAsc();
        String string = influxQueryWrapper.generateSql();
        historyData = dataIMapper.getIHistoryData(string);
        if (CollectionUtils.isEmpty(historyData)) {
            //如果数据为空，则提示给用户暂无数据
            throw new BusinessException(HarmonicResponseEnum.NO_DATA);
        }
        //最新两条数据的间隔与监测点查出的间隔做对比，返回一个合理的间隔
        historyData = historyData.stream().filter(Objects::nonNull).collect(Collectors.toList());
        int lineInterval = getInterval(lineDetailData.getInterval(), PubUtils.instantToDate(historyData.get(historyData.size() - 1).getTime()), PubUtils.instantToDate(historyData.get(historyData.size() - 2).getTime()));
        historyData = dealHistoryData(historyData, lineInterval);
        if (CollectionUtils.isEmpty(historyData)) {
            //如果数据为空，则提示给用户暂无数据
            throw new BusinessException(HarmonicResponseEnum.NO_DATA);
        }
        //根据时间天数，获取理论上多少次用采数据
        List<String> dateStr = PubUtils.getTimes(DateUtil.beginOfDay(DateUtil.parse(historyHarmParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(historyHarmParam.getSearchEndTime())));
        int dueTimes = dateStr.size() * 1440 / lineInterval;
        int realTimes = historyData.size();
        if (dueTimes != realTimes) {
            //期待值与实际值不等，则提示用户时间范围内谐波数据完整性不足
            throw new BusinessException(HarmonicResponseEnum.INSUFFICIENCY_OF_INTEGRITY);
        }
        return historyData.stream().sorted(Comparator.comparing(HarmData::getTime)).collect(Collectors.toList());
    }

    /**
     * 获取谐波电压的数据
     * <p>
     * 因历史谐波表data_harmrate_v
     */
    private List<HarmData> getVHistoryData(HistoryHarmParam historyHarmParam) {
        LineDevGetDTO lineDetailData = commTerminalGeneralClient.getMonitorDetail(historyHarmParam.getLineId()).getData();
        List<HarmData> historyData;
        InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class, HarmData.class);
        influxQueryWrapper
                .select(DataHarmRateV::getTime)
                .max("v_" + historyHarmParam.getTime(), "value")
                .between(DataHarmRateV::getTime, historyHarmParam.getSearchBeginTime().concat(" 00:00:00"), historyHarmParam.getSearchEndTime().concat(" 23:59:59"))
                .eq(DataHarmRateV::getLineId, historyHarmParam.getLineId())
                .or(DataHarmRateV::getPhaseType, Stream.of(InfluxDBTableConstant.PHASE_TYPE_A, InfluxDBTableConstant.PHASE_TYPE_B, InfluxDBTableConstant.PHASE_TYPE_C).collect(Collectors.toList()))
                .groupBy("time(" + lineDetailData.getInterval() + "m)")
                .timeAsc();
        historyData = dataHarmRateVMapper.getHarmRateVHistoryData(influxQueryWrapper);
        if (CollectionUtils.isEmpty(historyData)) {
            //如果数据为空，则提示给用户暂无数据
            throw new BusinessException(HarmonicResponseEnum.NO_DATA);
        }
        historyData = historyData.stream().filter(Objects::nonNull).collect(Collectors.toList());
        int lineInterval = getInterval(lineDetailData.getInterval(), PubUtils.instantToDate(historyData.get(historyData.size() - 1).getTime()), PubUtils.instantToDate(historyData.get(historyData.size() - 2).getTime()));
        //最新两条数据的间隔与监测点查出的间隔做对比，返回一个合理的间隔
        historyData = dealHistoryData(historyData, lineInterval);
        if (CollectionUtils.isEmpty(historyData)) {
            //如果数据为空，则提示给用户暂无数据
            throw new BusinessException(HarmonicResponseEnum.NO_DATA);
        }
        //根据时间天数，获取理论上多少次用采数据
        List<String> dateStr = PubUtils.getTimes(DateUtil.beginOfDay(DateUtil.parse(historyHarmParam.getSearchBeginTime())), DateUtil.endOfDay(DateUtil.parse(historyHarmParam.getSearchEndTime())));
        int dueTimes = dateStr.size() * 1440 / lineInterval;
        int realTimes = historyData.size();
        if (dueTimes != realTimes) {
            //期待值与实际值不等，则提示用户时间范围内谐波数据完整性不足
            throw new BusinessException(HarmonicResponseEnum.INSUFFICIENCY_OF_INTEGRITY);
        }
        return historyData.stream().sorted(Comparator.comparing(HarmData::getTime)).collect(Collectors.toList());
    }

    /**
     * 使用流对象的方法插入数据
     */
    private static List<StatHarmonicOrgVO> transName(List<StatHarmonicOrgVO> statHarmonicOrgVOS, List<DeptDTO> deptDTOS) {
        List<StatHarmonicOrgVO> list = statHarmonicOrgVOS.stream().map(e1 -> {
            return deptDTOS.stream().filter(e2 -> {//条件判断
                return e1.getId().equals(e2.getId());
            }).map(e2 -> {
                if (e2.getType() == 0) {
                    e1.setName(e2.getArea());
                } else {
                    e1.setName(e2.getName());
                }
                return e1;//返回的结果
            }).collect(Collectors.toList());
        }).flatMap(List::stream).collect(Collectors.toList());//设置返回结果类型

        return list;
    }


    /**
     * 根据库中查询的数据，进行数据补齐操作
     *
     * @param beforeDeal 库中实际的历史谐波数据
     */
    private List<HarmData> dealHistoryData(List<HarmData> beforeDeal, int lineInterval) {
        List<HarmData> result = new ArrayList<>();
        try {
            if (CollectionUtils.isEmpty(beforeDeal)) {
                return result;
            } else {
                //先将查询数据按日进行收集
                Map<String/*yyyy-MM-dd的时间格式*/, Map<Date, HarmData>/*当前天的所有谐波数据*/> dayHistoryDatas = new HashMap<>();
                for (HarmData harmData : beforeDeal) {
                    Date time = PubUtils.instantToDate(harmData.getTime());
                    String date = DateUtil.format(time, DatePattern.NORM_DATE_PATTERN);
                    if (dayHistoryDatas.containsKey(date)) {
                        Map<Date, HarmData> harmDataMap = dayHistoryDatas.get(date);
                        harmDataMap.put(PubUtils.getSecondsAsZero(PubUtils.instantToDate(harmData.getTime())), harmData);
                        dayHistoryDatas.put(date, harmDataMap);
                    } else {
                        Map<Date, HarmData> harmDataMap = new HashMap<>();
                        harmDataMap.put(PubUtils.getSecondsAsZero(PubUtils.instantToDate(harmData.getTime())), harmData);
                        dayHistoryDatas.put(date, harmDataMap);
                    }
                }
                //将数据按日期处理后，开始进行完整性判断，满足完整性则进行补齐，否则返回空数据
                Set<String> days = dayHistoryDatas.keySet();
                for (String day : days) {
                    //获取出当天的历史谐波数据
                    Map<Date, HarmData> harmDataMap = dayHistoryDatas.get(day);
                    if (CollectionUtils.isEmpty(harmDataMap)) {
                        continue;
                    }
                    int dueTimes = 1440 / lineInterval;
                    int realTimes = harmDataMap.size();
                    double integrity = (double) realTimes / (double) dueTimes;
                    if (integrity < 0.9 || integrity >= 1.0) {
                        //完整性不足，则返回原数据
                        Set<Date> dates = harmDataMap.keySet();
                        for (Date time : dates) {
                            result.add(harmDataMap.get(time));
                        }
                    } else if (integrity < 1.0) {
                        //进行数据补齐,数据补齐需要根据监测点测量间隔,最好是MAP格式 map的key是yyyy-MM-dd HH:mm
                        List<HarmData> afterDeal = new ArrayList<>();
                        String timeTemp = day + " 00:00:00";
                        Date date = DateUtil.parse(timeTemp, DatePattern.NORM_DATETIME_PATTERN);
                        for (int i = 0; i < dueTimes; i++) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            calendar.add(Calendar.MINUTE, lineInterval * i);
                            HarmData temp = harmDataMap.get(calendar.getTime());
                            if (temp != null && temp.getValue() != null) {
                                afterDeal.add(temp);
                            } else {
                                //递归找到前面的值
                                Float preValue = getPreHarmValue(date, calendar.getTime(), harmDataMap, lineInterval);
                                //递归找到后面的值
                                Float appendValue = getAppendHarmValue(date, calendar.getTime(), harmDataMap, lineInterval);
                                HarmData harmData = new HarmData();
                                harmData.setTime(PubUtils.dateToInstant(calendar.getTime()));
                                //还需要判断前值和后值为空的情况
                                if (null == preValue && null == appendValue) {
                                    harmData.setValue(0.0f);
                                } else if (null == preValue) {
                                    harmData.setValue(appendValue);
                                } else if (null == appendValue) {
                                    harmData.setValue(preValue);
                                } else {
                                    harmData.setValue((preValue + appendValue) / 2);
                                }
                                afterDeal.add(harmData);
                            }
                        }
                        result.addAll(afterDeal);
                    }
                }
            }
        } catch (Exception e) {
            log.error("开始处理历史电压谐波数据失败，失败原因:{}", e.toString());
            throw new BusinessException(HarmonicResponseEnum.INSUFFICIENCY_OF_INTEGRITY);
        }
        return result;
    }


    /**
     * 递归找前值 谐波数据
     *
     * @param date       起始时间
     * @param time       当前事件
     * @param beforeDeal 处理前的数据
     */
    private Float getPreHarmValue(Date date, Date time, Map<Date, HarmData> beforeDeal, int interval) {
        Float result;
        if (date.getTime() >= time.getTime()) {
            return null;
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(time);
            interval = -interval;
            calendar.add(Calendar.MINUTE, interval);
            HarmData temp = beforeDeal.get(calendar.getTime());
            if (temp == null || temp.getValue() == null) {
                result = getPreHarmValue(date, calendar.getTime(), beforeDeal, Math.abs(interval));
            } else {
                result = temp.getValue();
            }
        }
        return result;
    }

    /**
     * 递归找后置 谐波数据
     *
     * @param date 起始时间
     * @param time 截止时间
     */
    private Float getAppendHarmValue(Date date, Date time, Map<Date, HarmData> beforeDeal, int interval) {
        Float result;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MINUTE, -interval);
        if (calendar.getTimeInMillis() <= time.getTime()) {
            return null;
        } else {
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(time);
            calendar1.add(Calendar.MINUTE, interval);
            HarmData temp = beforeDeal.get(calendar1.getTime());
            if (temp == null || temp.getValue() == null) {
                result = getAppendHarmValue(date, calendar1.getTime(), beforeDeal, interval);
            } else {
                result = temp.getValue();
            }
        }
        return result;
    }


//    /**
//     * 获取季度时间段
//     * @param date
//     * @return 结果
//     */
//    private static Map<String, Date> getSeasonDate(Date date) {
//        Map<String, Date> result = new HashMap<>();
//        //根据当前时间初始化
//        Calendar start = Calendar.getInstance();
//        Calendar end = Calendar.getInstance();
//        start.setTime(date);
//        end.setTime(date);
//        //根据月份计算出季度时间段
//        int month = start.get(Calendar.MONTH);
//        switch (month) {
//            case Calendar.JANUARY:
//            case Calendar.FEBRUARY:
//            case Calendar.MARCH:
//                start.set(Calendar.MONTH, 0);
//                start.set(Calendar.DATE,1);
//                end.set(Calendar.MONTH, 2);
//                end.set(Calendar.DATE, 31);
//                break;
//            case Calendar.APRIL:
//            case Calendar.MAY:
//            case Calendar.JUNE:
//                start.set(Calendar.MONTH, 3);
//                start.set(Calendar.DATE,1);
//                end.set(Calendar.MONTH, 5);
//                end.set(Calendar.DATE, 30);
//                break;
//            case Calendar.JULY:
//            case Calendar.AUGUST:
//            case Calendar.SEPTEMBER:
//                start.set(Calendar.MONTH, 6);
//                start.set(Calendar.DATE,1);
//                end.set(Calendar.MONTH, 8);
//                end.set(Calendar.DATE, 30);
//                break;
//            case Calendar.OCTOBER:
//            case Calendar.NOVEMBER:
//            case Calendar.DECEMBER:
//                start.set(Calendar.MONTH, 9);
//                start.set(Calendar.DATE,1);
//                end.set(Calendar.MONTH, 11);
//                end.set(Calendar.DATE, 31);
//                break;
//            default:
//                break;
//        }
//        //转换成date组装返回
//        result.put("startTime",start.getTime());
//        result.put("endTime",end.getTime());
//        return result;
//    }

    /**
     * 获取合理的测量间隔
     */
    private int getInterval(int lineInterval, Date lastOne, Date lastTwo) {
        int interval = 0;
        Calendar one = Calendar.getInstance();
        one.setTime(lastOne);
        Calendar two = Calendar.getInstance();
        two.setTime(lastTwo);
        long oneTime = lastOne.getTime();
        long twoTime = lastTwo.getTime();
        long intvalTime = oneTime - twoTime;
        long databaseInterval = lineInterval * 60 * 1000;
        if (oneTime < twoTime || intvalTime >= databaseInterval) {
            interval = lineInterval;
        }
        if (intvalTime < databaseInterval) {
            interval = (int) (intvalTime / (1000 * 60));
        }
        return interval;
    }

}
