package com.njcn.product.event.transientes.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.event.file.pojo.enums.WaveFileResponseEnum;
import com.njcn.product.event.config.RedisUtil;
import com.njcn.product.event.devcie.pojo.dto.LedgerBaseInfoDTO;
import com.njcn.product.event.devcie.pojo.po.PqDevice;
import com.njcn.product.event.devcie.pojo.po.PqLine;
import com.njcn.product.event.devcie.pojo.po.PqLinedetail;
import com.njcn.product.event.transientes.pojo.po.PqsEventdetail;
import com.njcn.product.event.transientes.service.CleanEventService;
import com.njcn.product.event.transientes.service.PqsEventdetailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2026/07/01  上午 10:57【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CleanEventServiceImpl implements CleanEventService {
    private final PqsEventdetailService pqsEventdetailService;
    private final RedisUtil redisUtil;
    private final static String NAME_KEY = "LineCache:";
    @Value("${business.wavePath}")
    private String WAVEPATH;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cleanup() {
        log.info("开始执行 PQS_EVENTDETAIL 清理任务...");
        LocalDateTime oneMonthAgo = LocalDateTime.now().minusMonths(1);
        LocalDateTime twoMonthAgo = LocalDateTime.now().minusMonths(1).minusDays(5);

        // 构建查询条件：timeid 早于一个月前，且 eventvalue 在 [0.9, 0.98] 之间
        LambdaQueryWrapper<PqsEventdetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(PqsEventdetail::getTimeid,twoMonthAgo, oneMonthAgo)
                .ge(PqsEventdetail::getEventvalue, 0.9)
                .le(PqsEventdetail::getEventvalue, 0.98);

        // 一次性查询所有符合条件的记录（注意：若数据量极大，建议改为分页或分批处理）
        List<PqsEventdetail> records = pqsEventdetailService.list(wrapper);
        if (records == null || records.isEmpty()) {
            log.info("没有符合条件的记录，清理任务结束");
            return;
        }

        log.info("共查询到 {} 条待清理记录", records.size());
        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()));
        // 收集主键 ID 和删除文件
        List<String> ids = new ArrayList<>(records.size());

        for (PqsEventdetail record : records) {
            ids.add(record.getEventdetailIndex());
            Integer lineid = record.getLineid();
            LedgerBaseInfoDTO ledgerBaseInfoDTO = LedgerBaseInfoDTOMap.get(lineid);

            String waveName = record.getWavename();
            String cfgPath, datPath,cfgPathLower,datPathLower;
            if (StrUtil.isBlank(waveName)) {
                continue;
            }
            cfgPath = WAVEPATH+"/"+ledgerBaseInfoDTO.getIp()+"/"+waveName+".CFG";
            datPath = WAVEPATH+"/"+ledgerBaseInfoDTO.getIp()+"/"+waveName+".DAT";
            cfgPathLower = WAVEPATH+"/"+ledgerBaseInfoDTO.getIp()+"/"+waveName+".cfg";
            datPathLower = WAVEPATH+"/"+ledgerBaseInfoDTO.getIp()+"/"+waveName+".dat";
            List<String> filePathList = new ArrayList<>();
            filePathList.add(cfgPath);
            filePathList.add(datPath);
            filePathList.add(cfgPathLower);
            filePathList.add(datPathLower);
            deleteWaveFile(filePathList);
        }

        // 批量删除数据库记录
        if (!ids.isEmpty()) {
            boolean flag = pqsEventdetailService.removeByIds(ids);
        }

        log.info("PQS_EVENTDETAIL 清理任务完成");
    }
    /**
     * 删除波形文件（若文件不存在则忽略）
     *
     * @param filePathList 文件路径（支持绝对或相对路径）
     */
    private void deleteWaveFile(List<String> filePathList ) {
        filePathList.forEach(filePath->{
            if (filePath == null || filePath.trim().isEmpty()) {
                return;
            }
            try {
                Path path = Paths.get(filePath);
                boolean deleted = Files.deleteIfExists(path);
                if (deleted) {
                    log.debug("成功删除波形文件: {}", filePath);
                } else {
                    log.warn("波形文件不存在，无法删除: {}", filePath);
                }
            } catch (IOException e) {
                log.error("删除波形文件失败: {}", filePath, e);
            }
        });

    }

}
