package com.njcn.event.service.majornetwork.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
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.enums.common.ServerEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.device.pms.api.MonitorClient;
import com.njcn.device.pms.pojo.param.MonitorTerminalParam;
import com.njcn.device.pms.pojo.vo.MonitorVO;
import com.njcn.device.pq.api.DeviceTreeClient;
import com.njcn.device.pq.api.GeneralDeviceInfoClient;
import com.njcn.device.pq.api.LineFeignClient;
import com.njcn.device.pq.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pq.pojo.vo.LineDetailDataVO;
import com.njcn.device.pq.pojo.vo.TerminalTree;
import com.njcn.event.enums.EventResponseEnum;
import com.njcn.event.file.component.WaveFileComponent;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.event.mapper.distribution.PwRmpEventDetailMapper;
import com.njcn.event.common.mapper.RmpEventDetailMapper;
import com.njcn.event.mapper.majornetwork.TransientMapper;
import com.njcn.event.pojo.param.EventVerifyReasonParam;
import com.njcn.event.pojo.param.TransientParam;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.po.EventDetailNew;
import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.event.pojo.vo.TransientVO;
import com.njcn.event.common.service.EventDetailService;
import com.njcn.event.service.majornetwork.TransientService;
import com.njcn.minioss.config.MinIossProperties;
import com.njcn.minioss.util.MinIoUtils;
import com.njcn.oss.constant.GeneralConstant;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author: chenchao
 * @date: 2022/03/29 14:37
 * @Description: <描述>
 */
@Service
@AllArgsConstructor
@Slf4j
public class TransientServiceImpl implements TransientService {

    private final GeneralDeviceInfoClient generalDeviceInfoClient;

    private final LineFeignClient lineFeignClient;

    private final DicDataFeignClient dicDataFeignClient;

    private final TransientMapper transientMapper;

    private final EventDetailService eventDetailService;

    private final GeneralInfo generalInfo;

    private final WaveFileComponent waveFileComponent;

    private final MonitorClient monitorClient;

    private final RmpEventDetailMapper rmpEventDetailMapper;

    private final PwRmpEventDetailMapper pwRmpEventDetailMapper;

    private final FileStorageUtil fileStorageUtil;

    private final DeviceTreeClient deviceTreeClient;

    private final MinIoUtils minIoUtils;

    private final MinIossProperties minIossProperties;


    @Override
    public Page<TransientVO> getTransientData(TransientParam transientParam) {
        Page<TransientVO> page = new Page<>();
        page.setSize(transientParam.getPageSize());
        page.setCurrent(transientParam.getPageNum());
        List<TransientVO> transientVOS = new ArrayList<>();
        transientParam.setServerName(ServerEnum.HARMONIC.getName());
        //按部门分类的实际运行终端综合信息
        List<GeneralDeviceDTO> deviceList = generalDeviceInfoClient.getPracticalRunDeviceInfo(transientParam).getData();
        if (!CollectionUtils.isEmpty(deviceList)) {
            //获取按终端分类的监测点索引集合
            List<String> LineIndexes = deviceList.stream().flatMap(list -> list.getLineIndexes().stream()).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(LineIndexes)) {

                List<EventDetail> eventDetailData = eventDetailService.getEventDetailLimit(LineIndexes, transientParam.getSearchBeginTime(), transientParam.getSearchEndTime(), transientParam.getPageSize(), transientParam.getPageNum(), transientParam.getWaveType());

                if (!CollectionUtils.isEmpty(eventDetailData)) {
                    List<String> lineIds = eventDetailData.stream().map(EventDetail::getLineId).collect(Collectors.toList());
                    lineIds = lineIds.stream().distinct().collect(Collectors.toList());
                    List<TransientVO> transientData = transientMapper.getTransientData(lineIds);
                    int i = 1;
                    for (EventDetail eventDetail : eventDetailData) {
                        if (!Objects.isNull(eventDetail)) {
                            TransientVO transientVO = new TransientVO();
                            transientVO.setId(eventDetail.getLineId());
                            transientVO.setNumber(i++);
                            transientVO.setWaveName(eventDetail.getWavePath());

                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
                            String format = dateTimeFormatter.format(eventDetail.getStartTime());
                            transientVO.setTime(format);
                            switch (eventDetail.getEventType()) {
                                case 0 + "":
                                    transientVO.setTrigType("扰动");
                                    break;
                                case 1 + "":
                                    transientVO.setTrigType("暂降");
                                    break;
                                case 2 + "":
                                    transientVO.setTrigType("暂升");
                                    break;
                                case 3 + "":
                                    transientVO.setTrigType("中断");
                                    break;
                                case 4 + "":
                                    transientVO.setTrigType("其他");
                                    break;
                                case 5 + "":
                                    transientVO.setTrigType("录波");
                                    break;
                            }
                            Double eventValue = new BigDecimal(eventDetail.getFeatureAmplitude()).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
                            transientVO.setEventValue(new BigDecimal(eventValue * 100).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue());
                            transientVO.setEventValues(100 - transientVO.getEventValue());
                            transientVO.setPersistTime((Float.parseFloat(eventDetail.getDuration().toString())) / 1000);

                            transientVO.setYZD(getYZD(Float.parseFloat(eventDetail.getDuration().toString()),
                                    Float.parseFloat(eventDetail.getFeatureAmplitude().toString()))
                            );
                            transientVOS.add(transientVO);
                        }
                    }
                    transientVOS.stream().map(list1 -> transientData.stream().filter(list2 -> Objects.equals(list1.getId(), list2.getId())).findAny().map(m -> {
                        list1.setName(m.getName());
                        list1.setPowerCompany(m.getPowerCompany());
                        list1.setSubstation(m.getSubstation());
                        list1.setNetworkParam(m.getNetworkParam());
                        list1.setVoltageLevel(m.getVoltageLevel());
                        return list1;
                    })).collect(Collectors.toList());
                    //当前页数据
                    page.setRecords(transientVOS);
                }

            }

        }
        return page;
    }

    @Override
    public WaveDataDTO getTransientAnalyseWave(MonitorTerminalParam param) {
        WaveDataDTO waveDataDTO;
        //获取暂降事件
        RmpEventDetailPO eventDetail = rmpEventDetailMapper.getByEventId(param.getId());
        LineDetailDataVO lineDetailData = new LineDetailDataVO();
        MonitorVO monitorVO = new MonitorVO();
        String ip;
        if (param.getSystemType() == 0) {
            lineDetailData = lineFeignClient.getLineDetailData(eventDetail.getMeasurementPointId()).getData();
            ip = lineDetailData.getIp();
        } else {
            param.setId(eventDetail.getMeasurementPointId());
            monitorVO = monitorClient.getMonitorTerminal(param).getData();
            ip = monitorVO.getIp();
        }
        String waveName = eventDetail.getWavePath();
        String cfgPath, datPath, cfgPath2, datPath2;
        if (generalInfo.getBusinessWaveFileStorage() == GeneralConstant.LOCAL_DISK) {
            cfgPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.CFG;
            datPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.DAT;

            //适配文件后缀小写
            cfgPath2 = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.CFG.toLowerCase();
            datPath2 = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.DAT.toLowerCase();
            log.info("本地磁盘波形文件路径----" + cfgPath2);
            log.info("本地磁盘波形文件路径----" + datPath2);
            try (
                InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath);
                InputStream datStream = waveFileComponent.getFileInputStreamByFilePath(datPath);
                )
            {
                if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {

                    throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);

                }
                waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1);



            } catch (Exception e) {
                log.info("大写文件流为空");
                try {
                    InputStream cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath2);
                    InputStream datStream = waveFileComponent.getFileInputStreamByFilePath(datPath2);
                    if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
                        throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                    }
                    waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1);
                } catch (Exception e1) {
                    throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
                }

            }

        } else {
            cfgPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG;
            datPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT;
            //适配文件后缀小写
            cfgPath2 = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG.toLowerCase();
            datPath2 = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT.toLowerCase();
            log.info("文件服务器波形文件路径----" + cfgPath);
            try (
                    InputStream cfgStream = fileStorageUtil.getFileStream(cfgPath);
                    InputStream datStream = fileStorageUtil.getFileStream(datPath)
            ) {
                if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
                    throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                }
                waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1);
            } catch (Exception e) {
                try {
                    InputStream cfgStream = fileStorageUtil.getFileStream(cfgPath2);
                    InputStream datStream = fileStorageUtil.getFileStream(datPath2);
                    if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
                        throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                    }
                    waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, 1);
                } catch (Exception e1) {
                    throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
                }

            }
        }
        waveDataDTO = waveFileComponent.getValidData(waveDataDTO);
        if (param.getSystemType() == 0) {
            waveDataDTO.setPtType(PubUtils.ptTypeName(lineDetailData.getPtType()));
            double pt1 = Double.parseDouble(lineDetailData.getPt().split(StrUtil.SLASH)[0]);
            double pt2 = Double.parseDouble(lineDetailData.getPt().split(StrUtil.SLASH)[1]);
            double ct1 = Double.parseDouble(lineDetailData.getCt().split(StrUtil.SLASH)[0]);
            double ct2 = Double.parseDouble(lineDetailData.getCt().split(StrUtil.SLASH)[1]);
            waveDataDTO.setPt(pt1 / pt2);
            waveDataDTO.setCt(ct1 / ct2);
            return waveDataDTO;
        }
        waveDataDTO.setPtType(Integer.valueOf(monitorVO.getTerminalWiringMethod()));
        waveDataDTO.setPt(monitorVO.getPt1() / monitorVO.getPt2());
        waveDataDTO.setCt(monitorVO.getCt1() / monitorVO.getCt2());
        return waveDataDTO;
    }


    @Override
    public void downloadWaveFile(List<String> eventIds, HttpServletResponse response) {
        copyTempData(eventIds);
        zipCompress(new File(generalInfo.getBusinessTempPath() + File.separator + "comtrade"));
        String zipPath = generalInfo.getBusinessTempPath() + File.separator + "comtrade.zip";
        try {
            // path是指欲下载的文件的路径。
            File file = new File(zipPath);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            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) {
            log.error(LocalDateTime.now() + "压缩波形文件下载异常异常信息" + ex.getMessage());
        }
        delFile(zipPath);
        deleteDirectoryLegacyIO(new File(generalInfo.getBusinessTempPath() + File.separator + "comtrade"));
    }

    @Override
    public Page<EventDetailNew> getTransientValue(TransientParam transientParam) {
        Page<EventDetailNew> page = new Page<>();
        page.setSize(transientParam.getPageSize());
        page.setCurrent(transientParam.getPageNum());
        // 按部门分类的实际运行终端综合信息
        List<GeneralDeviceDTO> generalDeviceDTOList;
        if (transientParam.getIsType() == 0) {
            generalDeviceDTOList = generalDeviceInfoClient.getPracticalRunDeviceInfo(transientParam).getData();
        } else {
            generalDeviceDTOList = generalDeviceInfoClient.getOfflineRunDeviceInfo(transientParam).getData();
        }
        if (!CollectionUtils.isEmpty(generalDeviceDTOList)) {
            if (Objects.nonNull(transientParam.getEventValueMin())) {
                transientParam.setEventValueMin(transientParam.getEventValueMin().divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP));
            }
            if (Objects.nonNull(transientParam.getEventValueMax())) {
                transientParam.setEventValueMax(transientParam.getEventValueMax().divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP));
            }
            // 获取按终端分类的监测点索引集合
            List<String> lineList = generalDeviceDTOList.stream().flatMap(dto -> dto.getLineIndexes().stream()).collect(Collectors.toList());
            List<TerminalTree> data = deviceTreeClient.getTerminalTree().getData();
//            if (!CollectionUtils.isEmpty(transientParam.getSubstationIds())) {
//                List<String> collect = data.stream().map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .filter(temp -> transientParam.getSubstationIds().contains(temp.getId()))
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getId).collect(Collectors.toList());
//                lineList.retainAll(collect);
//            }

            if (!CollectionUtils.isEmpty(transientParam.getLineIds())) {
//                List<String> collect1 = data.stream().map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .map(TerminalTree::getChildren).flatMap(Collection::stream)
//                        .filter(temp -> transientParam.getLineIds().contains(temp.getId()))
//                        .map(TerminalTree::getId).collect(Collectors.toList());
                lineList.retainAll(transientParam.getLineIds());
            }
            if (CollUtil.isEmpty(lineList)) {
                return new Page<>();
            }
            List<AreaLineInfoVO> lineInfoVOList = lineFeignClient.getBaseLineAreaInfo(lineList).getData();
            List<AreaLineInfoVO> filteredLines = lineInfoVOList.stream().filter(item -> filterSearchValue(item, transientParam.getSearchValue())).collect(Collectors.toList());
            List<String> lines = filteredLines.stream().map(AreaLineInfoVO::getLineId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(lines)) {

                LambdaQueryWrapper<RmpEventDetailPO> wrapper = new LambdaQueryWrapper<RmpEventDetailPO>()
                        .in(RmpEventDetailPO::getMeasurementPointId, lines)
                        .ge(StringUtils.isNotBlank(transientParam.getSearchBeginTime()), RmpEventDetailPO::getStartTime, DateUtil.beginOfDay(DateUtil.parse(transientParam.getSearchBeginTime())))
                        .le(StringUtils.isNotBlank(transientParam.getSearchEndTime()), RmpEventDetailPO::getStartTime, DateUtil.endOfDay(DateUtil.parse(transientParam.getSearchEndTime())))
                        // 事件
                        .in(CollUtil.isNotEmpty(transientParam.getWaveType()), RmpEventDetailPO::getEventType, transientParam.getWaveType())
                        .in(CollUtil.isNotEmpty(transientParam.getEventReason()), RmpEventDetailPO::getAdvanceReason, transientParam.getEventReason())
                        .in(CollUtil.isNotEmpty(transientParam.getEventType()), RmpEventDetailPO::getAdvanceType, transientParam.getEventType());


                if (StrUtil.isNotBlank(transientParam.getOrderBy())) {
                    if (transientParam.getSortBy().equals("start_time")) {
                        wrapper.orderBy(true, transientParam.getOrderBy().equals("asc"), RmpEventDetailPO::getStartTime);
                    } else if (transientParam.getSortBy().equals("feature_amplitude")) {
                        wrapper.orderBy(true, transientParam.getOrderBy().equals("asc"), RmpEventDetailPO::getFeatureAmplitude);
                    } else if (transientParam.getSortBy().equals("firstMs")) {
                        wrapper.orderBy(true, transientParam.getOrderBy().equals("asc"), RmpEventDetailPO::getFirstMs);
                    } else if (transientParam.getSortBy().equals("duration")) {
                        wrapper.orderBy(true, transientParam.getOrderBy().equals("asc"), RmpEventDetailPO::getDuration);
                    }
                } else {
                    wrapper.orderByDesc(RmpEventDetailPO::getStartTime);
                }

                //暂态幅值
                if (Objects.nonNull(transientParam.getEventValueMin())) {
                    wrapper.ge(RmpEventDetailPO::getFeatureAmplitude, transientParam.getEventValueMin());
                }
                if (Objects.nonNull(transientParam.getEventValueMax())) {
                    wrapper.le(RmpEventDetailPO::getFeatureAmplitude, transientParam.getEventValueMax());
                }
                if (Objects.nonNull(transientParam.getPersistMin()) && Objects.nonNull(transientParam.getSeverityMax())) {
                    wrapper.ge(RmpEventDetailPO::getDuration, transientParam.getPersistMin()).le(RmpEventDetailPO::getDuration, transientParam.getPersistMax());
                }
                //严重度
                if (Objects.nonNull(transientParam.getSeverityMin()) && Objects.nonNull(transientParam.getSeverityMax())) {
                    wrapper.ge(RmpEventDetailPO::getSeverity, transientParam.getSeverityMin()).le(Objects.nonNull(transientParam.getSeverityMax()), RmpEventDetailPO::getSeverity, transientParam.getSeverityMax());
                }
                //波形文件
                if (Objects.nonNull(transientParam.getFileFlag())) {
                    wrapper.eq(Objects.nonNull(transientParam.getFileFlag()), RmpEventDetailPO::getFileFlag, transientParam.getFileFlag());
                }
                wrapper.in(!CollectionUtils.isEmpty(transientParam.getVerifyReason()), RmpEventDetailPO::getVerifyReason, transientParam.getVerifyReason());
                // Page<RmpEventDetailPO> pageInfo = eventDetailService.page(new Page<>(transientParam.getPageNum(), transientParam.getPageSize()),wrapper);
                Page<RmpEventDetailPO> pageInfo = pwRmpEventDetailMapper.selectPage(new Page<>(transientParam.getPageNum(), transientParam.getPageSize()), wrapper);
                List<EventDetailNew> eventDetailData = BeanUtil.copyToList(pageInfo.getRecords(), EventDetailNew.class);
                page = BeanUtil.copyProperties(pageInfo, Page.class);
                if (CollUtil.isNotEmpty(eventDetailData)) {
                    List<String> lineIds = eventDetailData.stream().map(EventDetailNew::getLineId).distinct().collect(Collectors.toList());
                    List<AreaLineInfoVO> r = lineFeignClient.getBaseLineAreaInfo(lineIds).getData();
                    List<DictData> reasonList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData();
                    List<DictData> typeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_TYPE.getName()).getData();
                    for (EventDetailNew eventDetail : eventDetailData) {
                        DecimalFormat df = new DecimalFormat("#0.000");
                        eventDetail.setSeverity(Double.parseDouble(df.format(Objects.isNull(eventDetail.getSeverity()) ? 0.00 : eventDetail.getSeverity())));
                        for (AreaLineInfoVO areaLineInfoVO : r) {
                            if (eventDetail.getLineId().equals(areaLineInfoVO.getLineId())) {
                                eventDetail.setLineId(areaLineInfoVO.getLineId());
                                eventDetail.setLineName(areaLineInfoVO.getLineName());
                                eventDetail.setGdName(areaLineInfoVO.getGdName());
                                eventDetail.setSubName(areaLineInfoVO.getSubName());
                                eventDetail.setIp(areaLineInfoVO.getIp());
                                eventDetail.setScale(areaLineInfoVO.getVoltageScale());
                                eventDetail.setIp(areaLineInfoVO.getIp());
                                break;
                            }
                        }

                        if (StrUtil.isNotBlank(eventDetail.getAdvanceReason())) {
                            for (DictData dictData : reasonList) {
                                if (eventDetail.getAdvanceReason().equals(dictData.getId())) {
                                    eventDetail.setAdvanceReason(dictData.getName());
                                    break;
                                }
                            }
                        }

                        if (StrUtil.isNotBlank(eventDetail.getAdvanceType())) {
                            for (DictData dictData : typeList) {
                                if (eventDetail.getAdvanceType().equals(dictData.getId())) {
                                    eventDetail.setAdvanceType(dictData.getName());
                                    break;
                                }
                            }
                        }
                    }
                    //当前页数据
                    page.setRecords(eventDetailData);
                }

            }

        }
        return page;
    }

    @Override
    public void updateEventReason(EventVerifyReasonParam eventVerifyReasonParam) {
        eventDetailService.lambdaUpdate()
                .eq(RmpEventDetailPO::getEventId, eventVerifyReasonParam.getEventId())
                .set(RmpEventDetailPO::getVerifyReason, eventVerifyReasonParam.getVerifyReason())
                .set(RmpEventDetailPO::getVerifyReasonDetail, eventVerifyReasonParam.getVerifyReasonDetail())
                .update();
    }


    private boolean filterSearchValue(AreaLineInfoVO item, String searchValue) {
        if (StringUtils.isBlank(searchValue)) {
            return true;
        } else {
            if (StringUtils.contains(item.getGdName(), searchValue)
                    || StringUtils.contains(item.getSubName(), searchValue)
                    || StringUtils.contains(item.getIp(), searchValue)
                    || StringUtils.contains(item.getLineName(), searchValue)
                    || StringUtils.containsIgnoreCase(item.getVoltageScale(), searchValue))
                return true;
        }
        return false;
    }


    /**
     * 复制保存文件
     */
    public void copyTempData(List<String> eventIds) {
        List<RmpEventDetailPO> rmpEventDetailPOList = eventDetailService.listByIds(eventIds);
        List<RmpEventDetailPO> nullWave = rmpEventDetailPOList.stream().filter(item -> Objects.isNull(item.getWavePath())).collect(Collectors.toList());
        if (!nullWave.isEmpty()) {
            throw new BusinessException("请选择存在波形的事件导出!");
        }
        if (CollUtil.isNotEmpty(rmpEventDetailPOList)) {
            String cfg = GeneralConstant.CFG;
            String dat = GeneralConstant.DAT;
            for (RmpEventDetailPO po : rmpEventDetailPOList) {
                //根据监测点id获取监测点详情
                LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(po.getMeasurementPointId()).getData();
                if (Objects.nonNull(lineDetailData)) {
                    String ip = lineDetailData.getIp();
                    String waveName = po.getWavePath();
                    if (StrUtil.isBlank(ip) && StrUtil.isBlank(waveName)) {
                        throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
                    }

                    String cfgPath = "";
                    String datPath = "";
                    InputStream cfgStream = null;
                    InputStream datStream = null;
                    try {
                        if (generalInfo.getBusinessWaveFileStorage() == GeneralConstant.LOCAL_DISK) {
                            cfgPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.CFG;
                            log.info("cfg-----"+cfgPath);
                            log.info("cfg-----"+datPath);


                            //判断文件是否存在
                            File file = new File(cfgPath);
                            if(!file.exists()){
                                cfgPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.CFG_LOWER;
                            }

                            datPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.DAT;
                            File file2 = new File(datPath);
                            if(!file2.exists()){
                                datPath = generalInfo.getBusinessWavePath() + File.separator + ip + File.separator + waveName + GeneralConstant.DAT_LOWER;
                            }
                            log.info("cfg-----"+cfgPath);
                            log.info("cfg-----"+datPath);
                            cfgStream = waveFileComponent.getFileInputStreamByFilePath(cfgPath);
                            datStream = waveFileComponent.getFileInputStreamByFilePath(datPath);

                        } else {
                            cfgPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG;
                            boolean result1 = minIoUtils.checkFileIsExist(minIossProperties.getBucket(), cfgPath);
                            if (!result1) {
                                cfgPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.CFG_LOWER;
                                cfg = GeneralConstant.CFG_LOWER;
                            }

                            datPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT;
                            boolean result2 = minIoUtils.checkFileIsExist(minIossProperties.getBucket(), datPath);
                            if (!result2) {
                                datPath = OssPath.WAVE_DIR + ip + StrUtil.SLASH + waveName + GeneralConstant.DAT_LOWER;
                                dat = GeneralConstant.DAT_LOWER;
                            }

                            System.out.println("波形路径-------------------" + cfgPath);

                            cfgStream = fileStorageUtil.getFileStream(cfgPath);
                            datStream = fileStorageUtil.getFileStream(datPath);

                        }
                        if (Objects.isNull(cfgStream) || Objects.isNull(datStream)) {
                            throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
                        }

                        String fileMu = generalInfo.getBusinessTempPath() + File.separator + "comtrade" + File.separator + ip;
                        File mulu = new File(fileMu);
                        if (!mulu.exists()) {
                            mulu.mkdirs();
                        }
                        File fileCfg = new File(fileMu + File.separator + waveName + cfg);
                        File fileDat = new File(fileMu + File.separator + waveName + dat);

                        fileCfg.createNewFile();
                        fileDat.createNewFile();

                        writeFile(cfgStream, fileCfg);
                        writeFile(datStream, fileDat);

                    } catch (Exception e) {
                        throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
                    } finally {
                        try {
                            if (cfgStream != null) {
                                cfgStream.close();
                            }
                            if (datStream != null) {
                                datStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    //读写文件
    public static void writeFile(InputStream inputStream, File temp) {
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(temp);
            int len;
            byte[] bys = new byte[1024];
            while ((len = inputStream.read(bys)) != -1) {
                fos.write(bys, 0, len);
                fos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


    /**
     * 将文件夹及文件夹包含的内容压缩成zip文件
     * (为了解决中文乱码的问题，ZipOutputStream用org.apache.tools.zip.*)
     *
     * @param inputFile 源文件(夹)
     * @return File 压缩后的文件(路径在源文件的文件夹路径下)
     */
    public static File zipCompress(File inputFile) {
        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) {
                log.error(LocalDateTime.now() + "暂态波形文件压缩异常：" + e.getMessage());
            } finally {
                try {
                    if (zos != null) {
                        //先调用outputStream的flush()再关闭流；
                        //流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象
                        zos.flush();
                        zos.close();
                    }
                } catch (Exception ex) {
                    log.error(LocalDateTime.now() + "输出流关闭异常：" + ex.getMessage());
                }
            }
        }
        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();
            }
        }
    }


    // /**处理文件路径和指定压缩包位置 */
    // public static String downloadWaveMoreFile(List<String> pathList) {
    //     List<File> list = new ArrayList<>();
    //     for (String string: pathList) {
    //         String path = string;
    //         //待压缩的多个源文件
    //         File f1 = new File(path+".CFG");
    //         File f2 = new File(path+".DAT");
    //         list.add(f1);
    //         list.add(f2);
    //     }
    //     File[] srcfile = list.toArray(new File[0]);
    //     String zipPath = "C:\\Users\\陈超\\Desktop\\YSWJ\\新下载的波形文件.zip";
    //     //压缩后的文件存放路径
    //     File zipfile = new File(zipPath);
    //     zipFiles(srcfile, zipfile);
    //     return zipPath;
    // }
    //
    // /**
    //  * 压缩多个文件成一个zip文件
    //  * @param srcfile：源文件列表
    //  * @param zipfile：压缩后的文件
    //  */
    // public static void zipFiles(File[] srcfile, File zipfile) {
    //     byte[] buf = new byte[1024];
    //     try {
    //         //ZipOutputStream类：完成文件或文件夹的压缩
    //         ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
    //         for (int i = 0; i < srcfile.length; i++) {
    //             FileInputStream in = new FileInputStream(srcfile[i]);
    //             out.putNextEntry(new ZipEntry(srcfile[i].getName()));
    //             int len;
    //             while ((len = in.read(buf)) > 0) {
    //                 out.write(buf, 0, len);
    //             }
    //             out.closeEntry();
    //             in.close();
    //         }
    //         out.close();
    //         System.out.println("压缩完成.");
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    // }

    /**
     * 删除文件(夹)和空文件夹
     */
    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();
        }
    }


    /**
     * 获取该事件的严重度
     *
     * @param persistTime 持续时间 ms单位
     * @param eventValue  暂降、暂升幅值
     */
    public static String getYZD(Float persistTime, Float eventValue) {
        float yzd;
        DecimalFormat df = new DecimalFormat("0.000");// 格式化小数
        if (persistTime <= 20) {
            yzd = 1 - eventValue;
        } else if (persistTime > 20 && persistTime <= 200) {
            yzd = 2 * (1 - eventValue);
        } else if (persistTime > 200 && persistTime <= 500) {
            yzd = 3.3f * (1 - eventValue);
        } else if (persistTime > 500 && persistTime <= 10000) {
            yzd = 5 * (1 - eventValue);
        } else {
            yzd = 10 * (1 - eventValue);
        }
        String tempOnlineRate = df.format(yzd);// 返回的是String类型
        return tempOnlineRate;
    }


}
