package com.common.schedule;

import com.common.service.AnalysisRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 离线分析定时任务
 */
@Slf4j
@Component
public class OfflineAnalysisScheduler {

    @Autowired
    private AnalysisRuleService analysisRuleService;

    @Value("${analysis.offline.enabled:true}")
    private boolean offlineEnabled;

    /**
     * 定时执行离线分析（使用cron表达式，默认每小时执行一次）
     * 具体分析规则运行需要根据配置运行时间周期进行，离线暂停
     */
   // @Scheduled(cron = "${analysis.offline.cron-expression:0 0 */1 * * ?}")
    public void executeOfflineAnalysis() {
        if (!offlineEnabled) {
            log.debug("离线分析引擎已禁用，跳过执行");
            return;
        }

        try {
            log.info("========== 开始执行离线分析任务 ==========");
            long startTime = System.currentTimeMillis();

            List<Map<String, Object>> results = analysisRuleService.executeOfflineAnalysis();

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            log.info("========== 离线分析任务完成，耗时: {} ms，处理规则数: {} ==========",
                    duration, results.size());

            // 输出执行结果摘要
            for (Map<String, Object> result : results) {
                log.info("规则: {}, 状态: {}, 处理记录数: {}, 生成告警数: {}",
                        result.get("ruleName"),
                        result.get("status"),
                        result.get("processedCount"),
                        result.get("alarmCount"));
            }

        } catch (Exception e) {
            log.error("执行离线分析任务失败", e);
        }
    }
}
