package com.njcn.product.event.dataTransmit;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.product.event.devcie.mapper.PqGdCompanyMapper;
import com.njcn.product.event.devcie.mapper.PqLineMapper;
import com.njcn.product.event.devcie.mapper.PqLinedetailMapper;
import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO;
import com.njcn.product.event.devcie.pojo.po.PqGdCompany;
import com.njcn.product.event.devcie.pojo.po.PqLinedetail;
import com.njcn.product.event.transientes.mapper.*;
import com.njcn.product.event.transientes.pojo.dto.UpLoadEvent;
import com.njcn.product.event.transientes.pojo.dto.UpLoadUserDTO;
import com.njcn.product.event.transientes.pojo.dto.UserLegerDTO;
import com.njcn.product.event.transientes.pojo.dto.UserLineAssDTO;
import com.njcn.product.event.transientes.pojo.po.*;
import com.njcn.product.event.transientes.service.PqsEventDetailStatusService;
import com.njcn.product.event.transientes.utils.OssFileStorageUtils;
import com.njcn.product.event.config.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @Author: cdf
 * @CreateTime: 2025-10-20
 * @Description: 暂降事件同步
 */
@Service
@EnableScheduling
@Slf4j
@RequiredArgsConstructor
public class DataSynchronization {

    private final PqsEventdetailMapper pqsEventdetailMapper;

    private final PqsEventDetailStatusService pqsEventDetailStatusService;

    private final OssFileStorageUtils ossFileStorageUtils;
    private final PqLinedetailMapper pqLinedetailMapper;
    private final PqLineMapper pqLineMapper;

    private final PqUserLineAssMapper pqUserLineAssMapper;
    private final PqUserLedgerMapper pqUserLedgerMapper;
    private final PqsDicTreeMapper pqsDicTreeMapper;
    private final PqGdCompanyMapper pqGdCompanyMapper;

    private final RedisUtil redisUtil;
    // 文件配置
    @Value("${business.wavePath}")
    private String sourceWaveDir;

    @Value("${business.targetPath}")
    private String targetPath;

    @Value("${business.syncinterval}")
    private Integer syncinterval;

    @Value("${business.failsyncinterval}")
    private Integer failsyncinterval;



    private volatile boolean syncEventFlag = false;
    private volatile boolean syncFailFlag = false;


    private final static String NAME_KEY = "LineCache:";

    /**
     * 定时执行的同步任务
     */
    @Scheduled(cron = "${business.eventCronExpression}")
    @Transactional
    public void syncPqsEventdetails() {
        // 防止任务并发执行
        if (syncEventFlag) {
            log.warn("同步任务正在执行中，跳过本次调度");
            return;
        }

        try {
            syncEventFlag = true;
            log.info("=== 开始暂降事件波形文件同步任务 ===");


            // 同步最近N天的事件,因为存在事件补招，延迟的原因，采用大范围扫描
            LocalDateTime end = LocalDateTime.now();
            LocalDateTime start = end.minusMinutes(syncinterval);
            syncEvents(start, end);

            log.info("=== 同步任务完成 ===");

        } catch (Exception e) {
            log.error("同步任务执行失败", e);
        } finally {
            syncEventFlag = false;
        }
    }

    @Scheduled(cron = "${business.failCronExpression}")
    @Transactional
    public void syncFail() {
        // 防止任务并发执行
        if (syncFailFlag) {
            log.warn("同步任务正在执行中，跳过本次调度");
            return;
        }

        try {
            syncFailFlag = true;
            log.info("=== 开始暂降事件波形文件同步任务 ===");


            // 同步最近N天的事件,因为存在事件补招，延迟的原因，采用大范围扫描
            LocalDateTime end = LocalDateTime.now();
            LocalDateTime start = end.minusMinutes(failsyncinterval);
            synFailEvents(start, end);

            log.info("=== 同步任务完成 ===");

        } catch (Exception e) {
            log.error("同步任务执行失败", e);
        } finally {
            syncFailFlag = false;
        }
    }

    @Scheduled(cron = "${business.userCronExpression}")
    @Transactional
    public void syncUser()  throws Exception {

        log.info("=== 开始重要敏感用户同步任务 ===");




        String exportDirName = "/pq_user/pq_user.json";
        UpLoadUserDTO result = new UpLoadUserDTO();
        QueryWrapper<PqUserLedgerPO> pqUserLedgerPOQueryWrapper = new QueryWrapper<>();
//        pqUserLedgerPOQueryWrapper.lambda().eq(PqUserLedgerPO::getIsShow,1);
        List<PqUserLedgerPO> pqUserLedgerPOS = pqUserLedgerMapper.selectList(null);
        if(!CollectionUtils.isEmpty(pqUserLedgerPOS)){
            List<String> showIds =new ArrayList<>();
            List<UserLegerDTO>  userLegerDTOList =new ArrayList<>();
            List<PqsDicTreePO> pqsDicTreePOS = pqsDicTreeMapper.selectList(new LambdaQueryWrapper<>());
            Map<String, PqsDicTreePO> pqsDicTreePOMap = pqsDicTreePOS.stream().collect(Collectors.toMap(PqsDicTreePO::getId, Function.identity()));
            List<PqGdCompany> pqGdCompanyList = pqGdCompanyMapper.selectList(null);
            Map<Long, PqGdCompany> gdMap = pqGdCompanyList.stream().collect(Collectors.toMap(PqGdCompany::getGdIndex, Function.identity()));
            pqUserLedgerPOS.forEach(temp->{
                showIds.add(temp.getId());
                UserLegerDTO userLegerDTO = new UserLegerDTO();
                userLegerDTO.setId(temp.getId());
                userLegerDTO.setPowerSupplyArea(gdMap.get(Long.valueOf(temp.getPowerSupplyArea())).getName());
                userLegerDTO.setCustomerName(temp.getCustomerName());
                userLegerDTO.setElectricityAddress(temp.getElectricityAddress());
                userLegerDTO.setBigObjType(pqsDicTreePOMap.get(temp.getBigObjType()).getName());
                userLegerDTO.setSmallObjType(pqsDicTreePOMap.get(temp.getSmallObjType()).getName());

                userLegerDTO.setCustomerNo("");
                userLegerDTO.setIsShow(temp.getIsShow());
                userLegerDTOList.add(userLegerDTO);
            });

            QueryWrapper<PqUserLineAssPO> userLineAssPOQueryWrapper = new QueryWrapper<>();
//            userLineAssPOQueryWrapper.lambda().in(PqUserLineAssPO::getUserIndex,showIds);
            if (showIds.size() > 1000) {
                List<List<String>> splitList = CollUtil.split(showIds, 1000);
                userLineAssPOQueryWrapper.lambda().and(ew -> {
                    for (int i = 0; i < splitList.size(); i++) {
                        List<String> batch = splitList.get(i);
                        if (i == 0) {
                            ew.in(PqUserLineAssPO::getUserIndex, batch); // 第一个条件不加 or
                        } else {
                            ew.or().in(PqUserLineAssPO::getUserIndex, batch); // 后续条件加 or
                        }
                    }
                });
            } else {
                userLineAssPOQueryWrapper.lambda().in(PqUserLineAssPO::getUserIndex, showIds);
            }
            List<PqUserLineAssPO> pqUserLineAssPOS = pqUserLineAssMapper.selectList(userLineAssPOQueryWrapper);
            List<UserLineAssDTO> userLineAssDTOS = pqUserLineAssPOS.stream().map(temp -> {
                UserLineAssDTO userLineAssDTO = new UserLineAssDTO();
                BeanUtils.copyProperties(temp, userLineAssDTO);
                return userLineAssDTO;
            }).collect(Collectors.toList());
            result.setUserList(userLegerDTOList);
            result.setAssList(userLineAssDTOS);


            ossFileStorageUtils.uploadObjectAsJsonStream(result,exportDirName);
            log.info("=== 结束重要敏感用户同步任务 ===");

        }else {
            log.info("=== 暂无重要敏感用户 ===");

        }



    }

    private void synFailEvents(LocalDateTime start, LocalDateTime end) throws Exception {
        log.info("=== 开始同步同步失败事件任务 ===");

        // 创建导出目录
        String filePath = start.toLocalDate().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        String fileName = end.format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN));

        String exportDirName = String.format("%s/%s/%s.json","/event", filePath,"bz_"+fileName);
        // 查询失败的暂降事件
        LambdaQueryWrapper<PqsEventDetailStatusPO> statusPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        statusPOLambdaQueryWrapper.between(PqsEventDetailStatusPO::getSyncTime,start,end);
        List<PqsEventDetailStatusPO> hasList = pqsEventDetailStatusService.list(statusPOLambdaQueryWrapper);
        Map<String, PqsEventDetailStatusPO> pqsEventDetailStatusPOMap = hasList.stream().collect(Collectors.toMap(PqsEventDetailStatusPO::getEventDetailId, Function.identity()));
        // 查询事件
        LambdaQueryWrapper<PqsEventdetail> pqsEventdetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pqsEventdetailLambdaQueryWrapper.between(PqsEventdetail::getCreateTime,start.minusMinutes(6*10),end);
        List<PqsEventdetail> unsyncedEvents = pqsEventdetailMapper.selectList(pqsEventdetailLambdaQueryWrapper);
        List<String> tempEvetIds = unsyncedEvents.stream().map(PqsEventdetail::getEventdetailIndex).collect(Collectors.toList());
        //查询日志
        List<String> allEventIds = hasList.stream().map(PqsEventDetailStatusPO::getEventDetailId).collect(Collectors.toList());
        List<String> unSyncIds = tempEvetIds.stream().filter(temp -> !allEventIds.contains(temp)).collect(Collectors.toList());

        List<String> failIds = hasList.stream().filter(temp -> temp.getRetryCount() <= 5 && temp.getSyncStatus() == 0).map(PqsEventDetailStatusPO::getEventDetailId).collect(Collectors.toList());
        unSyncIds.addAll(failIds);
        List<UpLoadEvent> result = new ArrayList<>();

        if(!CollectionUtils.isEmpty(unSyncIds)){
            List<String> eventIds = unSyncIds.stream().distinct().collect(Collectors.toList());

            LambdaQueryWrapper<PqsEventdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            if (eventIds.size() > 1000) {
                List<List<String>> splitList = CollUtil.split(eventIds, 1000);
                lambdaQueryWrapper.and(ew -> {
                    for (int i = 0; i < splitList.size(); i++) {
                        List<String> batch = splitList.get(i);
                        if (i == 0) {
                            ew.in(PqsEventdetail::getEventdetailIndex, batch); // 第一个条件不加 or
                        } else {
                            ew.or().in(PqsEventdetail::getEventdetailIndex, batch); // 后续条件加 or
                        }
                    }
                });
            } else {
                lambdaQueryWrapper.in(PqsEventdetail::getEventdetailIndex, eventIds);
            }
            List<PqsEventdetail> pqsEventdetails = pqsEventdetailMapper.selectList(lambdaQueryWrapper);
            Map<String, PqsEventdetail> pqsEventdetailMap = pqsEventdetails.stream().collect(Collectors.toMap(PqsEventdetail::getEventdetailIndex, Function.identity()));

            List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = (List<LedgerBaseInfoDTO>)redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED+"LedgerBaseInfoDTO");
            Map<Integer, LedgerBaseInfoDTO> LedgerBaseInfoDTOMap = ledgerBaseInfoDTOS.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));
            List<PqLinedetail> pqLinedetails = pqLinedetailMapper.selectList(null);
            Map<Integer, PqLinedetail> lineDetailMap = pqLinedetails.stream().collect(Collectors.toMap(PqLinedetail::getLineIndex, Function.identity()));

            eventIds.forEach(temp->{
                PqsEventdetail pqsEventdetail = pqsEventdetailMap.get(temp);

                if(pqsEventDetailStatusPOMap.containsKey(temp)){
                    PqsEventDetailStatusPO pqsEventDetailStatusPO = pqsEventDetailStatusPOMap.get(temp);
                    pqsEventDetailStatusPO.setRetryCount(pqsEventDetailStatusPO.getRetryCount()+1);
                    if(Objects.nonNull(pqsEventdetail.getWavename())||pqsEventDetailStatusPO.getRetryCount()>5){
                        pqsEventDetailStatusPO.setSyncStatus(1);
                        pqsEventDetailStatusPO.setWaveFlag(0);
                        UpLoadEvent upLoadEvent = new UpLoadEvent();
                        upLoadEvent.setEventdetail_index(pqsEventdetail.getEventdetailIndex());
                        upLoadEvent.setLineid(pqsEventdetail.getLineid());
                        upLoadEvent.setTimeid(LocalDateTimeUtil.format(pqsEventdetail.getTimeid(),DatePattern.NORM_DATETIME_PATTERN));
                        upLoadEvent.setMs(pqsEventdetail.getMs());
                        upLoadEvent.setDescribe(pqsEventdetail.getDescribe());
                        upLoadEvent.setWavetype(pqsEventdetail.getWavetype());
                        upLoadEvent.setPersisttime( pqsEventdetail.getPersisttime()/ 1000);
                        upLoadEvent.setEventvalue(pqsEventdetail.getEventvalue());
                        upLoadEvent.setEventreason(pqsEventdetail.getEventreason());
                        upLoadEvent.setEventtype(pqsEventdetail.getEventtype());
                        LedgerBaseInfoDTO ledgerBaseInfoDTO = LedgerBaseInfoDTOMap.get(pqsEventdetail.getLineid());
                        if(Objects.isNull(ledgerBaseInfoDTO)){
                            List<LedgerBaseInfoDTO> baseLineInfo = pqLineMapper.getBaseLineInfo(Stream.of(pqsEventdetail.getLineid()).collect(Collectors.toList()));
                            ledgerBaseInfoDTO = baseLineInfo.get(0);
                        }
                        upLoadEvent.setGdname(ledgerBaseInfoDTO.getGdName());
                        upLoadEvent.setBdname(ledgerBaseInfoDTO.getStationName());
                        upLoadEvent.setBusname(ledgerBaseInfoDTO.getBusBarName());
                        upLoadEvent.setPointname(ledgerBaseInfoDTO.getLineName());
                        upLoadEvent.setIp(ledgerBaseInfoDTO.getIp());
                        upLoadEvent.setPt(ledgerBaseInfoDTO.getPt());
                        upLoadEvent.setCt(ledgerBaseInfoDTO.getCt());
                        upLoadEvent.setPtType(lineDetailMap.get(pqsEventdetail.getLineid()).getPttype());
                        upLoadEvent.setIp(ledgerBaseInfoDTO.getIp());
                        if(Objects.nonNull(pqsEventdetail.getWavename())){
                            pqsEventDetailStatusPO.setWaveFlag(1);

                            upLoadEvent.setWavePath(ledgerBaseInfoDTO.getIp()+"/"+pqsEventdetail.getWavename());
                        }
                        result.add(upLoadEvent);
                    }
                    pqsEventDetailStatusService.saveOrUpdate(pqsEventDetailStatusPO);

                }else{
                    PqsEventDetailStatusPO pqsEventDetailStatusPO = new PqsEventDetailStatusPO();
                    pqsEventDetailStatusPO.setEventDetailId(pqsEventdetail.getEventdetailIndex());
                    pqsEventDetailStatusPO.setEventTime(pqsEventdetail.getTimeid());
                    pqsEventDetailStatusPO.setSyncTime(LocalDateTime.now());
                    pqsEventDetailStatusPO.setRemark("");
                    pqsEventDetailStatusPO.setRetryCount(0);

                    if(StringUtils.isEmpty(pqsEventdetail.getWavename())){
                        pqsEventDetailStatusPO.setSyncStatus(0);
                        pqsEventDetailStatusPO.setWaveFlag(0);
                    }else {
                        UpLoadEvent upLoadEvent = new UpLoadEvent();
                        upLoadEvent.setEventdetail_index(pqsEventdetail.getEventdetailIndex());
                        upLoadEvent.setLineid(pqsEventdetail.getLineid());
                        upLoadEvent.setTimeid(LocalDateTimeUtil.format(pqsEventdetail.getTimeid(),DatePattern.NORM_DATETIME_PATTERN));
                        upLoadEvent.setMs(pqsEventdetail.getMs());
                        upLoadEvent.setDescribe(pqsEventdetail.getDescribe());
                        upLoadEvent.setWavetype(pqsEventdetail.getWavetype());
                        upLoadEvent.setPersisttime(pqsEventdetail.getPersisttime()/ 1000);
                        upLoadEvent.setEventvalue(pqsEventdetail.getEventvalue());
                        upLoadEvent.setEventreason(pqsEventdetail.getEventreason());
                        upLoadEvent.setEventtype(pqsEventdetail.getEventtype());
                        LedgerBaseInfoDTO ledgerBaseInfoDTO = LedgerBaseInfoDTOMap.get(pqsEventdetail.getLineid());
                        if(Objects.isNull(ledgerBaseInfoDTO)){
                            List<LedgerBaseInfoDTO> baseLineInfo = pqLineMapper.getBaseLineInfo(Stream.of(pqsEventdetail.getLineid()).collect(Collectors.toList()));
                            ledgerBaseInfoDTO = baseLineInfo.get(0);
                        }
                        upLoadEvent.setGdname(ledgerBaseInfoDTO.getGdName());
                        upLoadEvent.setBdname(ledgerBaseInfoDTO.getStationName());
                        upLoadEvent.setBusname(ledgerBaseInfoDTO.getBusBarName());
                        upLoadEvent.setPointname(ledgerBaseInfoDTO.getLineName());
                        upLoadEvent.setIp(ledgerBaseInfoDTO.getIp());
                        upLoadEvent.setPt(ledgerBaseInfoDTO.getPt());
                        upLoadEvent.setCt(ledgerBaseInfoDTO.getCt());
                        upLoadEvent.setPtType(lineDetailMap.get(pqsEventdetail.getLineid()).getPttype());
                        upLoadEvent.setWavePath(ledgerBaseInfoDTO.getIp()+"/"+pqsEventdetail.getWavename());
                        result.add(upLoadEvent);
                        pqsEventDetailStatusPO.setSyncStatus(1);
                        pqsEventDetailStatusPO.setWaveFlag(1);


                    }
                    pqsEventDetailStatusService.saveOrUpdate(pqsEventDetailStatusPO);

                }

            });
        }
        if(!CollectionUtils.isEmpty(result)){
            //上传Json
            ossFileStorageUtils.uploadObjectAsJsonStream(result,exportDirName);
            //上传波形文件
            result.forEach(temp->{
                if(Objects.nonNull(temp.getWavePath())){
                    //            String uploadLocalFile1 =sourceWaveDir+"/"+temp.getWavePath()+".dat";
                    String uploadLocalFile2 =sourceWaveDir+"/"+temp.getWavePath()+".DAT";
//            String uploadLocalFile3 =sourceWaveDir+"/"+temp.getWavePath()+".cfg";
                    String uploadLocalFile4 =sourceWaveDir+"/"+temp.getWavePath()+".CFG";
                    String uploadLocalFile5 =sourceWaveDir+"/"+temp.getWavePath()+".HDR";
//            String uploadLocalFile6 =sourceWaveDir+"/"+temp.getWavePath()+".hdr";
//            ossFileStorageUtils.uploadLocalFile(uploadLocalFile1,  targetPath+"/"+temp.getIp());
                    ossFileStorageUtils.uploadLocalFile(uploadLocalFile2,  targetPath+"/"+temp.getIp());
//            ossFileStorageUtils.uploadLocalFile(uploadLocalFile3,  targetPath+"/"+temp.getIp());
                    ossFileStorageUtils.uploadLocalFile(uploadLocalFile4,  targetPath+"/"+temp.getIp());
                    ossFileStorageUtils.uploadLocalFile(uploadLocalFile5,  targetPath+"/"+temp.getIp());
//            ossFileStorageUtils.uploadLocalFile(uploadLocalFile6,  targetPath+"/"+temp.getIp());
                }



            });
        }


    }


    /**
     * 同步指定时间范围内的事件
     */
    public void syncEvents(LocalDateTime startTime, LocalDateTime endTime) throws Exception {
        // 创建导出目录
        String filePath = endTime.toLocalDate().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
        String fileName = startTime.format(DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_PATTERN));

        String exportDirName = String.format("%s/%s/%s.json","/event", filePath,fileName);

        // 查询未同步的事件
        LambdaQueryWrapper<PqsEventdetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(PqsEventdetail::getCreateTime,startTime,endTime);
        List<PqsEventdetail> unsyncedEvents = pqsEventdetailMapper.selectList(lambdaQueryWrapper);
        log.info("查询到 " + unsyncedEvents.size() + " 个暂降事件");
        if(CollUtil.isEmpty(unsyncedEvents)){
            return ;
        }

//        // 查询已经存在记录的暂降事件
//        LambdaQueryWrapper<PqsEventDetailStatusPO> statusPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        statusPOLambdaQueryWrapper.between(PqsEventDetailStatusPO::getEventTime,startTime,endTime);
//        List<PqsEventDetailStatusPO> hasList = pqsEventDetailStatusMapper.selectList(statusPOLambdaQueryWrapper);

//        log.info("查询到 " + hasList.size() + "条已存在记录事件");
//        //成功或者重试超过2次的时间id
//        List<String> successEventDetailIds = hasList.stream().filter(it->it.getWaveFlag() == 1||it.getRetryCount()>2).map(PqsEventDetailStatusPO::getEventDetailId).collect(Collectors.toList());
//
//
//        //排除已经成功的事件
//        if(CollUtil.isNotEmpty(successEventDetailIds)){
//            unsyncedEvents = unsyncedEvents.stream().filter(it->!successEventDetailIds.contains(it.getEventdetailIndex())).collect(Collectors.toList());
//        }
        List<LedgerBaseInfoDTO> ledgerBaseInfoDTOS = (List<LedgerBaseInfoDTO>)redisUtil.getObjectByKey(NAME_KEY + StrUtil.DASHED+"LedgerBaseInfoDTO");
        Map<Integer, LedgerBaseInfoDTO> LedgerBaseInfoDTOMap = ledgerBaseInfoDTOS.stream().collect(Collectors.toMap(LedgerBaseInfoDTO::getLineId, Function.identity()));

        List<PqLinedetail> pqLinedetails = pqLinedetailMapper.selectList(null);
        Map<Integer, PqLinedetail> lineDetailMap = pqLinedetails.stream().collect(Collectors.toMap(PqLinedetail::getLineIndex, Function.identity()));
        List<UpLoadEvent> result = new ArrayList<>();
        List<PqsEventDetailStatusPO> logs = new ArrayList<>();

        for (PqsEventdetail unsyncedEvent : unsyncedEvents) {

            PqsEventDetailStatusPO pqsEventDetailStatusPO = new PqsEventDetailStatusPO();
            pqsEventDetailStatusPO.setEventDetailId(unsyncedEvent.getEventdetailIndex());
            pqsEventDetailStatusPO.setEventTime(unsyncedEvent.getTimeid());
            pqsEventDetailStatusPO.setSyncTime(LocalDateTime.now());
            pqsEventDetailStatusPO.setRemark("");
            pqsEventDetailStatusPO.setRetryCount(0);

            if(StringUtils.isEmpty(unsyncedEvent.getWavename())){
                pqsEventDetailStatusPO.setSyncStatus(0);
                pqsEventDetailStatusPO.setWaveFlag(0);
            }else {
                UpLoadEvent upLoadEvent = new UpLoadEvent();
                upLoadEvent.setEventdetail_index(unsyncedEvent.getEventdetailIndex());
                upLoadEvent.setLineid(unsyncedEvent.getLineid());
                upLoadEvent.setTimeid(LocalDateTimeUtil.format(unsyncedEvent.getTimeid(),DatePattern.NORM_DATETIME_PATTERN));
                upLoadEvent.setMs(unsyncedEvent.getMs());
                upLoadEvent.setDescribe(unsyncedEvent.getDescribe());
                upLoadEvent.setWavetype(unsyncedEvent.getWavetype());
                upLoadEvent.setPersisttime(unsyncedEvent.getPersisttime()/ 1000);
                upLoadEvent.setEventvalue(unsyncedEvent.getEventvalue());
                upLoadEvent.setEventreason(unsyncedEvent.getEventreason());
                upLoadEvent.setEventtype(unsyncedEvent.getEventtype());
                LedgerBaseInfoDTO ledgerBaseInfoDTO = LedgerBaseInfoDTOMap.get(unsyncedEvent.getLineid());
                if(Objects.isNull(ledgerBaseInfoDTO)){
                    List<LedgerBaseInfoDTO> baseLineInfo = pqLineMapper.getBaseLineInfo(Stream.of(unsyncedEvent.getLineid()).collect(Collectors.toList()));
                    ledgerBaseInfoDTO = baseLineInfo.get(0);
                }
                upLoadEvent.setGdname(ledgerBaseInfoDTO.getGdName());
                upLoadEvent.setBdname(ledgerBaseInfoDTO.getStationName());
                upLoadEvent.setBusname(ledgerBaseInfoDTO.getBusBarName());
                upLoadEvent.setPointname(ledgerBaseInfoDTO.getLineName());
                upLoadEvent.setIp(ledgerBaseInfoDTO.getIp());
                upLoadEvent.setPt(ledgerBaseInfoDTO.getPt());
                upLoadEvent.setCt(ledgerBaseInfoDTO.getCt());
                upLoadEvent.setPtType(lineDetailMap.get(unsyncedEvent.getLineid()).getPttype());
                upLoadEvent.setWavePath(ledgerBaseInfoDTO.getIp()+"/"+unsyncedEvent.getWavename());
                result.add(upLoadEvent);
                pqsEventDetailStatusPO.setSyncStatus(1);
                pqsEventDetailStatusPO.setWaveFlag(1);


            }
            pqsEventDetailStatusService.saveOrUpdate(pqsEventDetailStatusPO);
            logs.add(pqsEventDetailStatusPO);

        }
        if(!CollectionUtils.isEmpty(result)){
            //上传Json
            ossFileStorageUtils.uploadObjectAsJsonStream(result,exportDirName);
            //上传波形文件
            result.forEach(temp->{
//            String uploadLocalFile1 =sourceWaveDir+"/"+temp.getWavePath()+".dat";
                String uploadLocalFile2 =sourceWaveDir+"/"+temp.getWavePath()+".DAT";
//            String uploadLocalFile3 =sourceWaveDir+"/"+temp.getWavePath()+".cfg";
                String uploadLocalFile4 =sourceWaveDir+"/"+temp.getWavePath()+".CFG";
                String uploadLocalFile5 =sourceWaveDir+"/"+temp.getWavePath()+".HDR";
//            String uploadLocalFile6 =sourceWaveDir+"/"+temp.getWavePath()+".hdr";
//            ossFileStorageUtils.uploadLocalFile(uploadLocalFile1,  targetPath+"/"+temp.getIp());
                ossFileStorageUtils.uploadLocalFile(uploadLocalFile2,  targetPath+"/"+temp.getIp());
//            ossFileStorageUtils.uploadLocalFile(uploadLocalFile3,  targetPath+"/"+temp.getIp());
                ossFileStorageUtils.uploadLocalFile(uploadLocalFile4,  targetPath+"/"+temp.getIp());
                ossFileStorageUtils.uploadLocalFile(uploadLocalFile5,  targetPath+"/"+temp.getIp());
//            ossFileStorageUtils.uploadLocalFile(uploadLocalFile6,  targetPath+"/"+temp.getIp());


            });
        }







    }






    /**
     * 获取波形类型描述
     */
    private String getWaveTypeDesc(Integer waveType) {
        if (waveType == null) return "未知";

        switch (waveType) {
            case 1: return "电压暂降";
            case 2: return "电压暂升";
            case 3: return "电压中断";
            case 4: return "电压波动";
            default: return "未知类型(" + waveType + ")";
        }
    }

    public static void main(String[] args) {
        double a =3.00;
        System.out.println(a/1000);
    }



}

