package com.common.schedule;


import com.common.service.DataExtractor;
import  com.Modules.etl.handler.ETLRetryHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.Modules.etl.TimeWindowCalculator;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.common.service.DeviceReceiveLogService;
import lombok.RequiredArgsConstructor;
import com.common.service.NormalizeRuleHitTimeService;
@Slf4j
@Component
@RequiredArgsConstructor
public class ETLOrchestrator {

    @Autowired
    private DataExtractor dataExtractor;

    @Autowired
    private ETLRetryHandler retryHandler;

    @Autowired
    private  DeviceReceiveLogService deviceReceiveLogService;

    @Autowired

    private NormalizeRuleHitTimeService normalizeRuleHitTimeService;
    /**
     * 定时任务 - 从每小时第1分钟开始，5分钟间隔执行
     * 20260317：暂停硬规则关联分析，由可配置关联分析规则取代
     * 泛化规则最新命中时间更新任务保留
     */
    @Scheduled(cron = "0 1/5 * * * ?")
    public void scheduledETL() {

        //暂停ETL数据降噪任务(关联分析）
        //RunETL();

        //泛化规则最新命中时间更新任务
        try {
            normalizeRuleHitTimeService.updateRuleHitTimeTask();
        } catch (Exception e) {
        log.error("泛化规则最新命中时间更新任务执行失败", e);
    }

    }

    //ETL数据降噪任务处理
    private  void  RunETL()
    {
        long startTime = System.currentTimeMillis();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime[] currentWindow=TimeWindowCalculator.getPrevious5MinuteWindow();
        String strStartTime= currentWindow[0].format(formatter);
        String strEndTime= currentWindow[1].format(formatter);
        log.info("ETL任务开始执行，开始时间：{},结束时间：{}",strStartTime,strEndTime );
        //泛化标准数据告警降噪任务
        try {
            //retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcess24HoursGroupedData());
            //retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcessQueryHoursGroupedData(strStartTime,strEndTime ));
            //retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcessQueryHoursAlarm(strStartTime,strEndTime ));
            long endTime = System.currentTimeMillis();
            long duration = (endTime - startTime) / 1000;
            log.info("定时ETL任务执行完成，耗时: {} 秒", duration);

        } catch (Exception e) {
            log.error("定时ETL任务执行失败", e);
        }
    }

    /**
     * 手动触发ETL任务
     */
    public void triggerETLManually() {
        log.info("手动触发ETL任务");
        try {
            //retryHandler.executeWithRetry(() ->
                    //dataExtractor.extractAndProcess24HoursGroupedData());
            retryHandler.executeWithRetry(() ->
                    dataExtractor.extractAndProcessQueryHoursGroupedData("2025-11-01 00:00:00","2025-11-15 00:00:00"));
            log.info("手动ETL任务执行完成");
        } catch (Exception e) {
            log.error("手动ETL任务执行失败", e);
            throw new RuntimeException("ETL任务执行失败", e);
        }
    }

    /**
     * 手动触发ETL任务,参数开始时间，结束时间
     * @param startTime
     * @param endTime
     */
    public void triggerETLManuallyByTime(String startTime ,String endTime) {
        log.info("手动触发ETL任务");
        try {
            retryHandler.executeWithRetry(() ->
                    dataExtractor.extractAndProcessQueryHoursGroupedData( startTime ,  endTime ));
            retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcessQueryHoursAlarm(startTime,endTime ));
            log.info("手动ETL任务执行完成");
        } catch (Exception e) {
            log.error("手动ETL任务执行失败", e);
            throw new RuntimeException("ETL任务执行失败", e);
        }
    }

    /**
     * 每天凌晨3点清理2天前的数据
     */
    @Scheduled(cron = "0 0 3 * * ?")
       public void cleanupOldLogs() {
        try {
            //默认删除7天内接收日志记录
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(2);
            int deleted = deviceReceiveLogService.deleteOldLogs(cutoffTime);
            log.info("定时清理任务完成，删除{}条2天前的日志", deleted);
        } catch (Exception e) {
            log.error("定时清理日志失败", e);
        }
    }


    public static void main(String[] args) {

        LocalDateTime befor= LocalDateTime.of(2025, 11, 1, 0, 0  ,0); // 默认2025年11月
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(2);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(befor.format(formatter).toString());
        System.out.println(cutoffTime.format(formatter).toString());
    }


}