package com.common.schedule;

import com.common.service.AlarmHealthCheckService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 告警健康检查定时任务
 * 每5分钟巡检告警表和告警日志表
 */
@Component
public class AlarmHealthCheckScheduler {

    private static final Logger logger = LoggerFactory.getLogger(AlarmHealthCheckScheduler.class);

    @Autowired
    private AlarmHealthCheckService alarmHealthCheckService;

    /**
     * 每30分钟执行一次告警健康检查
     * 巡检告警表 alarm 和告警日志表 alarm_visit
     */
    @Scheduled(cron = "0 */30 * * * ?")
    public void scheduledHealthCheck() {
        logger.info("========== 开始执行告警健康检查 ==========");
        long startTime = System.currentTimeMillis();
        
        try {
            boolean hasAlarm = alarmHealthCheckService.performHealthCheck();
            
            long elapsedTime = System.currentTimeMillis() - startTime;
            
            if (hasAlarm) {
                logger.warn("告警健康检查完成, 发现异常数据, 耗时: {}ms", elapsedTime);
            } else {
                logger.info("告警健康检查完成, 所有表数据正常, 耗时: {}ms", elapsedTime);
            }
        } catch (Exception e) {
            logger.error("告警健康检查执行异常: {}", e.getMessage(), e);
        }
        
        logger.info("========== 告警健康检查任务结束 ==========");
    }

    /**
     * 手动触发健康检查（供其他服务调用）
     * @return 是否有异常
     */
    public boolean manualHealthCheck() {
        logger.info("手动触发告警健康检查");
        return alarmHealthCheckService.performHealthCheck();
    }
}
