package com.common.schedule;

import com.common.entity.DeviceCollectHeartbeat;
import com.common.service.ProbeHeartbeatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * 探针状态检查调度器
 * 定期检查探针是否离线，触发告警
 */
@Component
public class ProbeStatusCheckScheduler {

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

    @Autowired
    private ProbeHeartbeatService probeHeartbeatService;

    @Value("${probe.heartbeat.enabled:true}")
    private boolean heartbeatEnabled;

    /**
     * 检查探针状态
     * 默认每10分钟检查一次（可配置）
     */
    @Scheduled(cron = "${probe.status.check.cron:0 */10 * * * ?}")
    public void checkProbeStatus() {
        if (!heartbeatEnabled) {
            logger.debug("探针状态检查已禁用");
            return;
        }
        
        logger.info("========== 开始探针状态检查 ==========");
        long startTime = System.currentTimeMillis();
        
        try {
            // 检查并标记离线探针
            List<DeviceCollectHeartbeat> newlyOffline = probeHeartbeatService.checkAndMarkOfflineProbes();
            
            long elapsedTime = System.currentTimeMillis() - startTime;
            
            if (!newlyOffline.isEmpty()) {
                logger.warn("探针状态检查完成，发现 {} 个新离线探针, 离线阈值: {}分钟, 耗时: {}ms", 
                        newlyOffline.size(), 
                        probeHeartbeatService.getOfflineThresholdMinutes(),
                        elapsedTime);
                
                for (DeviceCollectHeartbeat probe : newlyOffline) {
                    logger.warn("离线探针: collectId={}, ip={}, name={}", 
                            probe.getCollectId(), probe.getDeviceIp(), probe.getCollectName());
                }
            } else {
                logger.info("探针状态检查完成，所有探针在线, 耗时: {}ms", elapsedTime);
            }
            
            // 输出当前探针统计
            List<DeviceCollectHeartbeat> allProbes = probeHeartbeatService.getAllProbes();
            long onlineCount = allProbes.stream().filter(p -> "online".equals(p.getStatus())).count();
            long offlineCount = allProbes.size() - onlineCount;
            
            logger.info("探针统计: 总数={}, 在线={}, 离线={}", 
                    allProbes.size(), onlineCount, offlineCount);
            
        } catch (Exception e) {
            logger.error("探针状态检查异常: {}", e.getMessage(), e);
        }
        
        logger.info("========== 探针状态检查结束 ==========");
    }

    /**
     * 手动触发探针状态检查
     * @return 新增的离线探针数量
     */
    public int manualCheck() {
        logger.info("手动触发探针状态检查");
        List<DeviceCollectHeartbeat> newlyOffline = probeHeartbeatService.checkAndMarkOfflineProbes();
        return newlyOffline.size();
    }
}
