package com.njcn.event.common.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.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.config.GeneralInfo;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pq.pojo.vo.LineDetailDataVO;
import com.njcn.event.common.service.EventAnalysisService;
import com.njcn.event.common.service.EventDetailService;
import com.njcn.event.enums.EventResponseEnum;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.event.pojo.param.EventBaseParam;
import com.njcn.event.pojo.param.StatisticsParam;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.event.pojo.vo.*;
import com.njcn.influx.utils.InfluxDbUtils;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.QueryResult;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * pqs-event
 *
 * @author cdf
 * @date 2022/6/23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class EventAnalysisServiceImpl implements EventAnalysisService {

    // 定义阈值常量（单位：百分比）
    final double[] EVENT_VALUE_THRESHOLDS = {85, 70, 40, 10, 0};
    // 定义持续时间阈值（单位：毫秒）
    final double[] DURATION_THRESHOLDS = {0.02, 0.1, 0.5, 1, 3, 20, 60, 180};
    // 定义持续时间阈值（单位：毫秒）
    final double[] DURATION_THRESHOLDS_411 = {0.02, 0.1, 0.2, 0.5, 1, 180};

    String[] labels = {"90%", "85%", "70%", "40%", "10%"};


    private final InfluxDbUtils influxDbUtils;

    private final LineFeignClient lineFeignClient;

    private final EventDetailService eventDetailService;

    private final GeneralInfo generalInfo;

    private final DicDataFeignClient dicDataFeignClient;


    /**
     * 获取电压暂态表及密度坐标图
     *
     * @param statisticsParam
     * @return
     * @author xxy
     */
    @Override
    public List<CoordsVO> getCoords(StatisticsParam statisticsParam) {
        List<CoordsVO> result = new ArrayList<>();

//        QueryResult query = MonitorQuery(statisticsParam);
//        InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//        List<EventDetail> info = influxDBResultMapper.toPOJO(query, EventDetail.class);

        //查询监测点未处理暂态事件
        List<RmpEventDetailPO> info = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );

        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 9; j++) {
                result.add(new CoordsVO(i, j, 0));
            }
        }
        for (int i = 0; i < info.size(); i++) {
            Integer index = null;
            CoordsVO dto = new CoordsVO();
            if (info.get(i).getFeatureAmplitude() >= 0 && info.get(i).getFeatureAmplitude() <= 0.1) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 0;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 1;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 2;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 3;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 4;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 5;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 6;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 7;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 8;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.1 && info.get(i).getFeatureAmplitude() <= 0.2) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 9;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 10;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 11;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 12;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 13;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 14;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 15;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 16;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 17;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.2 && info.get(i).getFeatureAmplitude() <= 0.3) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 18;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 19;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 20;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 21;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 22;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 23;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 24;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 25;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 26;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.3 && info.get(i).getFeatureAmplitude() <= 0.4) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 27;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 28;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 29;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 30;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 31;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 32;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 33;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 34;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 35;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.4 && info.get(i).getFeatureAmplitude() <= 0.5) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 36;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 37;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 38;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 39;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 40;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 41;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 42;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 43;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 44;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.5 && info.get(i).getFeatureAmplitude() <= 0.6) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 45;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 46;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 47;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 48;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 49;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 50;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 51;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 52;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 53;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.6 && info.get(i).getFeatureAmplitude() <= 0.7) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 54;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 55;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 56;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 57;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 58;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 59;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 60;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 61;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 62;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.7 && info.get(i).getFeatureAmplitude() <= 0.8) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 63;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 64;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 65;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 66;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 67;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 68;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 69;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 70;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 71;
                }
            } else if (info.get(i).getFeatureAmplitude() > 0.8 && info.get(i).getFeatureAmplitude() <= 0.9) {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 72;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 73;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 74;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 75;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 76;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 77;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 78;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 79;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 80;
                }
            } else {
                if (info.get(i).getDuration() / 1000 > 0 && info.get(i).getDuration() / 1000 <= 0.020) {
                    index = 81;
                } else if (info.get(i).getDuration() / 1000 <= 0.040 && info.get(i).getDuration() / 1000 > 0.020) {
                    index = 82;
                } else if (info.get(i).getDuration() / 1000 <= 0.060 && info.get(i).getDuration() / 1000 > 0.040) {
                    index = 83;
                } else if (info.get(i).getDuration() / 1000 <= 0.080 && info.get(i).getDuration() / 1000 > 0.060) {
                    index = 84;
                } else if (info.get(i).getDuration() / 1000 <= 0.120 && info.get(i).getDuration() / 1000 > 0.080) {
                    index = 85;
                } else if (info.get(i).getDuration() / 1000 > 0.120 && info.get(i).getDuration() / 1000 < 0.200) {
                    index = 86;
                } else if (info.get(i).getDuration() / 1000 >= 0.200 && info.get(i).getDuration() / 1000 < 0.400) {
                    index = 87;
                } else if (info.get(i).getDuration() / 1000 >= 0.400 && info.get(i).getDuration() / 1000 < 0.600) {
                    index = 88;
                } else if (info.get(i).getDuration() / 1000 >= 0.600 && info.get(i).getDuration() / 1000 <= 1.200) {
                    index = 89;
                }
            }
            if (Objects.nonNull(index)) {
                CoordsVO coordsVO = result.get(index);
                coordsVO.setZ(coordsVO.getZ() + 1);
            }
        }
        return result;
    }

    @Override
    public List<DISDIPVO> eventDisdip(StatisticsParam statisticsParam) {
        // 初始化结果数组（默认值为0）
        int[][] arr = new int[5][8];

        // 查询事件数据
        List<RmpEventDetailPO> events = eventDetailService.list(
                new LambdaQueryWrapper<RmpEventDetailPO>()
                        .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                        .le(RmpEventDetailPO::getFeatureAmplitude,0.9)
                        .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()),
                                RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                        .le(StringUtils.isNotBlank(statisticsParam.getEndTime()),
                                RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );

        // 分类统计事件
        for (RmpEventDetailPO event : events) {
            double eventValue = event.getFeatureAmplitude() * 100; // 转换为百分比
            double duration = event.getDuration();

            // 确定事件等级（0=90%, 1=85%, ..., 4=10%）
            int level = getEventLevel(eventValue, EVENT_VALUE_THRESHOLDS);
            // 确定持续时间区间索引
            int durationIndex = getDurationIndex(duration, DURATION_THRESHOLDS);

            if (level != -1 && durationIndex != -1) {
                arr[level][durationIndex]++;
            }
        }

        // 构建结果列表
        List<DISDIPVO> result = new ArrayList<>();
        for (int i = 0; i < labels.length; i++) {
            result.add(new DISDIPVO(
                    labels[i],
                    String.valueOf(arr[i][0]), String.valueOf(arr[i][1]), String.valueOf(arr[i][2]), String.valueOf(arr[i][3]),
                    String.valueOf(arr[i][4]), String.valueOf(arr[i][5]), String.valueOf(arr[i][6]), String.valueOf(arr[i][7])
            ));
        }

        return result;
    }

    /**
     * 根据事件值获取等级索引（从高到低匹配）
     */
    private int getEventLevel(double eventValue, double[] thresholds) {
        for (int i = 0; i < thresholds.length; i++) {
            if (eventValue >= thresholds[i]) {
                return i; // 返回匹配的等级索引
            }
        }
        return thresholds.length - 1; // 默认最低等级
    }

    /**
     * 根据持续时间获取区间索引
     */
    private int getDurationIndex(double duration, double[] thresholds) {
        for (int i = 0; i < thresholds.length; i++) {
            if (duration < thresholds[i]) {
                return i;
            }
        }
        return thresholds.length - 1; // 超过最大阈值时返回最后一个区间
    }

    @Override
    public List<IEC411VO> IEC411(StatisticsParam statisticsParam) {
        List<IEC411VO> result = new ArrayList<>();
        //查询监测点未处理暂态事件
        List<RmpEventDetailPO> events = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                .le(RmpEventDetailPO::getFeatureAmplitude,0.9)
                .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );
        int[][] arr = new int[3][6];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 6; j++) {
                arr[i][j] = 0;
            }
        }
        // 分类统计事件
        for (RmpEventDetailPO event : events) {
            double eventValue = event.getFeatureAmplitude(); // 转换为百分比
            double duration = event.getDuration();

            // 确定事件等级（0=90%, 1=85%, ..., 4=10%）
            int level = getIEC411_EventLevel(eventValue);
            // 确定持续时间区间索引
            int durationIndex = getDurationIndex(duration, DURATION_THRESHOLDS_411);

            if (level != -1 && durationIndex != -1) {
                arr[level][durationIndex]++;
            }
        }
        result.add(new IEC411VO("40~70%", String.valueOf(arr[0][0]), String.valueOf(arr[0][1]), String.valueOf(arr[0][2]), String.valueOf(arr[0][3]), String.valueOf(arr[0][4]), String.valueOf(arr[0][5])));
        result.add(new IEC411VO("1~40%", String.valueOf(arr[1][0]), String.valueOf(arr[1][1]), String.valueOf(arr[1][2]), String.valueOf(arr[1][3]), String.valueOf(arr[1][4]), String.valueOf(arr[1][5])));
        result.add(new IEC411VO("<1%", String.valueOf(arr[2][0]), String.valueOf(arr[2][1]), String.valueOf(arr[2][2]), String.valueOf(arr[2][3]), String.valueOf(arr[2][4]), String.valueOf(arr[2][5])));
        return result;
    }


    /**
     * 根据事件值获取等级索引（从高到低匹配）
     */
    private int getIEC411_EventLevel(double eventValue) {
            if (eventValue >= 0.01 && eventValue < 0.4) {
                return 1;
            } else if (eventValue >= 0.4 && eventValue < 0.7) {
                return 0;
            }
//            else if (eventValue >= 0.7 && eventValue < 1) {
//                return 2;
//            }
            else if (eventValue < 0.01) {
                return 2;
            }
            return -1;
    }

    @Override
    public List<IEC28VO> IEC28(StatisticsParam statisticsParam) {

        List<IEC28VO> result = new ArrayList<>();
        //查询监测点未处理暂态事件
        List<RmpEventDetailPO> info = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );

        int[][] arr = new int[17][8];
        for (int i = 0; i < 17; i++) {
            for (int j = 0; j < 8; j++) {
                arr[i][j] = 0;
            }
        }
        for (int i = 0; i < info.size(); i++) {
            Double eventvalue = info.get(i).getFeatureAmplitude();
            double persisttime = info.get(i).getDuration();
            if (eventvalue * 100 < 1 && eventvalue * 100 >= 0) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[16][0]++;
                } else if (persisttime <= 250) {
                    arr[16][1]++;
                } else if (persisttime <= 500) {
                    arr[16][2]++;
                } else if (persisttime <= 1000) {
                    arr[16][3]++;
                } else if (persisttime <= 3000) {
                    arr[16][4]++;
                } else if (persisttime <= 20000) {
                    arr[16][5]++;
                } else if (persisttime <= 60000) {
                    arr[16][6]++;
                } else if (persisttime <= 180000) {
                    arr[16][7]++;
                }
            } else if (eventvalue * 100 < 10) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[15][0]++;
                } else if (persisttime <= 250) {
                    arr[15][1]++;
                } else if (persisttime <= 500) {
                    arr[15][2]++;
                } else if (persisttime <= 1000) {
                    arr[15][3]++;
                } else if (persisttime <= 3000) {
                    arr[15][4]++;
                } else if (persisttime <= 20000) {
                    arr[15][5]++;
                } else if (persisttime <= 60000) {
                    arr[15][6]++;
                } else if (persisttime <= 180000) {
                    arr[15][7]++;
                }
            } else if (eventvalue * 100 < 20) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[14][0]++;
                } else if (persisttime <= 250) {
                    arr[14][1]++;
                } else if (persisttime <= 500) {
                    arr[14][2]++;
                } else if (persisttime <= 1000) {
                    arr[14][3]++;
                } else if (persisttime <= 3000) {
                    arr[14][4]++;
                } else if (persisttime <= 20000) {
                    arr[14][5]++;
                } else if (persisttime <= 60000) {
                    arr[14][6]++;
                } else if (persisttime <= 180000) {
                    arr[14][7]++;
                }
            } else if (eventvalue * 100 < 30) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[13][0]++;
                } else if (persisttime <= 250) {
                    arr[13][1]++;
                } else if (persisttime <= 500) {
                    arr[13][2]++;
                } else if (persisttime <= 1000) {
                    arr[13][3]++;
                } else if (persisttime <= 3000) {
                    arr[13][4]++;
                } else if (persisttime <= 20000) {
                    arr[13][5]++;
                } else if (persisttime <= 60000) {
                    arr[13][6]++;
                } else if (persisttime <= 180000) {
                    arr[13][7]++;
                }
            } else if (eventvalue * 100 < 40) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[12][0]++;
                } else if (persisttime <= 250) {
                    arr[12][1]++;
                } else if (persisttime <= 500) {
                    arr[12][2]++;
                } else if (persisttime <= 1000) {
                    arr[12][3]++;
                } else if (persisttime <= 3000) {
                    arr[12][4]++;
                } else if (persisttime <= 20000) {
                    arr[12][5]++;
                } else if (persisttime <= 60000) {
                    arr[12][6]++;
                } else if (persisttime <= 180000) {
                    arr[12][7]++;
                }
            } else if (eventvalue * 100 < 50) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[11][0]++;
                } else if (persisttime <= 250) {
                    arr[11][1]++;
                } else if (persisttime <= 500) {
                    arr[11][2]++;
                } else if (persisttime <= 1000) {
                    arr[11][3]++;
                } else if (persisttime <= 3000) {
                    arr[11][4]++;
                } else if (persisttime <= 20000) {
                    arr[11][5]++;
                } else if (persisttime <= 60000) {
                    arr[11][6]++;
                } else if (persisttime <= 180000) {
                    arr[11][7]++;
                }
            } else if (eventvalue * 100 < 60) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[10][0]++;
                } else if (persisttime <= 250) {
                    arr[10][1]++;
                } else if (persisttime <= 500) {
                    arr[10][2]++;
                } else if (persisttime <= 1000) {
                    arr[10][3]++;
                } else if (persisttime <= 3000) {
                    arr[10][4]++;
                } else if (persisttime <= 20000) {
                    arr[10][5]++;
                } else if (persisttime <= 60000) {
                    arr[10][6]++;
                } else if (persisttime <= 180000) {
                    arr[10][7]++;
                }
            } else if (eventvalue * 100 < 70) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[9][0]++;
                } else if (persisttime <= 250) {
                    arr[9][1]++;
                } else if (persisttime <= 500) {
                    arr[9][2]++;
                } else if (persisttime <= 1000) {
                    arr[9][3]++;
                } else if (persisttime <= 3000) {
                    arr[9][4]++;
                } else if (persisttime <= 20000) {
                    arr[9][5]++;
                } else if (persisttime <= 60000) {
                    arr[9][6]++;
                } else if (persisttime <= 180000) {
                    arr[9][7]++;
                }
            } else if (eventvalue * 100 < 80) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[8][0]++;
                } else if (persisttime <= 250) {
                    arr[8][1]++;
                } else if (persisttime <= 500) {
                    arr[8][2]++;
                } else if (persisttime <= 1000) {
                    arr[8][3]++;
                } else if (persisttime <= 3000) {
                    arr[8][4]++;
                } else if (persisttime <= 20000) {
                    arr[8][5]++;
                } else if (persisttime <= 60000) {
                    arr[8][6]++;
                } else if (persisttime <= 180000) {
                    arr[8][7]++;
                }
            } else if (eventvalue * 100 <= 90) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[7][0]++;
                } else if (persisttime <= 250) {
                    arr[7][1]++;
                } else if (persisttime <= 500) {
                    arr[7][2]++;
                } else if (persisttime <= 1000) {
                    arr[7][3]++;
                } else if (persisttime <= 3000) {
                    arr[7][4]++;
                } else if (persisttime <= 20000) {
                    arr[7][5]++;
                } else if (persisttime <= 60000) {
                    arr[7][6]++;
                } else if (persisttime <= 180000) {
                    arr[7][7]++;
                }
            } else if (eventvalue * 100 < 120 && eventvalue * 100 >= 110) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[6][0]++;
                } else if (persisttime <= 250) {
                    arr[6][1]++;
                } else if (persisttime <= 500) {
                    arr[6][2]++;
                } else if (persisttime <= 1000) {
                    arr[6][3]++;
                } else if (persisttime <= 3000) {
                    arr[6][4]++;
                } else if (persisttime <= 20000) {
                    arr[6][5]++;
                } else if (persisttime <= 60000) {
                    arr[6][6]++;
                } else if (persisttime <= 180000) {
                    arr[6][7]++;
                }
            } else if (eventvalue * 100 < 130) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[5][0]++;
                } else if (persisttime <= 250) {
                    arr[5][1]++;
                } else if (persisttime <= 500) {
                    arr[5][2]++;
                } else if (persisttime <= 1000) {
                    arr[5][3]++;
                } else if (persisttime <= 3000) {
                    arr[5][4]++;
                } else if (persisttime <= 20000) {
                    arr[5][5]++;
                } else if (persisttime <= 60000) {
                    arr[5][6]++;
                } else if (persisttime <= 180000) {
                    arr[5][7]++;
                }
            } else if (eventvalue * 100 < 140) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[4][0]++;
                } else if (persisttime <= 250) {
                    arr[4][1]++;
                } else if (persisttime <= 500) {
                    arr[4][2]++;
                } else if (persisttime <= 1000) {
                    arr[4][3]++;
                } else if (persisttime <= 3000) {
                    arr[4][4]++;
                } else if (persisttime <= 20000) {
                    arr[4][5]++;
                } else if (persisttime <= 60000) {
                    arr[4][6]++;
                } else if (persisttime <= 180000) {
                    arr[4][7]++;
                }
            } else if (eventvalue * 100 < 150) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[3][0]++;
                } else if (persisttime <= 250) {
                    arr[3][1]++;
                } else if (persisttime <= 500) {
                    arr[3][2]++;
                } else if (persisttime <= 1000) {
                    arr[3][3]++;
                } else if (persisttime <= 3000) {
                    arr[3][4]++;
                } else if (persisttime <= 20000) {
                    arr[3][5]++;
                } else if (persisttime <= 60000) {
                    arr[3][6]++;
                } else if (persisttime <= 180000) {
                    arr[3][7]++;
                }
            } else if (eventvalue * 100 < 160) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[2][0]++;
                } else if (persisttime <= 250) {
                    arr[2][1]++;
                } else if (persisttime <= 500) {
                    arr[2][2]++;
                } else if (persisttime <= 1000) {
                    arr[2][3]++;
                } else if (persisttime <= 3000) {
                    arr[2][4]++;
                } else if (persisttime <= 20000) {
                    arr[2][5]++;
                } else if (persisttime <= 60000) {
                    arr[2][6]++;
                } else if (persisttime <= 180000) {
                    arr[2][7]++;
                }
            } else if (eventvalue * 100 < 170) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[1][0]++;
                } else if (persisttime <= 250) {
                    arr[1][1]++;
                } else if (persisttime <= 500) {
                    arr[1][2]++;
                } else if (persisttime <= 1000) {
                    arr[1][3]++;
                } else if (persisttime <= 3000) {
                    arr[1][4]++;
                } else if (persisttime <= 20000) {
                    arr[1][5]++;
                } else if (persisttime <= 60000) {
                    arr[1][6]++;
                } else if (persisttime <= 180000) {
                    arr[1][7]++;
                }
            } else if (eventvalue * 100 <= 180) {
                if (persisttime > 10 && persisttime <= 100) {
                    arr[0][0]++;
                } else if (persisttime <= 250) {
                    arr[0][1]++;
                } else if (persisttime <= 500) {
                    arr[0][2]++;
                } else if (persisttime <= 1000) {
                    arr[0][3]++;
                } else if (persisttime <= 3000) {
                    arr[0][4]++;
                } else if (persisttime <= 20000) {
                    arr[0][5]++;
                } else if (persisttime <= 60000) {
                    arr[0][6]++;
                } else if (persisttime <= 180000) {
                    arr[0][7]++;
                }
            }
        }
        result.add(new IEC28VO("180>U>=170", String.valueOf(arr[0][0]), String.valueOf(arr[0][1]), String.valueOf(arr[0][2]), String.valueOf(arr[0][3]), String.valueOf(arr[0][4]), String.valueOf(arr[0][5]), String.valueOf(arr[0][6]), String.valueOf(arr[0][7])));
        result.add(new IEC28VO("170>U>=160", String.valueOf(arr[1][0]), String.valueOf(arr[1][1]), String.valueOf(arr[1][2]), String.valueOf(arr[1][3]), String.valueOf(arr[1][4]), String.valueOf(arr[1][5]), String.valueOf(arr[1][6]), String.valueOf(arr[1][7])));
        result.add(new IEC28VO("160>U>=150", String.valueOf(arr[2][0]), String.valueOf(arr[2][1]), String.valueOf(arr[2][2]), String.valueOf(arr[2][3]), String.valueOf(arr[2][4]), String.valueOf(arr[2][5]), String.valueOf(arr[2][6]), String.valueOf(arr[2][7])));
        result.add(new IEC28VO("150>U>=140", String.valueOf(arr[3][0]), String.valueOf(arr[3][1]), String.valueOf(arr[3][2]), String.valueOf(arr[3][3]), String.valueOf(arr[3][4]), String.valueOf(arr[3][5]), String.valueOf(arr[3][6]), String.valueOf(arr[3][7])));
        result.add(new IEC28VO("140>U>=130", String.valueOf(arr[4][0]), String.valueOf(arr[4][1]), String.valueOf(arr[4][2]), String.valueOf(arr[4][3]), String.valueOf(arr[4][4]), String.valueOf(arr[4][5]), String.valueOf(arr[4][6]), String.valueOf(arr[4][7])));
        result.add(new IEC28VO("130>U>=120", String.valueOf(arr[5][0]), String.valueOf(arr[5][1]), String.valueOf(arr[5][2]), String.valueOf(arr[5][3]), String.valueOf(arr[5][4]), String.valueOf(arr[5][5]), String.valueOf(arr[5][6]), String.valueOf(arr[5][7])));
        result.add(new IEC28VO("120>U>=110", String.valueOf(arr[6][0]), String.valueOf(arr[6][1]), String.valueOf(arr[6][2]), String.valueOf(arr[6][3]), String.valueOf(arr[6][4]), String.valueOf(arr[6][5]), String.valueOf(arr[6][6]), String.valueOf(arr[6][7])));
        result.add(new IEC28VO("90>U>=80", String.valueOf(arr[7][0]), String.valueOf(arr[7][1]), String.valueOf(arr[7][2]), String.valueOf(arr[7][3]), String.valueOf(arr[7][4]), String.valueOf(arr[7][5]), String.valueOf(arr[7][6]), String.valueOf(arr[7][7])));
        result.add(new IEC28VO("80>U>=70", String.valueOf(arr[8][0]), String.valueOf(arr[8][1]), String.valueOf(arr[8][2]), String.valueOf(arr[8][3]), String.valueOf(arr[8][4]), String.valueOf(arr[8][5]), String.valueOf(arr[8][6]), String.valueOf(arr[8][7])));
        result.add(new IEC28VO("70>U>=60", String.valueOf(arr[9][0]), String.valueOf(arr[9][1]), String.valueOf(arr[9][2]), String.valueOf(arr[9][3]), String.valueOf(arr[9][4]), String.valueOf(arr[9][5]), String.valueOf(arr[9][6]), String.valueOf(arr[9][7])));
        result.add(new IEC28VO("60>U>=50", String.valueOf(arr[10][0]), String.valueOf(arr[10][1]), String.valueOf(arr[10][2]), String.valueOf(arr[10][3]), String.valueOf(arr[10][4]), String.valueOf(arr[10][5]), String.valueOf(arr[10][6]), String.valueOf(arr[10][7])));
        result.add(new IEC28VO("50>U>=40", String.valueOf(arr[11][0]), String.valueOf(arr[11][1]), String.valueOf(arr[11][2]), String.valueOf(arr[11][3]), String.valueOf(arr[11][4]), String.valueOf(arr[11][5]), String.valueOf(arr[11][6]), String.valueOf(arr[11][7])));
        result.add(new IEC28VO("40>U>=30", String.valueOf(arr[12][0]), String.valueOf(arr[12][1]), String.valueOf(arr[12][2]), String.valueOf(arr[12][3]), String.valueOf(arr[12][4]), String.valueOf(arr[12][5]), String.valueOf(arr[12][6]), String.valueOf(arr[12][7])));
        result.add(new IEC28VO("30>U>=20", String.valueOf(arr[13][0]), String.valueOf(arr[13][1]), String.valueOf(arr[13][2]), String.valueOf(arr[13][3]), String.valueOf(arr[13][4]), String.valueOf(arr[13][5]), String.valueOf(arr[13][6]), String.valueOf(arr[13][7])));
        result.add(new IEC28VO("20>U>=10", String.valueOf(arr[14][0]), String.valueOf(arr[14][1]), String.valueOf(arr[14][2]), String.valueOf(arr[14][3]), String.valueOf(arr[14][4]), String.valueOf(arr[14][5]), String.valueOf(arr[14][6]), String.valueOf(arr[14][7])));
        result.add(new IEC28VO("10>U>=1", String.valueOf(arr[15][0]), String.valueOf(arr[15][1]), String.valueOf(arr[15][2]), String.valueOf(arr[15][3]), String.valueOf(arr[15][4]), String.valueOf(arr[15][5]), String.valueOf(arr[15][6]), String.valueOf(arr[15][7])));
        result.add(new IEC28VO("1>U>=0", String.valueOf(arr[16][0]), String.valueOf(arr[16][1]), String.valueOf(arr[16][2]), String.valueOf(arr[16][3]), String.valueOf(arr[16][4]), String.valueOf(arr[16][5]), String.valueOf(arr[16][6]), String.valueOf(arr[16][7])));
        return result;
    }

    /**
     * 暂降原因类型和时间
     *
     * @param statisticsParam
     * @return
     * @author xxy
     */
    @Override
    public List<TimeVO> getReasonTypeTime(StatisticsParam statisticsParam) {
        //获取暂降字典信息
        List<DictData> data = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();
        List<String> typeList = data.stream().filter(it->it.getCode().equals(DicDataEnum.VOLTAGE_DIP.getCode()) || it.getCode().equals(DicDataEnum.SHORT_INTERRUPTIONS.getCode())).map(DictData::getId).collect(Collectors.toList());        List<TimeVO> list = new ArrayList<>();
        //参数
        StringBuilder builder1 = new StringBuilder();
        StringBuilder builder2 = new StringBuilder();
        QueryResult query = null;
        //获取时间字符串
        String startTime = statisticsParam.getStartTime();
        String endTime = statisticsParam.getEndTime();
        Integer startDays = Integer.parseInt(startTime.substring(8, 10));
        Integer endDays = Integer.parseInt(endTime.substring(8, 10));
        Integer startMonth = Integer.parseInt(startTime.substring(5, 7));
        Integer endMonth = Integer.parseInt(endTime.substring(5, 7));
        Integer startYear = Integer.parseInt(startTime.substring(0, 4));
        Integer endYear = Integer.parseInt(endTime.substring(0, 4));
        if (statisticsParam.getFlag() == 0) {
            while (startYear != endYear && startMonth != endMonth) {
                builder1.delete(0, builder1.length());
                builder2.delete(0, builder2.length());
                builder1.append(startYear).append("-").append(startMonth).append("-").append(startDays);
                if (startMonth + 1 == 13) {
                    builder2.append(startYear + 1).append("-").append(1).append("-").append(startDays);
                } else {
                    builder2.append(startYear).append("-").append(startMonth + 1).append("-").append(startDays);
                }

//                query = MonitorQuery(new StatisticsParam(statisticsParam.getLineIndex(),builder1.toString(), builder2.toString(), statisticsParam.getFlag()));
//                InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//                List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(query, EventDetail.class);
//                long count = eventDetailList.stream().filter(x -> x.getWaveType() == 1).count();
                List<RmpEventDetailPO> eventDetailList = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                        .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                        .in(RmpEventDetailPO::getEventType,typeList)
                        .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                        .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
                );
                long count = eventDetailList.stream().filter(x -> typeList.contains(x.getEventType())).count();
                if (startMonth < 10) {
                    list.add(new TimeVO(null, null, "", "0" + startMonth.toString(), count + "", startYear.toString(), startYear.toString() + "-" + "0" + startMonth.toString()));
                } else {
                    list.add(new TimeVO(null, null, "", startMonth.toString(), count + "", startYear.toString(), startYear.toString() + "-" + startMonth.toString()));
                }
                startMonth++;
                if (startMonth == 13) {
                    startYear++;
                    startMonth = 1;
                }
            }
            builder1.delete(0, builder1.length());
            builder2.delete(0, builder2.length());
            builder1.append(startYear).append("-").append(startMonth).append("-").append(startDays);
            builder2.append(startYear).append("-").append(startMonth).append("-").append(endDays);
//            query = MonitorQuery(new StatisticsParam(statisticsParam.getLineIndex(),builder1.toString(), builder2.toString(), statisticsParam.getFlag()));
//            InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//            List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(query, EventDetail.class);
//            long count1 = eventDetailList.stream().filter(x -> x.getWaveType() == 1).count();
            List<RmpEventDetailPO> eventDetailList = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                    .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                    .in(RmpEventDetailPO::getEventType, typeList)
                    .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                    .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
            );
            long count1 = eventDetailList.stream().filter(x -> typeList.contains(x.getEventType())).count();
            if (startMonth < 10) {
                list.add(new TimeVO(null, null, "", "0" + startMonth.toString(), count1 + "", startYear.toString(), startYear.toString() + "-" + "0" + startMonth.toString()));
            } else {
                list.add(new TimeVO(null, null, "", startMonth.toString(), count1 + "", startYear.toString(), startYear.toString() + "-" + startMonth.toString()));
            }
            return list;
        } else {
//            QueryResult monitorQuery = MonitorQuery(statisticsParam);
//            InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//            List<EventDetailNew> eventDetailList = influxDBResultMapper.toPOJO(monitorQuery, EventDetailNew.class);
//            Map<String, List<EventDetailNew>> map = eventDetailList.stream().filter(x -> data.getId().equals(x.getEventType())).collect(Collectors.groupingBy(s -> s.getTimeId().substring(0, 10)));

            List<RmpEventDetailPO> eventDetailList = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                    .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                    .in(RmpEventDetailPO::getEventType, typeList)
                    .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                    .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
            );

            Map<String, List<RmpEventDetailPO>> map = eventDetailList.stream().filter(x -> typeList.contains(x.getEventType()))
                    .peek(t -> t.setFormatTime(t.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))))
                    .collect(Collectors.groupingBy(RmpEventDetailPO::getFormatTime));
            Set<String> keySet = map.keySet();
            LocalDate parse1 = LocalDate.parse(startTime);
            LocalDate parse2 = LocalDate.parse(endTime);
            while (!parse1.equals(parse2.plus(1, ChronoUnit.DAYS))) {
                if (keySet.contains(parse1.toString())) {
//                    List<EventDetailNew> eventDetailNews = map.get(parse1.toString());
                    List<RmpEventDetailPO> eventDetailNews = map.get(parse1.toString());
                    TimeVO timeVO = new TimeVO();
                    timeVO.setTimes(eventDetailNews.size() + "");
                    if (parse1.getDayOfMonth() < 10) {
                        timeVO.setDay("0" + parse1.getDayOfMonth() + "");
                    } else {
                        timeVO.setDay(parse1.getDayOfMonth() + "");
                    }
                    timeVO.setYear(parse1.getYear() + "");
                    if (parse1.getMonthValue() < 10) {
                        timeVO.setMonth("0" + parse1.getMonthValue() + "");
                    } else {
                        timeVO.setMonth(parse1.getMonthValue() + "");
                    }
                    timeVO.setFulltime(parse1.toString());
                    list.add(timeVO);
                } else {
                    TimeVO timeVO = new TimeVO();
                    timeVO.setTimes("0");
                    if (parse1.getDayOfMonth() < 10) {
                        timeVO.setDay("0" + parse1.getDayOfMonth() + "");
                    } else {
                        timeVO.setDay(parse1.getDayOfMonth() + "");
                    }
                    timeVO.setYear(parse1.getYear() + "");
                    if (parse1.getMonthValue() < 10) {
                        timeVO.setMonth("0" + parse1.getMonthValue() + "");
                    } else {
                        timeVO.setMonth(parse1.getMonthValue() + "");
                    }
                    timeVO.setFulltime(parse1.toString());
                    list.add(timeVO);
                }
                parse1 = parse1.plus(1, ChronoUnit.DAYS);
            }
            return list;
        }
    }

    @Override
    public StatisticVO getStatistic(StatisticsParam statisticsParam) {
        StatisticVO result = new StatisticVO();
        List<EventDetail> list = new ArrayList<>();
        List<ReasonsVO> reasonsVOS = new ArrayList<>();
        List<TypesVO> typesVOS = new ArrayList<>();
        //获取暂降字典信息
        List<DictData> dataDic = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();
        List<String> typeList = dataDic.stream().filter(it->it.getCode().equals(DicDataEnum.VOLTAGE_DIP.getCode()) || it.getCode().equals(DicDataEnum.SHORT_INTERRUPTIONS.getCode())).map(DictData::getId).collect(Collectors.toList());
        //数据暂降查询
        List<RmpEventDetailPO> info = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                .in( RmpEventDetailPO::getEventType,typeList)
                .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );

        HttpResult<List<DictData>> reason = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName());
        HttpResult<List<DictData>> type = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_TYPE.getName());
        List<DictData> reasonData = reason.getData();
        List<DictData> typeData = type.getData();

        Map<String, Integer> reasonMap = new LinkedHashMap<>();
        Map<String, Integer> typeMap = new LinkedHashMap<>();

        info = info.stream().filter(temp->StringUtils.isNotEmpty(temp.getAdvanceReason())||StringUtils.isNotEmpty(temp.getAdvanceType())).collect(Collectors.toList());
        //添加detail
        for (RmpEventDetailPO detail : info) {
            EventDetail details = null;
            if (typeList.contains(detail.getEventType())) {
                for (DictData data : reasonData) {
                    reasonMap.put(data.getName(), 0);
                    //此处写法会报空指针异常修改写法
                    if (Objects.equals(detail.getAdvanceReason(),data.getId())) {
                        details = BeanUtil.copyProperties(detail, EventDetail.class);
                        details.setAdvanceReason(data.getName());
                    }
                }
                for (DictData data : typeData) {
                    typeMap.put(data.getName(), 0);
                    if (Objects.equals(detail.getAdvanceType(),data.getId())) {
//                        details = BeanUtil.copyProperties(detail, EventDetail.class);
                        details.setAdvanceType(data.getName());
                    }
                }
                list.add(details);
            }
        }

        //添加reason到map
        for (EventDetail data : list) {
            if (StringUtils.isNotEmpty(data.getAdvanceReason())&&reasonMap.get(data.getAdvanceReason()) != null) {
                reasonMap.put(data.getAdvanceReason(), reasonMap.get(data.getAdvanceReason()) + 1);
            }
        }
        //添加type到map
        for (EventDetail data : list) {
            if (StringUtils.isNotEmpty(data.getAdvanceType())&&typeMap.get(data.getAdvanceType()) != null) {
                typeMap.put(data.getAdvanceType(), typeMap.get(data.getAdvanceType()) + 1);
            }
        }
        Set<String> reasonKeyset = reasonMap.keySet();
        Set<String> typeKeyset = typeMap.keySet();
        for (String s : reasonKeyset) {
            reasonsVOS.add(new ReasonsVO(s, reasonMap.get(s), null));
        }
        for (String s : typeKeyset) {
            typesVOS.add(new TypesVO(s, typeMap.get(s)));
        }
        result.setTypes(typesVOS);
        result.setReason(reasonsVOS);
        result.setDetail(list);
        return result;
    }

    /**
     * 暂降幅值的概率分布函数
     *
     * @param statisticsParam
     * @return
     * @author xxy
     */
    @Override
    public ProbabilityVO getProbabilityDistribution(StatisticsParam statisticsParam) {

        ProbabilityVO result = new ProbabilityVO();
        List<EventDetail> info = new ArrayList<>();
        //数据暂降查询
        List<RmpEventDetailPO> infos = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
                .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );
        List<EventDetail> info2 = BeanUtil.copyToList(infos, EventDetail.class);
        //总数
        Integer count = 0;
        for (EventDetail eventDetail : info2) {
            //过滤掉大于0.9的数据
            if (eventDetail.getFeatureAmplitude() <= 0.9) {
                count++;
                info.add(eventDetail);
            }
        }
        //计数map
        HashMap<String, Integer> countMap = new HashMap<>();
        countMap.put("=0", 0);
        countMap.put("<10", 0);
        countMap.put("<20", 0);
        countMap.put("<30", 0);
        countMap.put("<40", 0);
        countMap.put("<50", 0);
        countMap.put("<60", 0);
        countMap.put("<70", 0);
        countMap.put("<80", 0);
        countMap.put("<90", 0);
        //分段计数
        HashMap<String, Integer> subsectionMap = new HashMap<>();
        subsectionMap.put("0", 0);
        subsectionMap.put("0~10", 0);
        subsectionMap.put("10~20", 0);
        subsectionMap.put("20~30", 0);
        subsectionMap.put("30~40", 0);
        subsectionMap.put("40~50", 0);
        subsectionMap.put("50~60", 0);
        subsectionMap.put("60~70", 0);
        subsectionMap.put("70~80", 0);
        subsectionMap.put("80~90", 0);
        //求数量
        for (EventDetail eventDetail : info) {
            if (eventDetail.getFeatureAmplitude() == 0.00) {
                countMap.put("=0", (countMap.get("=0") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.1) {
                countMap.put("<10", (countMap.get("<10") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.2) {
                countMap.put("<20", (countMap.get("<20") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.3) {
                countMap.put("<30", (countMap.get("<30") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.4) {
                countMap.put("<40", (countMap.get("<40") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.5) {
                countMap.put("<50", (countMap.get("<50") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.6) {
                countMap.put("<60", (countMap.get("<60") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.7) {
                countMap.put("<70", (countMap.get("<70") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.8) {
                countMap.put("<80", (countMap.get("<80") + 1));
            }
            if (eventDetail.getFeatureAmplitude() < 0.9) {
                countMap.put("<90", (countMap.get("<90") + 1));
            }
        }
        //求每段数量
        for (EventDetail eventDetail : info) {
            if (eventDetail.getFeatureAmplitude() ==0) {
                subsectionMap.put("0", (subsectionMap.get("0") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0 && eventDetail.getFeatureAmplitude() < 0.1) {
                subsectionMap.put("0~10", (subsectionMap.get("0~10") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.1 && eventDetail.getFeatureAmplitude() < 0.2) {
                subsectionMap.put("10~20", (subsectionMap.get("10~20") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.2 && eventDetail.getFeatureAmplitude() < 0.3) {
                subsectionMap.put("20~30", (subsectionMap.get("20~30") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.3 && eventDetail.getFeatureAmplitude() < 0.4) {
                subsectionMap.put("30~40", (subsectionMap.get("30~40") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.4 && eventDetail.getFeatureAmplitude() < 0.5) {
                subsectionMap.put("40~50", (subsectionMap.get("40~50") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.5 && eventDetail.getFeatureAmplitude() < 0.6) {
                subsectionMap.put("50~60", (subsectionMap.get("50~60") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.6 && eventDetail.getFeatureAmplitude() < 0.7) {
                subsectionMap.put("60~70", (subsectionMap.get("60~70") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.7 && eventDetail.getFeatureAmplitude() < 0.8) {
                subsectionMap.put("70~80", (subsectionMap.get("70~80") + 1));
            } else if (eventDetail.getFeatureAmplitude() > 0.8 && eventDetail.getFeatureAmplitude() < 0.9) {
                subsectionMap.put("80~90", (subsectionMap.get("80~90") + 1));
            }
        }
        //求概率并求pereventvalue
        List<String> pereventvalue = new ArrayList<>();
        Set<String> subsectionSet = subsectionMap.keySet();
        List<String> strings1 = new ArrayList<>();
        strings1.add("0");
        strings1.add("0~10");
        strings1.add("10~20");
        strings1.add("20~30");
        strings1.add("30~40");
        strings1.add("40~50");
        strings1.add("50~60");
        strings1.add("60~70");
        strings1.add("70~80");
        strings1.add("80~90");
        for (int i = 0; i < strings1.size(); i++) {
            for (String s : subsectionSet) {
                if (strings1.get(i).equals(s)) {
                    if (subsectionMap.get(s) == 0) {
                        pereventvalue.add("0.00");
                        break;
                    }
                    if (subsectionMap.get(s) / count.doubleValue() == 1.0) {
                        pereventvalue.add("100.00");
                    } else {
                        String s1 = String.format("%.4f", (subsectionMap.get(s) / count.doubleValue()));
                        pereventvalue.add(s1.substring(2, 4) + "." + s1.substring(4, 6));
                    }
                }
            }
        }
        result.setPereventvalue(pereventvalue);
        //求eventvalue
        List<String> eventvalue = new ArrayList<>();
        List<String> strings = new ArrayList<>();
        strings.add("=0");
        strings.add("<10");
        strings.add("<20");
        strings.add("<30");
        strings.add("<40");
        strings.add("<50");
        strings.add("<60");
        strings.add("<70");
        strings.add("<80");
        strings.add("<90");
        Set<String> countSet = countMap.keySet();
        //保证顺序
        for (int i = 0; i < strings.size(); i++) {
            for (String s : countSet) {
                if (strings.get(i).equals(s)) {
                    if (countMap.get(s) == 0) {
                        eventvalue.add("0.00");
                        break;
                    }
                    if (countMap.get(s) / count.floatValue() == 1.0) {
                        eventvalue.add("100.00");
                    } else {
                        String s1 = String.format("%.4f", (countMap.get(s) / count.doubleValue()));
                        eventvalue.add(s1.substring(2, 4) + "." + s1.substring(4, 6));
                    }
                }
            }
        }
        result.setEventvalue(eventvalue);
        //时间
        HashMap<String, Integer> timeMap = new HashMap<>();
        timeMap.put("<0.01", 0);
        timeMap.put("<0.1", 0);
        timeMap.put("<0.25", 0);
        timeMap.put("<0.5", 0);
        timeMap.put("<1", 0);
        timeMap.put("<3", 0);
        timeMap.put("<20", 0);
        timeMap.put("<60", 0);
        timeMap.put("<180", 0);
        //求不同时间段的总数
        for (EventDetail eventDetail : info) {
            Double persistTime = eventDetail.getDuration();
            if (persistTime < 0.01 ) {
                timeMap.put("<0.1", timeMap.get("<0.1") + 1);
            } else if (persistTime >= 0.01 && persistTime < 0.1) {
                timeMap.put("<0.1", timeMap.get("<0.1") + 1);
            } else if (persistTime  >= 0.1 && persistTime  < 0.25) {
                timeMap.put("<0.25", timeMap.get("<0.25") + 1);
            } else if (persistTime  >= 0.25 && persistTime  < 0.5) {
                timeMap.put("<0.5", timeMap.get("<0.5") + 1);
            } else if (persistTime  >= 0.5 && persistTime  < 1) {
                timeMap.put("<1", timeMap.get("<1") + 1);
            } else if (persistTime  >= 1 && persistTime  < 3) {
                timeMap.put("<3", timeMap.get("<3") + 1);
            } else if (persistTime  >= 3 && persistTime  < 20) {
                timeMap.put("<20", timeMap.get("<20") + 1);
            } else if (persistTime  >= 20 && persistTime  < 60) {
                timeMap.put("<60", timeMap.get("<60") + 1);
            } else if (persistTime  >= 60 && persistTime  < 180) {
                timeMap.put("<180", timeMap.get("<180") + 1);
            }
        }
        List<String> strings2 = new ArrayList<>();
        strings2.add("<0.01");
        strings2.add("<0.1");
        strings2.add("<0.25");
        strings2.add("<0.5");
        strings2.add("<1");
        strings2.add("<3");
        strings2.add("<20");
        strings2.add("<60");
        strings2.add("<180");
        //求persisttime
        List<String> persisttime = new ArrayList<>();
        Set<String> timeSet = timeMap.keySet();
        for (int i = 0; i < strings2.size(); i++) {
            for (String s : timeSet) {
                if (strings2.get(i).equals(s)) {
                    if (timeMap.get(s) == 0) {
                        persisttime.add("0.00");
                        break;
                    }
                    if (timeMap.get(s) / count.floatValue() == 1.0) {
                        persisttime.add("100.00");
                    } else {
                        String s1 = String.format("%.4f", (timeMap.get(s) / count.doubleValue()));
                        persisttime.add(s1.substring(2, 4) + "." + s1.substring(4, 6));
                    }
                }
            }
        }
        result.setPersisttime(persisttime);

        HashMap<String, Integer> timeMap2 = new HashMap<>();
        timeMap2.put("<0.01", 0);
        timeMap2.put("<0.1", 0);
        timeMap2.put("<0.25", 0);
        timeMap2.put("<0.5", 0);
        timeMap2.put("<1", 0);
        timeMap2.put("<3", 0);
        timeMap2.put("<20", 0);
        timeMap2.put("<60", 0);
        timeMap2.put("<180", 0);
        //求sisttime
        List<String> sisttime = new ArrayList<>();
        for (EventDetail eventDetail : info) {
            Double persistTime = eventDetail.getDuration();
            if (persistTime < 0.01) {
                timeMap2.put("<0.01", timeMap2.get("<0.01") + 1);
            }
            if (persistTime < 0.1) {
                timeMap2.put("<0.1", timeMap2.get("<0.1") + 1);
            }
            if (persistTime < 0.25) {
                timeMap2.put("<0.25", timeMap2.get("<0.25") + 1);
            }
            if (persistTime < 0.5) {
                timeMap2.put("<0.5", timeMap2.get("<0.5") + 1);
            }
            if (persistTime < 1) {
                timeMap2.put("<1", timeMap2.get("<1") + 1);
            }
            if (persistTime < 3) {
                timeMap2.put("<3", timeMap2.get("<3") + 1);
            }
            if (persistTime < 20) {
                timeMap2.put("<20", timeMap2.get("<20") + 1);
            }
            if (persistTime < 60) {
                timeMap2.put("<60", timeMap2.get("<60") + 1);
            }
            if (persistTime < 180) {
                timeMap2.put("<180", timeMap2.get("<180") + 1);
            }
        }
        Set<String> time2Set = timeMap2.keySet();
        for (int i = 0; i < strings2.size(); i++) {
            for (String s : time2Set) {
                if (strings2.get(i).equals(s)) {
                    if (timeMap2.get(s) == 0) {
                        sisttime.add("0.00");
                        break;
                    }
                    if (timeMap2.get(s) / count.floatValue() == 1.0) {
                        sisttime.add("100.00");
                    } else {
                        String s1 = String.format("%.4f", (timeMap2.get(s) / count.doubleValue()));
                        sisttime.add(s1.substring(2, 4) + "." + s1.substring(4, 6));
                    }
                }
            }
        }
        result.setSisttime(sisttime);
        return result;
    }

    /**
     * 暂降事件点图
     *
     * @param statisticsParam
     * @return
     * @author xxy
     */
    @Override
    public VoltageToleranceCurveVO getPlot(StatisticsParam statisticsParam) {
        List<EventDetail> result = new ArrayList<>();
//        QueryResult query = MonitorQuery(statisticsParam);
//        InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//        result = influxDBResultMapper.toPOJO(query, EventDetail.class);
//        //添加detail
//        for (EventDetail detail : result) {
//            if (detail.getWaveType() == 1) {
//                for (DictData data : reasonData) {
//                    if (detail.getEventReason().equals(data.getId())) {
//                        detail.setEventReason(data.getName());
//                    }
//                }
//                for (DictData data : typeData) {
//                    if (detail.getEventType().equals(data.getId())) {
//                        detail.setEventType(data.getName());
//                    }
//                }
//            }
//        }
        //获取电压暂降信息
//        List<DictData> data = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_STATIS.getCode()).getData();
//        List<String> typeList = data.stream().filter(it->it.getCode().equals(DicDataEnum.VOLTAGE_DIP.getCode()) || it.getCode().equals(DicDataEnum.SHORT_INTERRUPTIONS.getCode())).map(DictData::getId).collect(Collectors.toList());
        //查询监测点未处理暂态事件
        List<RmpEventDetailPO> eventDetails = eventDetailService.list(new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, statisticsParam.getLineIndex())
//                .in(RmpEventDetailPO::getEventType,typeList)
                .ge(StringUtils.isNotBlank(statisticsParam.getStartTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(statisticsParam.getStartTime())))
                .le(StringUtils.isNotBlank(statisticsParam.getEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(statisticsParam.getEndTime())))
        );
        //获取字典属性
        List<DictData> reasonData = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_REASON.getCode()).getData();
        Map<String, DictData> reasonMap = reasonData.stream().collect(Collectors.toMap(DictData::getId, Function.identity(), (kye1, key2) -> kye1));
        List<DictData> typeData = dicDataFeignClient.getDicDataByTypeCode(DicDataTypeEnum.EVENT_TYPE.getCode()).getData();
        Map<String, DictData> typeMap = typeData.stream().collect(Collectors.toMap(DictData::getId, Function.identity(), (kye1, key2) -> kye1));

        EventDetail eventDetailNew;
        for (RmpEventDetailPO eventDetail : eventDetails) {
            eventDetailNew = BeanUtil.copyProperties(eventDetail, EventDetail.class);
            //监测点id
            eventDetailNew.setLineId(eventDetail.getMeasurementPointId());
            //监测点id
            eventDetailNew.setEventId(eventDetail.getEventId());
            //持续时间
            eventDetailNew.setDuration(eventDetail.getDuration());
            //特征幅值
            eventDetailNew.setFeatureAmplitude(eventDetail.getFeatureAmplitude());
            //波形路径
            eventDetailNew.setWavePath(eventDetail.getWavePath());
            //if (data.getId().equals(eventDetail.getEventType())) {
                if (reasonMap.containsKey(eventDetail.getAdvanceReason())) {
                    //暂降原因
                    DictData dictData = reasonMap.get(eventDetail.getAdvanceReason());
                    eventDetailNew.setAdvanceReason(dictData.getName());
                }
                if (typeMap.containsKey(eventDetail.getAdvanceType())) {
                    //事件类型
                    DictData dictData = typeMap.get(eventDetail.getAdvanceType());
                    eventDetailNew.setAdvanceType(dictData.getName());
                }
           // }

            result.add(eventDetailNew);
        }
        if (CollUtil.isEmpty(result)) {
            return VoltageToleranceCurveVO.empty();
        }
        ArrayList<String> lineIds = new ArrayList<>();
        lineIds.add(statisticsParam.getLineIndex());
        List<AreaLineInfoVO> getBaseLineAreaInfo = lineFeignClient.getBaseLineAreaInfo(lineIds).getData();
        if (CollUtil.isEmpty(getBaseLineAreaInfo)) {
            return VoltageToleranceCurveVO.empty();
        }

        Map<String, AreaLineInfoVO> areaLineInfoVOMap =
                getBaseLineAreaInfo.parallelStream().collect(Collectors.toConcurrentMap(AreaLineInfoVO::getLineId,
                        Function.identity()));

        List<VoltageToleranceCurveVO.VoltageToleranceCurveDataList> curveDataList = result.parallelStream()
                .map(dto -> {
                    AreaLineInfoVO info = areaLineInfoVOMap.get(dto.getLineId());

                    VoltageToleranceCurveVO.VoltageToleranceCurveDataList voltageToleranceCurve = new VoltageToleranceCurveVO.VoltageToleranceCurveDataList();
                    voltageToleranceCurve.setLineId(dto.getLineId());
                    voltageToleranceCurve.setEventId(dto.getEventId());
                    voltageToleranceCurve.setPersistTime(dto.getDuration());
                    voltageToleranceCurve.setEventValue(dto.getFeatureAmplitude() * 100);
                    voltageToleranceCurve.setTime(dto.getStartTime());
                    voltageToleranceCurve.setGdName(info.getGdName());
                    voltageToleranceCurve.setSubName(info.getSubName());
                    return voltageToleranceCurve;
                })
                //.sorted(VoltageToleranceCurveDataList.sortAscTime())
                .collect(Collectors.toCollection(() -> Collections.synchronizedList(new ArrayList<>())));

        return VoltageToleranceCurveVO.buildVO(result.size(), curveDataList);
    }

    /**
     * 监测点暂降事件分析查询
     *
     * @author zbj
     * @date 2022/7/25
     */
    @Override
    public Page<WaveTypeVO> getMonitorEventAnalyseQuery(EventBaseParam eventBaseParam) {
        List<DictData> eventReasonList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData();
        List<DictData> eventTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_TYPE.getName()).getData();
        //数据暂降查询
        Page<RmpEventDetailPO> pageInfo = eventDetailService.page(new Page<>(eventBaseParam.getPageNum(), eventBaseParam.getPageSize()), new LambdaQueryWrapper<RmpEventDetailPO>()
                .eq(RmpEventDetailPO::getMeasurementPointId, eventBaseParam.getLineId())
                .ge(StringUtils.isNotBlank(eventBaseParam.getSearchBeginTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime())))
                .le(StringUtils.isNotBlank(eventBaseParam.getSearchEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime())))
                .orderByDesc(RmpEventDetailPO::getStartTime)

        );
        //获取关于监测点发电站相关信息
        List<AreaLineInfoVO> areaLineList = lineFeignClient.getBaseLineAreaInfo(Arrays.asList(eventBaseParam.getLineId())).getData();
        if (CollectionUtil.isEmpty(areaLineList)) {
            throw new BusinessException(EventResponseEnum.NOT_FOUND);
        }
        List<WaveTypeVO> waveTypeVOS = new ArrayList<>();
        List<RmpEventDetailPO> records = pageInfo.getRecords();
        WaveTypeVO waveTypeVO;
        //将监测点发电机相关信息copy到准备好的VO对象中
        for (RmpEventDetailPO record : records) {
            waveTypeVO = BeanUtil.copyProperties(record, WaveTypeVO.class);
            if (waveTypeVO.getLineId() != null) {
                for (AreaLineInfoVO lineInfoVO : areaLineList) {
                    if (waveTypeVO.getLineId().equals(lineInfoVO.getLineId())) {
//                        waveTypeVO.setStartTime(record.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                        waveTypeVO.setStartTime(record.getStartTime());
                        waveTypeVO.setSubName(lineInfoVO.getSubName());
                        waveTypeVO.setLineId(lineInfoVO.getLineId());
                        waveTypeVO.setLineName(lineInfoVO.getLineName());
                        waveTypeVO.setGdId(lineInfoVO.getGdId());
                        waveTypeVO.setGdName(lineInfoVO.getGdName());
                        waveTypeVO.setVoltageId(lineInfoVO.getVoltageId());
                        waveTypeVO.setNoDealCount(lineInfoVO.getNoDealCount());
                        waveTypeVO.setCt1(lineInfoVO.getCt1());
                        waveTypeVO.setCt2(lineInfoVO.getCt2());
                        waveTypeVO.setPt1(lineInfoVO.getPt1());
                        waveTypeVO.setPt2(lineInfoVO.getPt2());
                        waveTypeVO.setRunFlag(lineInfoVO.getRunFlag());
                        waveTypeVO.setComFlag(lineInfoVO.getComFlag());
                        waveTypeVO.setIp(lineInfoVO.getIp());
                        waveTypeVO.setLat(lineInfoVO.getLat());
                        waveTypeVO.setLng(lineInfoVO.getLng());
                        waveTypeVO.setManufacturer(lineInfoVO.getManufacturer());
                        waveTypeVO.setVoltageScale(lineInfoVO.getVoltageScale());
                        //查询字典表替换事件原因与事件类型的字符串
                        if (waveTypeVO.getAdvanceReason() != null) {
                            for (DictData dictData : eventReasonList) {
                                //将字典数据id与VO中属性eventReason对应的字符串进行比较
                                if (waveTypeVO.getAdvanceReason().equals(dictData.getId())) {
                                    waveTypeVO.setAdvanceReason(dictData.getName());
                                }
                            }
                        }

                        if (waveTypeVO.getAdvanceType() != null) {
                            for (DictData dictData : eventTypeList) {
                                //将字典数据id与VO中属性eventType对应的字符串进行比较
                                if (waveTypeVO.getAdvanceType().equals(dictData.getId())) {
                                    waveTypeVO.setAdvanceType(dictData.getName());
                                }
                            }
                        }
                        waveTypeVOS.add(waveTypeVO);
                    }
                }
            } else {
                //抛出异常,当前监测点id为空
                throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
            }
        }
        Page<WaveTypeVO> page = BeanUtil.copyProperties(pageInfo, Page.class);
        page.setRecords(waveTypeVOS);
        return page;
//        //提前创建结果集合
//        List<WaveTypeVO> eventDetailList = new ArrayList<>();
//
//        //创建line_id集合,将入参line_id塞进去
//        List<String> lineIds = new ArrayList<>();
//        lineIds.add(eventBaseParam.getLineId());
//
//        //提前创建total
//        StringBuilder stringTotal = new StringBuilder();
//
//
//        //查询参数不为空,进行条件填充
//        if (ObjectUtil.isNotNull(eventBaseParam.getSearchValue())) {
//            //查询sql语句
//            StringBuilder stringResult = new StringBuilder(Param.SELECT).append(Param.EVENT_DETAIL).append(Param.WHERE).
//                    append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime()))).append("' and ")
//                    .append("line_id= '").append(eventBaseParam.getLineId()).append("'");
//
//            //套用公式(page-1)*pageSize
//            int i = (eventBaseParam.getPageNum() - 1) * eventBaseParam.getPageSize();
//            //拼接分页sql
//            stringResult.append("LIMIT ").append(eventBaseParam.getPageSize()).append(" OFFSET ").append(i).append("  tz('Asia/Shanghai')");
//
//
//            //查询sql语句总条数
//            stringTotal = new StringBuilder("SELECT COUNT(num) as aa FROM ").append(Param.EVENT_DETAIL).append(" WHERE ").append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime()))).append("' and ")
//                    .append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime()))).append("' and ");
//            stringTotal.append("line_id= '").append(eventBaseParam.getLineId()).append("' tz('Asia/Shanghai')");
//
//            //结果集
//            QueryResult result = influxDbUtils.query(stringResult.toString());
//            //总条数
//            QueryResult resultTotal = influxDbUtils.query(stringTotal.toString());
//
//            //结果集映射到对象中
//            InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//            eventDetailList = influxDBResultMapper.toPOJO(result, WaveTypeVO.class);
//
//
//            //获取关于监测点发电站相关信息
//            HttpResult<List<AreaLineInfoVO>> baseLineAreaInfo = lineFeignClient.getBaseLineAreaInfo(lineIds);
//            System.out.println(baseLineAreaInfo);
//            //将返回的封装好的结果集进行还原成集合
//            List<AreaLineInfoVO> areaLineList = baseLineAreaInfo.getData();
//
//
//            //将监测点发电机相关信息copy到准备好的VO对象中
//            for (WaveTypeVO waveTypeVO : eventDetailList) {
//                if (waveTypeVO.getLineId() != null) {
//                    for (AreaLineInfoVO lineInfoVO : areaLineList) {
//                        if (waveTypeVO.getLineId().equals(lineInfoVO.getLineId())) {
//                            waveTypeVO.setSubName(lineInfoVO.getSubName());
//                            waveTypeVO.setLineId(lineInfoVO.getLineId());
//                            waveTypeVO.setLineName(lineInfoVO.getLineName());
//                            waveTypeVO.setGdId(lineInfoVO.getGdId());
//                            waveTypeVO.setGdName(lineInfoVO.getGdName());
//                            waveTypeVO.setVoltageId(lineInfoVO.getVoltageId());
//                            waveTypeVO.setNoDealCount(lineInfoVO.getNoDealCount());
//                            waveTypeVO.setCt1(lineInfoVO.getCt1());
//                            waveTypeVO.setCt2(lineInfoVO.getCt2());
//                            waveTypeVO.setPt1(lineInfoVO.getPt1());
//                            waveTypeVO.setPt2(lineInfoVO.getPt2());
//                            waveTypeVO.setRunFlag(lineInfoVO.getRunFlag());
//                            waveTypeVO.setComFlag(lineInfoVO.getComFlag());
//                            waveTypeVO.setIp(lineInfoVO.getIp());
//                            waveTypeVO.setLat(lineInfoVO.getLat());
//                            waveTypeVO.setLng(lineInfoVO.getLng());
//                            waveTypeVO.setManufacturer(lineInfoVO.getManufacturer());
//                            waveTypeVO.setVoltageScale(lineInfoVO.getVoltageScale());
//                        }
//                    }
//                } else {
//                    //抛出异常,当前监测点id为空
//                    throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
//                }
//            }
//
//            //使用字典表对暂态类型和暂态原因进行转换
//            HttpResult<List<DictData>> reason = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName());
//            HttpResult<List<DictData>> type = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_TYPE.getName());
//            //获取字典数据暂态原因集合
//            List<DictData> eventReasonList = reason.getData();
//            //System.out.println(eventReasonList);
//            //获取字典数据暂态类型集合
//            List<DictData> eventTypeList = type.getData();
//            //System.out.println(eventTypeList);
//
//
//            //查询字典表替换事件原因与事件类型的字符串
//            for (WaveTypeVO eventDetail : eventDetailList) {
//                if (eventDetail.getEventReason() != null) {
//                    for (DictData dictData : eventReasonList) {
//                        //将字典数据id与VO中属性eventReason对应的字符串进行比较
//                        if (eventDetail.getEventReason().equals(dictData.getId())) {
//                            eventDetail.setEventReason(dictData.getName());
//                        }
//                    }
//                } else {
//                    //抛出异常,当前暂态原因为空
//                    throw new BusinessException(EventResponseEnum.EVENT_REASON_NOT_FOUND);
//                }
//            }
//
//            for (WaveTypeVO eventDetail : eventDetailList) {
//                if (eventDetail.getEventType() != null) {
//                    for (DictData dictData : eventTypeList) {
//                        //将字典数据id与VO中属性eventType对应的字符串进行比较
//                        if (eventDetail.getEventType().equals(dictData.getId())) {
//                            eventDetail.setEventType(dictData.getName());
//                        }
//                    }
//                } else {
//                    //抛出异常,当前暂态类型为空
//                    throw new BusinessException(EventResponseEnum.EVENT_TYPE_NOT_FOUND);
//                }
//            }
//            Page<WaveTypeVO> page = new Page<>();
//            page.setTotal(eventDetailList.size());
//            page.setRecords(eventDetailList);
//            page.setCurrent(eventBaseParam.getPageNum());
//            page.setSize(eventBaseParam.getPageSize());
//            return page;
//
//
//        } else {
//            StringBuilder stringResult = new StringBuilder(Param.SELECT).append(Param.EVENT_DETAIL).append(Param.WHERE).
//                    append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime()))).append("' and ")
//                    .append("line_id= '").append(eventBaseParam.getLineId()).append("'");
//
//
//            int i = (eventBaseParam.getPageNum() - 1) * eventBaseParam.getPageSize();
//
//            stringResult.append("LIMIT ").append(eventBaseParam.getPageSize()).append(" OFFSET ").append(i).append("  tz('Asia/Shanghai')");
//
//            //查询sql语句总条数
//            stringTotal = new StringBuilder("SELECT COUNT(num) as aa FROM ").append(Param.EVENT_DETAIL).append(" WHERE ").append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime()))).append("' and ")
//                    .append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime()))).append("' and ");
//            stringTotal.append("line_id= '").append(eventBaseParam.getLineId()).append("' tz('Asia/Shanghai')");
//
//
//            //结果集
//            QueryResult result = influxDbUtils.query(stringResult.toString());
//            //总条数
//            QueryResult resultTotal = influxDbUtils.query(stringTotal.toString());
//
//            //结果集映射到对象中
//            InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
//            eventDetailList = influxDBResultMapper.toPOJO(result, WaveTypeVO.class);
//
//
//            //获取关于监测点发电站相关信息
//            HttpResult<List<AreaLineInfoVO>> baseLineAreaInfo = lineFeignClient.getBaseLineAreaInfo(lineIds);
//            System.out.println(baseLineAreaInfo);
//            //将返回的封装好的结果集进行还原成集合
//            List<AreaLineInfoVO> areaLineList = baseLineAreaInfo.getData();
//
//
//            //将监测点发电机相关信息copy到准备好的VO对象中
//            for (WaveTypeVO waveTypeVO : eventDetailList) {
//                if (waveTypeVO.getLineId() != null) {
//                    for (AreaLineInfoVO lineInfoVO : areaLineList) {
//                        if (waveTypeVO.getLineId().equals(lineInfoVO.getLineId())) {
//                            waveTypeVO.setSubName(lineInfoVO.getSubName());
//                            waveTypeVO.setLineId(lineInfoVO.getLineId());
//                            waveTypeVO.setLineName(lineInfoVO.getLineName());
//                            waveTypeVO.setGdId(lineInfoVO.getGdId());
//                            waveTypeVO.setGdName(lineInfoVO.getGdName());
//                            waveTypeVO.setVoltageId(lineInfoVO.getVoltageId());
//                            waveTypeVO.setNoDealCount(lineInfoVO.getNoDealCount());
//                            waveTypeVO.setCt1(lineInfoVO.getCt1());
//                            waveTypeVO.setCt2(lineInfoVO.getCt2());
//                            waveTypeVO.setPt1(lineInfoVO.getPt1());
//                            waveTypeVO.setPt2(lineInfoVO.getPt2());
//                            waveTypeVO.setRunFlag(lineInfoVO.getRunFlag());
//                            waveTypeVO.setComFlag(lineInfoVO.getComFlag());
//                            waveTypeVO.setIp(lineInfoVO.getIp());
//                            waveTypeVO.setLat(lineInfoVO.getLat());
//                            waveTypeVO.setLng(lineInfoVO.getLng());
//                            waveTypeVO.setManufacturer(lineInfoVO.getManufacturer());
//                            waveTypeVO.setVoltageScale(lineInfoVO.getVoltageScale());
//                        }
//                    }
//                } else {
//                    //抛出异常,当前监测点id为空
//                    throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
//                }
//            }
//
//
//            //使用字典表对暂态类型和暂态原因进行转换
//            HttpResult<List<DictData>> reason = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName());
//            HttpResult<List<DictData>> type = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_TYPE.getName());
//            //获取字典数据暂态原因集合
//            List<DictData> eventReasonList = reason.getData();
//            //System.out.println(eventReasonList);
//            //获取字典数据暂态类型集合
//            List<DictData> eventTypeList = type.getData();
//            //System.out.println(eventTypeList);
//
//
//            //查询字典表替换事件原因与事件类型的字符串
//            for (WaveTypeVO eventDetail : eventDetailList) {
//                if (eventDetail.getEventReason() != null) {
//                    for (DictData dictData : eventReasonList) {
//                        //将字典数据id与VO中属性eventReason对应的字符串进行比较
//                        if (eventDetail.getEventReason().equals(dictData.getId())) {
//                            eventDetail.setEventReason(dictData.getName());
//                            break;
//                        }
//                    }
//                } else {
//                    //抛出异常,当前暂态原因为空
//                    throw new BusinessException(EventResponseEnum.EVENT_REASON_NOT_FOUND);
//                }
//
//                if (eventDetail.getEventType() != null) {
//                    for (DictData dictData : eventTypeList) {
//                        //将字典数据id与VO中属性eventType对应的字符串进行比较
//                        if (eventDetail.getEventType().equals(dictData.getId())) {
//                            eventDetail.setEventType(dictData.getName());
//                            break;
//                        }
//                    }
//                } else {
//                    //抛出异常,当前暂态类型为空
//                    throw new BusinessException(EventResponseEnum.EVENT_TYPE_NOT_FOUND);
//                }
//            }
//
//
//            Page<WaveTypeVO> page = new Page<>();
//            long total = eventDetailList.size();
//            page.setTotal(total);
//            page.setRecords(eventDetailList);
//            page.setCurrent(eventBaseParam.getPageNum());
//            page.setSize(eventBaseParam.getPageSize());
//            return page;
//        }

    }

    @Override
    public String determineDropZone(String eventValue, String persistTime) {
        if (eventValue == null || eventValue.trim().isEmpty()
                || persistTime == null || persistTime.trim().isEmpty()) {
            log.warn("判定压降落点区域入参为空，eventValue={}, persistTime={}", eventValue, persistTime);
            return null;
        }
        BigDecimal vvm;
        BigDecimal vvtm;
        try {
            // params[3] 是百分比（如 "80.5"），/100 得到 0~1 的 VVm
            vvm = new BigDecimal(eventValue.trim()).divide(new BigDecimal("100"), 6, RoundingMode.HALF_UP);
            vvtm = new BigDecimal(persistTime.trim());
        } catch (Exception e) {
            log.error("判定压降落点区域入参解析失败，eventValue={}, persistTime={}", eventValue, persistTime, e);
            return null;
        }

        // 1) 超短脉冲 或 完全失压 默认 A 区
        if (vvtm.compareTo(new BigDecimal("0.001")) < 0
                || vvm.compareTo(BigDecimal.ZERO) == 0) {
            return "A区";
        }

        // 2) 区间表（左闭右开）
        // A区
        if (inRange(vvm, "0.9", "1") && inRange(vvtm, "0.001", "60")) {
            return "A区";
        }
        if (inRange(vvm, "0", "0.9") && inRange(vvtm, "0.001", "0.05")) {
            return "A区";
        }
        // B区
        if (inRange(vvm, "0.5", "0.7") && inRange(vvtm, "0.05", "0.2")) {
            return "B区";
        }
        if (inRange(vvm, "0.7", "0.8") && inRange(vvtm, "0.05", "0.5")) {
            return "B区";
        }
        if (inRange(vvm, "0.8", "0.9") && inRange(vvtm, "0.05", "60")) {
            return "B区";
        }
        // C区
        if (inRange(vvm, "0", "0.5") && inRange(vvtm, "0.05", "1")) {
            return "C区";
        }
        if (inRange(vvm, "0.5", "0.7") && inRange(vvtm, "0.2", "1")) {
            return "C区";
        }
        if (inRange(vvm, "0.7", "0.8") && inRange(vvtm, "0.5", "1")) {
            return "C区";
        }
        // D区
        if (inRange(vvm, "0", "0.8") && inRange(vvtm, "1", "60")) {
            return "D区";
        }

        log.warn("压降落点区域未匹配任何规则，eventValue={}, persistTime={}", eventValue, persistTime);
        return null;
    }

    /**
     * 左闭右开区间判断：lowerInclusive ≤ value < upperExclusive
     */
    private boolean inRange(BigDecimal value, String lowerInclusive, String upperExclusive) {
        return value.compareTo(new BigDecimal(lowerInclusive)) >= 0
                && value.compareTo(new BigDecimal(upperExclusive)) < 0;
    }


    /**
     * 监测点事件波形下载
     *
     * @author zbj
     * @date 2022/7/28
     */
  /*  @Override
    public HttpServletResponse downloadMonitorEventWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception {
        List<String> lineId = waveFileParam.getLineId();
        List<String> timeId = waveFileParam.getTimeId();
        copyTempData(timeId, lineId);

        LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId.get(0)).getData();


        // TODO 1
        //压缩的文件夹名用检测点名进行命名
        zipCompress(new File(generalInfo.getBusinessTempPath() + File.separator + lineDetailData.getLineName()));


        //使用自定义压缩文件名进行测试
        //zipCompress(new File("C:\\Users\\User\\Desktop\\" + lineDetailData.getLineName()));


        // TODO 1
        //对压缩文件名进行字符串拼接
        String zipPath = generalInfo.getBusinessTempPath() + File.separator + lineDetailData.getLineName() + "波形文件" + ".zip";


        //使用自定义压缩文件名进行测试
        // String zipPath ="C:\\Users\\User\\Desktop\\"+lineDetailData.getLineName()+".zip";


        try {
            // path是指欲下载的文件的路径。
            File file = new File(zipPath);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(zipPath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        //这里会删除压缩文件
        delFile(zipPath);
        deleteDirectoryLegacyIO(new File(generalInfo.getBusinessTempPath() + File.separator + "comtrade"));
        return response;
    }*/

    /**
     * 复制保存文件
     */
    public void copyTempData(List<String> timeId, List<String> lineId) throws IOException {
        for (int i = 0; i < timeId.size(); i++) {
            //根据监测点id获取监测点详情
            LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId.get(i)).getData();
            EventDetail eventDetailByTime = eventDetailService.getEventDetailByTime(lineId.get(i), timeId.get(i));
            if (Objects.isNull(lineDetailData.getIp()) && Objects.isNull(eventDetailByTime.getWavePath())) {
                throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
            }
            String ip = lineDetailData.getIp();
            String waveName = eventDetailByTime.getWavePath();

            // TODO 1
            File srcCFGFile = new File(generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + ".CFG");
            File srcDATFile = new File(generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + ".DAT");


            //使用本地的波形文件进行测试
//            File srcCFGFile = new File("C:\\Users\\User\\Desktop\\comtrade\\1\\PQMonitor_PQM1_002038_20220602_040510_117.CFG");
//            File srcDATFile = new File("C:\\Users\\User\\Desktop\\comtrade\\1\\PQMonitor_PQM1_002038_20220602_040510_117.DAT");


            // TODO 1
            if (!srcCFGFile.exists() && !srcDATFile.exists()) {
                throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
            }

            // TODO 1
            File temp = new File(generalInfo.getBusinessTempPath() + File.separator + lineDetailData.getLineName());
            temp.mkdirs();


            //使用本地创建的文件夹进行测试
//            File temp = new File("C:\\Users\\User\\Desktop\\" + lineDetailData.getLineName());
//            temp.mkdirs();


            //使用本地创建的文件夹进行测试
//            File cfg = new File("C:\\Users\\User\\Desktop\\" + lineDetailData.getLineName() + File.separator + srcCFGFile.getName());
//            File dat = new File("C:\\Users\\User\\Desktop\\" + lineDetailData.getLineName() + File.separator + srcDATFile.getName());


            // TODO 1
            File cfg = new File(generalInfo.getBusinessTempPath() + File.separator + lineDetailData.getLineName() + File.separator + srcCFGFile.getName());
            File dat = new File(generalInfo.getBusinessTempPath() + File.separator + lineDetailData.getLineName() + File.separator + srcDATFile.getName());


            writeFile(srcCFGFile, cfg);
            writeFile(srcDATFile, dat);
        }
    }

    //读写文件
    public static void writeFile(File wave, File temp) throws IOException {
        FileInputStream fis = new FileInputStream(wave);
        FileOutputStream fos = new FileOutputStream(temp);
        int len;
        byte[] bys = new byte[1024];
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
            fos.flush();
        }
        fos.close();
        fis.close();
    }


    /**
     * 将文件夹及文件夹包含的内容压缩成zip文件
     * (为了解决中文乱码的问题，ZipOutputStream用org.apache.tools.zip.*)
     *
     * @param inputFile 源文件(夹)
     * @return File 压缩后的文件(路径在源文件的文件夹路径下)
     */
    public static File zipCompress(File inputFile) throws Exception {
        File zipFile = null;
        ZipOutputStream zos = null;
        if (inputFile != null && inputFile.exists()) {
            try {
                String path = inputFile.getCanonicalPath();
                String zipFileName = path + ".zip";
                zipFile = new File(zipFileName);
                if (zipFile.exists()) {
                    zipFile.delete();
                }
                zipFile.createNewFile();//创建文件
                zos = new ZipOutputStream(new FileOutputStream(zipFile));
                //压缩文件或文件夹
                compressFile(zos, inputFile, inputFile.getName());
            } catch (Exception e) {
                System.out.println("文件压缩异常：" + e);
                throw e;
            } finally {
                try {
                    if (zos != null) {
                        //先调用outputStream的flush()再关闭流；
                        //流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象
                        zos.flush();
                        zos.close();
                    }
                } catch (Exception ex) {
                    System.out.println("输出流关闭异常：" + ex);
                }
            }
        }
        return zipFile;
    }

    /**
     * 压缩文件或文件夹   (ZipEntry 使用org.apache.tools.zip.*，不要用 java.util.zip.*)
     *
     * @param zos        zip输出流
     * @param sourceFile 源文件
     * @param baseName   父路径
     * @throws Exception 异常
     */
    public static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws Exception {
        if (!sourceFile.exists()) {
            return;
        }
        //若路径为目录（文件夹）
        if (sourceFile.isDirectory()) {
            //取出文件夹中的文件（或子文件夹）
            File[] fileList = sourceFile.listFiles();
            //若文件夹为空，则创建一个目录进入点
            if (fileList.length == 0) {
                //文件名称后跟File.separator表示这是一个文件夹
                zos.putNextEntry(new ZipEntry(baseName + File.separator));

                //若文件夹非空，则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩
            } else {
                for (int i = 0; i < fileList.length; i++) {
                    compressFile(zos, fileList[i],
                            baseName + File.separator + fileList[i].getName());
                }
            }

            //若为文件,则先创建目录进入点,再将文件写入zip文件中
        } else {
            ZipEntry ze = new ZipEntry(baseName);
            //设置ZipEntry的最后修改时间为源文件的最后修改时间
            ze.setTime(sourceFile.lastModified());
            zos.putNextEntry(ze);

            FileInputStream fis = new FileInputStream(sourceFile);
            copyStream(fis, zos);
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {
                System.out.println("输入流关闭异常：" + e);
            }
        }
    }

    /**
     * 流拷贝
     *
     * @param in  输入流
     * @param out 输出流
     * @throws IOException
     */
    public static void copyStream(InputStream in, OutputStream out) throws IOException {
        int bufferLength = 1024 * 100;
        synchronized (in) {
            synchronized (out) {
                int count = 0;
                byte[] buffer = new byte[bufferLength];
                while ((count = in.read(buffer, 0, bufferLength)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.flush();
            }
        }
    }

    /**
     * 删除文件(夹)和空文件夹
     */
    private void deleteDirectoryLegacyIO(File file) {
        File[] list = file.listFiles();  //无法做到list多层文件夹数据
        if (list != null) {
            for (File temp : list) {     //先去递归删除子文件夹及子文件
                deleteDirectoryLegacyIO(temp);   //注意这里是递归调用
            }
        }
        if (file.delete()) {     //再删除自己本身的文件夹
            System.out.printf("删除成功 : %s%n", file);
        } else {
            System.err.printf("删除失败 : %s%n", file);
        }
    }

    /**
     * 删除文件
     *
     * @param filePathAndName 指定得路径
     */
    public static void delFile(String filePathAndName) {
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            File myDelFile = new File(filePath);
            myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
        }
    }
}
