package com.njcn.csharmonic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.enums.AlgorithmResponseEnum;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.CsLinePO;
import com.njcn.csdevice.pojo.vo.DataGroupEventVO;
import com.njcn.csharmonic.enums.CsEventEnum;
import com.njcn.csharmonic.enums.CsTransientEnum;
import com.njcn.csharmonic.mapper.CsEventPOMapper;
import com.njcn.csharmonic.param.CldEventParam;
import com.njcn.csharmonic.param.CsEventUserQueryPage;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.param.DataParam;
import com.njcn.csharmonic.pojo.param.EventStatisticParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.vo.CsEventVO;
import com.njcn.csharmonic.pojo.vo.CsWarnDescVO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.EventStatisticsVo;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.csharmonic.service.CsEventUserPOService;
import com.njcn.event.common.mapper.WlRmpEventDetailMapper;
import com.njcn.event.file.component.WaveFileComponent;
import com.njcn.event.file.component.WavePicComponent;
import com.njcn.event.file.pojo.bo.WaveDataDetail;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.event.file.utils.WaveUtil;
import com.njcn.event.pojo.po.RmpEventDetailPO;
import com.njcn.influx.pojo.constant.InfluxDBTableConstant;
import com.njcn.influx.pojo.dto.EventDataSetDTO;
import com.njcn.influx.service.EvtDataService;
import com.njcn.influx.utils.InfluxDbUtils;
import com.njcn.minioss.config.MinIossProperties;
import com.njcn.minioss.util.MinIoUtils;
import com.njcn.oss.constant.GeneralConstant;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.api.EleEvtFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.system.pojo.po.DictData;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.njcn.csharmonic.enums.CsTransientEnum.*;

/**
 * Description:
 * Date: 2023/9/4  15:15【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO> implements CsEventPOService {

    private final EvtDataService evtDataService;
    private final FileStorageUtil fileStorageUtil;
    private final WaveFileComponent waveFileComponent;
    private final CsLineFeignClient csLineFeignClient;
    private final CsLedgerFeignClient csLedgerFeignClient;
    private final EpdFeignClient epdFeignClient;
    private final CsEventUserPOService csEventUserPOService;
    private final EleEvtFeignClient eleEvtFeignClient;
    private final WavePicComponent wavePicComponent;
    private final MinIossProperties minIossProperties;
    private final InfluxDbUtils influxDbUtils;
    private final MinIoUtils minIoUtils;
    private final DicDataFeignClient dicDataFeignClient;
    private final WlRmpEventDetailMapper wlRmpEventDetailMapper;
    //private final CommonEventWaveAnalysisService commonEventWaveAnalysisService;
    private final EquipmentFeignClient equipmentFeignClient;

    @Override
    public List<EventDetailVO> queryEventList(CsEventUserQueryParam csEventUserQueryParam) {

        List<EventDetailVO> list = csEventUserPOService.queryUserEventList(csEventUserQueryParam);
        list.forEach(temp -> {
            DevDetailDTO devDetail = csLedgerFeignClient.queryDevDetail(temp.getDeviceId()).getData();
            temp.setEquipmentName(devDetail.getEquipmentName());
            temp.setProjectId(devDetail.getProjectId());
            temp.setProjectName(devDetail.getProjectName());
            temp.setEngineeringid(devDetail.getEngineeringid());
            temp.setEngineeringName(devDetail.getEngineeringName());
            EleEpdPqd data = epdFeignClient.findByName(temp.getTag()).getData();
            List<EleEvtParm> data1 = eleEvtFeignClient.queryByPid(data.getId()).getData();
            List<EventDataSetDTO> eventDataSetDTOS = new ArrayList<>();
            for (EleEvtParm eleEvtParm : data1) {
                EventDataSetDTO eventDataSetDTO = new EventDataSetDTO();
                BeanUtils.copyProperties(eleEvtParm, eventDataSetDTO);
                if (Objects.equals(eventDataSetDTO.getName(),"Evt_Param_Position")) {
                    continue;
//                        eventDataSetDTO.setValue(Objects.equals(temp.getLocation(),"grid")?"电网侧":"负载侧");
                }
                EventDataSetDTO evtData = evtDataService.getEventDataSet("evt_data", temp.getId(), eleEvtParm.getName());
                if (evtData == null) {
                    eventDataSetDTO.setValue("3.1415926");
                } else {
                    eventDataSetDTO.setValue(Optional.ofNullable(evtData.getValue()).orElse("3.1415926"));
                }
                //优化，删除监测点位置
//                if (Objects.equals(temp.getEvtParamPosition(),"-") || Objects.isNull(temp.getEvtParamPosition())) {
//                    if (!Objects.isNull(temp.getLocation())) {
//                        temp.setEvtParamPosition(Objects.equals(temp.getLocation(),"grid")?"电网侧":"负载侧");
//                    }
//                }
                eventDataSetDTOS.add(eventDataSetDTO);
            }
            temp.setDataSet(eventDataSetDTOS);

        });

        return list;
    }

    @Override
    public Page<DataGroupEventVO> pageQueryByLineId(CsEventUserQueryPage csEventUserQueryPage) {
        Page<DataGroupEventVO> result = new Page<>(csEventUserQueryPage.getPageNum(),csEventUserQueryPage.getPageSize());
        //治理，无线混用会导致csEventUserQueryPage.getStartTime()为空，这里坐下特殊处理，当时间为空的时候默认查当天的数据
        DateTime begin = DateUtil.beginOfDay(new Date());
        DateTime end = DateUtil.endOfDay(new Date());
        if(StringUtils.isNotBlank(csEventUserQueryPage.getStartTime())){
             begin = DateUtil.parse(csEventUserQueryPage.getStartTime(), DatePattern.NORM_DATE_PATTERN);
        }
        if(StringUtils.isNotBlank(csEventUserQueryPage.getEndTime())){
            end = DateUtil.endOfDay(DateUtil.parse(csEventUserQueryPage.getEndTime(), DatePattern.NORM_DATE_PATTERN));
        }

        LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CsEventPO::getLineId,csEventUserQueryPage.getLineId())
                .eq(CsEventPO::getType,0).between(CsEventPO::getStartTime,begin,end)
                .orderByDesc(CsEventPO::getStartTime);
        Page<CsEventPO> page = this.page(new Page<>(csEventUserQueryPage.getPageNum(),csEventUserQueryPage.getPageSize()),lambdaQueryWrapper);
        if(CollUtil.isNotEmpty(page.getRecords())){
            List<DataGroupEventVO> dataGroupEventVOList = BeanUtil.copyToList(page.getRecords(),DataGroupEventVO.class);
            result.setRecords(dataGroupEventVOList);
            result.setTotal(page.getTotal());
        }
        return result;
    }

    @Override
    public Page<DataGroupEventVO> pageEvent(EventStatisticParam baseParam) {
        Page<DataGroupEventVO> result = new Page<>(PageFactory.getPageNum(baseParam),PageFactory.getPageSize(baseParam));
        DateTime begin = DateUtil.beginOfDay(DateUtil.parse(baseParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN));
        DateTime end = DateUtil.endOfDay(DateUtil.parse(baseParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN));

         List<String> EVENT_TAGS = Arrays.asList(
                EVT_SYS_DIPSTR.getCode(),
                EVT_SYS_INTRSTR.getCode(),
                EVT_SYS_SWLSTR.getCode()
        );

        LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(baseParam.getLineId()),CsEventPO::getLineId,baseParam.getLineId())
                .eq(CsEventPO::getType, CsEventEnum.EVENT_TYPE.getCode())
                .in(CsEventPO::getTag, EVENT_TAGS)
                .between(CsEventPO::getStartTime,begin,end)
                .orderByDesc(CsEventPO::getStartTime);
        Page<CsEventPO> page = this.page(new Page<>(PageFactory.getPageNum(baseParam),PageFactory.getPageSize(baseParam)),lambdaQueryWrapper);
        if(CollUtil.isNotEmpty(page.getRecords())){

            List<String> ids = page.getRecords().stream().map(CsEventPO::getLineId).distinct().collect(Collectors.toList());
            List<CsLinePO> csLinePOList = csLineFeignClient.queryLineById(ids).getData();
            Map<String,String> linePOMap = csLinePOList.stream().collect(Collectors.toMap(CsLinePO::getLineId, CsLinePO::getName));

            List<DataGroupEventVO> dataGroupEventVOList = BeanUtil.copyToList(page.getRecords(),DataGroupEventVO.class);
            dataGroupEventVOList.forEach(item->{
                item.setLineName(linePOMap.getOrDefault(item.getLineId(),"/"));
                if(CsTransientEnum.EVT_SYS_SWLSTR.getCode().equals(item.getTag())){
                    item.setSeverity("/");
                }else {
                    item.setSeverity(getYzd(item.getPersistTime()*1000,item.getAmplitude()/100.0));
                }
                item.setTag(CsTransientEnum.getNameByCode(item.getTag()));
                item.setPersistTime(BigDecimal.valueOf(item.getPersistTime()).setScale(3, RoundingMode.HALF_UP).doubleValue());
            });
            result.setRecords(dataGroupEventVOList);
            result.setTotal(page.getTotal());
        }
        return result;
    }

    /**
     * 获取该事件的严重度
     *
     * @param persistTime 持续时间 ms单位
     * @param eventValue  暂降、暂升幅值
     */
    public String getYzd(Double persistTime, Double eventValue) {
        Double yzd;
        // 格式化小数
        DecimalFormat df = new DecimalFormat("0.000");
        if (persistTime <= 20) {
            yzd = 1.0 - eventValue;
        } else if (persistTime > 20 && persistTime <= 200) {
            yzd = 2.0 * (1 - eventValue);
        } else if (persistTime > 200 && persistTime <= 500) {
            yzd = 3.3 * (1 - eventValue);
        } else if (persistTime > 500 && persistTime <= 10000) {
            yzd = 5.0 * (1 - eventValue);
        } else {
            yzd = 10.0 * (1 - eventValue);
        }
        return df.format(yzd);
    }

    @Override
    @Transactional
    public void saveBatchEventList(List<CsEventPO> csEventPOS) {
        this.saveBatch(csEventPOS);
    }

    @Override
    public void getFileZip(String eventId, HttpServletResponse response) {
        CsEventPO eventDetail = this.baseMapper.selectById(eventId);
        String waveName = eventDetail.getWavePath();
        if (StrUtil.isBlank(waveName)) {
            throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
        }
        int i = 0;
        String baseName="";
        try {
            List<MultipartFile> excelreport = fileStorageUtil.getAllFile(minIossProperties.getBucket(), waveName);
            //被压缩文件流集合
            InputStream[] srcFiles = new InputStream[excelreport.size()];
            //被压缩文件名称
            String[] srcFileNames = new String[excelreport.size()];
            for (MultipartFile entity : excelreport) {
                //以下代码为获取图片inputStream
                InputStream ins = entity.getInputStream();
                if (ins == null) {
                    continue;
                }
                //塞入流数组中
                srcFiles[i] = ins;
                int lastIndex = entity.getOriginalFilename().lastIndexOf('/');
                String fileName = entity.getOriginalFilename().substring(lastIndex + 1);
                baseName = FilenameUtils.getBaseName(fileName);
                srcFileNames[i] = fileName;
                i++;
            }
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(baseName+".zip", "UTF-8"));
            //多个文件压缩成压缩包返回
            ZipUtil.zip(response.getOutputStream(), srcFileNames, srcFiles);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<DataGroupEventVO> queryEventList(LocalDateTime startDate, LocalDateTime endDate, String lineId) {
        List<DataGroupEventVO> dataGroupEventVOList = new ArrayList<>();
        LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CsEventPO::getLineId,lineId)
                .eq(CsEventPO::getType,0).between(CsEventPO::getStartTime,startDate,endDate)
                .orderByDesc(CsEventPO::getStartTime);
        List<CsEventPO> pos = this.baseMapper.selectList(lambdaQueryWrapper);
        if(CollUtil.isNotEmpty(pos)){
            dataGroupEventVOList = BeanUtil.copyToList(pos,DataGroupEventVO.class);
        }
        return dataGroupEventVOList;
    }

    @Override
    public List<CsEventPO> queryByModelId(DataParam param) {
        List<CsEventPO> pos = new ArrayList<>();
        LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CsEventPO::getLineId,param.getLineId())
                .eq(CsEventPO::getClDid,param.getClDid())
                .between(CsEventPO::getStartTime,param.getStartTime()+" 00:00:00",param.getEndTime()+" 23:59:59")
                .orderByDesc(CsEventPO::getStartTime);
        //判断当前用户，管理员查看所有告警；普通用户可以查看二级、三级告警(一级看不了)
        String userRole = RequestUtil.getUserRole();
        String trimmedString = userRole.substring(1, userRole.length() - 1).replace("\"", "");
        List<String> list = Arrays.asList(trimmedString.split(","));
        if (!list.contains("tourist")) {
            pos = this.baseMapper.selectList(lambdaQueryWrapper);
            if (list.contains("app_vip_user")) {
                pos = pos.stream()
                        .filter(entity -> entity.getLevel() != 1)
                        .collect(Collectors.toList());
            }
        }
        pos = list.contains("tourist") ? new ArrayList<>() : pos;
        return pos;
    }

    @Override
    @DSTransactional
    public void addCldEvent(CldEventParam param) {
        //校验是新增时间还是更新文件信息
        LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CsEventPO::getLineId,param.getMonitorId()).eq(CsEventPO::getStartTime,param.getStartTime());
        CsEventPO event = this.getOne(lambdaQueryWrapper);
        if (Objects.isNull(event)) {
            //首次录入
            //根据监测点获取装置信息
            CsLinePO po = csLineFeignClient.getById(param.getMonitorId()).getData();
            CsEventPO eventPo = new CsEventPO();
            String uuid = IdUtil.simpleUUID();
            eventPo.setId(uuid);
            eventPo.setLineId(param.getMonitorId());
            eventPo.setDeviceId(po.getDeviceId());
            LocalDateTime time = LocalDateTime.parse(param.getStartTime(), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_MS_PATTERN));
            eventPo.setStartTime(time);
            eventPo.setTag(getTag(param.getEventType()));
            eventPo.setType(0);
            eventPo.setClDid(Integer.parseInt(param.getMonitorId().substring(param.getMonitorId().length() - 1)));
            eventPo.setLevel(2);
            eventPo.setProcess(4);
            eventPo.setPersistTime(param.getDuration());
            eventPo.setAmplitude(param.getAmplitude() * 100);
            this.baseMapper.insert(eventPo);
            //influxDB数据录入
            List<String> records = new ArrayList<String>();
            Map<String, String> tags = new HashMap<>();
            tags.put(InfluxDBTableConstant.UUID,uuid);
            Map<String,Object> fields = new HashMap<>();
            fields.put("Evt_Param_Phase",param.getPhase());
            fields.put("Evt_Param_Tm",param.getDuration());
            fields.put("Evt_Param_VVaDepth",param.getAmplitude() * 100);
            Point point = influxDbUtils.pointBuilder("evt_data", time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()/1000, TimeUnit.SECONDS, tags, fields);
            BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
            batchPoints.point(point);
            records.add(batchPoints.lineProtocol());
            if (CollectionUtil.isNotEmpty(records)) {
                influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, records);
            }
            //同步数据到 r_mp_event_detail
            insertEvent(uuid, param, time);
        } else {
            if (StrUtil.isNotBlank(param.getWavePath())) {
                //更新文件信息
                //先校验两份文件的名称是否一致
                this.lambdaUpdate()
                        .eq(CsEventPO::getLineId,param.getMonitorId())
                        .eq(CsEventPO::getStartTime,param.getStartTime())
                        .set(CsEventPO::getWavePath,param.getWavePath())
                        .update();
                //更新文件信息
                updateEvent(param);
            }
        }
    }

    public void insertEvent(String uuid, CldEventParam param, LocalDateTime time) {
        RmpEventDetailPO rmpEventDetailPO = new RmpEventDetailPO();
        rmpEventDetailPO.setEventId(uuid);
        rmpEventDetailPO.setMeasurementPointId(param.getMonitorId());
        rmpEventDetailPO.setStartTime(time);
        rmpEventDetailPO.setEventType(getEventType(param.getEventType()));
        rmpEventDetailPO.setFeatureAmplitude(param.getAmplitude() * 100);
        rmpEventDetailPO.setDuration(param.getDuration());
        rmpEventDetailPO.setEventDescribe(getTag(param.getEventType()));
        rmpEventDetailPO.setPhase(param.getPhase());
        rmpEventDetailPO.setDealFlag(0);
        wlRmpEventDetailMapper.insert(rmpEventDetailPO);
    }

    public void updateEvent(CldEventParam param) {
        LambdaQueryWrapper<RmpEventDetailPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RmpEventDetailPO::getMeasurementPointId,param.getMonitorId()).eq(RmpEventDetailPO::getStartTime,param.getStartTime());
        RmpEventDetailPO po = wlRmpEventDetailMapper.selectOne(wrapper);
        po.setWavePath(param.getWavePath());
        po.setFileFlag(1);

        //根据事件获取暂态类型、暂态原因、暂态发生位置
        //String ip = equipmentFeignClient.getDevByLineId(param.getMonitorId()).getData().getMac();
        //EntityAdvancedData advancedData = commonEventWaveAnalysisService.analysis(po,ip);
        //po.setAdvanceReason(advancedData.getSagReason()[0]);
        //po.setAdvanceType(advancedData.getSagType()[0]);

        wlRmpEventDetailMapper.updateById(po);
    }


    @Override
    public List<CsEventPO> getEventByTime(List<String> lineList, String startTime, String endTime) {
        LambdaQueryWrapper<CsEventPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(CsEventPO::getStartTime,startTime,endTime)
                .eq(CsEventPO::getType,0)
                .isNull(CsEventPO::getWavePath);
        if (CollUtil.isNotEmpty(lineList)) {
            lambdaQueryWrapper.in(CsEventPO::getLineId,lineList);
        }
        return this.list(lambdaQueryWrapper);
    }

    @Override
    public List<EventStatisticsVo> getEventStatistics(CsEventUserQueryParam param) {




        return Collections.emptyList();
    }

    @Override
    public List<CsWarnDescVO> getEventDesc(List<String> lineIdList) {
        List<CsWarnDescVO> csWarnDescVOList = new ArrayList<>();
        if(CollUtil.isEmpty(lineIdList)){
            return csWarnDescVOList;
        }
        /**
         * todo.. 目前且先查最近的60条
         */
        csWarnDescVOList = this.baseMapper.getEventDesc(lineIdList,60);
        // 处理下描述
        for (CsWarnDescVO csWarnDescVO : csWarnDescVOList) {
            String desc;
            if(csWarnDescVO.getAmplitude() <= 90) {
                desc = "降至";
            } else if (csWarnDescVO.getAmplitude() >= 110) {
                desc = "升至";
            } else {
                desc = "维持";
            }
            csWarnDescVO.setEventDesc("电压暂态事件，持续时间"+csWarnDescVO.getPersistTime()+"秒，电压"+desc+csWarnDescVO.getAmplitude()+"%。");
        }
        return csWarnDescVOList;
    }

    public String getTag(Integer type) {
        String tag;
        switch (type) {
            case 1:
                tag = "Evt_Sys_DipStr";
                break;
            case 2:
                tag = "Evt_Sys_SwlStr";
                break;
            case 3:
                tag = "Evt_Sys_IntrStr";
                break;
            case 4:
                tag = "Transient";
                break;
            default:
                tag = "Un_Know";
                break;
        }
        return tag;
    }

    public String getEventType(Integer type) {
        String tag;
        switch (type) {
            case 1:
                DictData dip = dicDataFeignClient.getDicDataByCode(DicDataEnum.VOLTAGE_DIP.getCode()).getData();
                tag = dip.getId();
                break;
            case 2:
                DictData rise = dicDataFeignClient.getDicDataByCode(DicDataEnum.VOLTAGE_RISE.getCode()).getData();
                tag = rise.getId();
                break;
            case 3:
                DictData interruptions = dicDataFeignClient.getDicDataByCode(DicDataEnum.SHORT_INTERRUPTIONS.getCode()).getData();
                tag = interruptions.getId();
                break;
            default:
                tag = "Un_Know";
                break;
        }
        return tag;
    }


    /**
     * @return WaveDataDTO
     * @date 2023/9/21 15:59
     * param iType == 0  高级算法的要求，采样率只能是32-128
     * iType == 1  普通展示，采样率按照cfg里面最小的（大于32）
     * iType == 2  App抽点要求，采样率抽点成32
     * iType == 3  高级算法原始波形（大于32）
     */
    @Override
    public WaveDataDTO analyseWave(String eventId, int iType) {
        WaveDataDTO waveDataDTO;
        //获取暂降事件
        CsEventPO eventDetail = this.baseMapper.selectById(eventId);
        String waveName = eventDetail.getWavePath();
        if (StrUtil.isBlank(waveName)) {
            throw new BusinessException(WaveFileResponseEnum.ANALYSE_WAVE_NOT_FOUND);
        }
        String cfgPath = waveName.concat(GeneralConstant.CFG), datPath = waveName.concat(GeneralConstant.DAT);
        //不同设备，波形文件后缀大小写不一致，针对大小写判断文件是否存在
        boolean result1 = minIoUtils.checkFileIsExist(minIossProperties.getBucket(), cfgPath);
        if (!result1) {
            cfgPath = waveName.concat(GeneralConstant.CFG_LOWER);
        }
        boolean result2 = minIoUtils.checkFileIsExist(minIossProperties.getBucket(), datPath);
        if (!result2) {
            datPath = waveName.concat(GeneralConstant.DAT_LOWER);
        }

        System.out.println("波形路径-------------------" + 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);
            }
            //持续时间超过30S时，iType调整为2，按32采样率采集数据
            if (Objects.nonNull(eventDetail.getPersistTime()) && eventDetail.getPersistTime() > 30) {
                iType = 2;
            }
            waveDataDTO = waveFileComponent.getComtrade(cfgStream, datStream, iType);
        } catch (Exception e) {
            throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
        }
        waveDataDTO = waveFileComponent.getValidData(waveDataDTO);
        List<CsLinePO> csLinePOList = csLineFeignClient.queryLineById(Stream.of(eventDetail.getLineId()).collect(Collectors.toList())).getData();
        if (CollectionUtil.isEmpty(csLinePOList)) {
            throw new BusinessException(AlgorithmResponseEnum.LINE_DATA_MISS);
        }
        waveDataDTO.setPtType(csLinePOList.get(0).getConType());
        waveDataDTO.setPt(csLinePOList.get(0).getPtRatio());
        waveDataDTO.setCt(csLinePOList.get(0).getCtRatio());
        waveDataDTO.setMonitorName(csLinePOList.get(0).getName());
        return waveDataDTO;
    }

    @Override
    public CsEventVO getWavePics(String eventId, int iType) {
        CsEventPO eventDetail = this.baseMapper.selectById(eventId);
        if (StrUtil.isBlank(eventDetail.getInstantPics())) {
            //获取波形数据。然后绘图
            WaveDataDTO waveDataDTO = this.analyseWave(eventId, iType);
            //数据筛选,如果是双路电压的话，会存在2个波形数据
            List<WaveDataDetail> waveDataDetails = WaveUtil.filterWaveData(waveDataDTO);
            String instantPath = wavePicComponent.generateInstantImageZl(waveDataDetails);
            eventDetail.setInstantPics(instantPath);
            if (StrUtil.isBlank(eventDetail.getRmsPics())) {
                String rmsPath = wavePicComponent.generateRmsImageZl(waveDataDetails);
                eventDetail.setRmsPics(rmsPath);
            }
            this.updateById(eventDetail);
        }
        CsEventVO csEventVO = new CsEventVO();
        BeanUtil.copyProperties(eventDetail, csEventVO);
        return csEventVO;
    }

}
