package com.zehong.quartz.config;

import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author lenovo
 * @date 2025/10/15
 * @description TODO
 */
@Component
public class QuartzTaskMonitor {

    private static final Logger log = LoggerFactory.getLogger(QuartzTaskMonitor.class);

    @Resource
    private Scheduler scheduler;
    /**
     * 监控指定storeyId的任务状态
     */
    public void monitorTaskStatus(Long fStoreyId) {
        try {
            String JOB_GROUP = "DEVICE_TASKS";
            String TRIGGER_GROUP = "DEVICE_TRIGGERS";

            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(JOB_GROUP));
            Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(TRIGGER_GROUP));

            log.info("=== 任务状态详细监控：storeyId={} ===", fStoreyId);
            log.info("总任务数: {}, 总触发器数: {}", jobKeys.size(), triggerKeys.size());

            int relatedJobs = 0;
            int relatedTriggers = 0;

            // 监控相关任务
            for (JobKey jobKey : jobKeys) {
                if (jobKey.getName().contains(fStoreyId.toString())) {
                    relatedJobs++;
                    List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                    for (Trigger trigger : triggers) {
                        Trigger.TriggerState state = scheduler.getTriggerState(trigger.getKey());
                        Date nextFireTime = trigger.getNextFireTime();
                        Date previousFireTime = trigger.getPreviousFireTime();

                        log.info("任务[{}]:", jobKey.getName());
                        log.info("  - 状态: {}", state);
                        log.info("  - 下次执行: {}", nextFireTime);
                        log.info("  - 上次执行: {}", previousFireTime);
                        log.info("  - 触发器: {}", trigger.getKey().getName());

                        if (trigger instanceof SimpleTrigger) {
                            SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
                            log.info("  - 重复次数: {}/{}",
                                    simpleTrigger.getTimesTriggered(),
                                    simpleTrigger.getRepeatCount() + 1);
                        }
                    }
                }
            }

            // 监控相关触发器
            for (TriggerKey triggerKey : triggerKeys) {
                if (triggerKey.getName().contains(fStoreyId.toString())) {
                    relatedTriggers++;
                    Trigger trigger = scheduler.getTrigger(triggerKey);
                    if (trigger != null) {
                        Trigger.TriggerState state = scheduler.getTriggerState(triggerKey);
                        log.info("独立触发器[{}]: 状态={}, 下次执行={}",
                                triggerKey.getName(), state, trigger.getNextFireTime());
                    }
                }
            }

            log.info("相关任务数: {}, 相关触发器数: {}", relatedJobs, relatedTriggers);

            // 调度器整体状态
            SchedulerMetaData metaData = scheduler.getMetaData();
            log.info("调度器整体状态:");
            log.info("  - 已启动: {}", scheduler.isStarted());
            log.info("  - 待机模式: {}", scheduler.isInStandbyMode());
            log.info("  - 已关闭: {}", scheduler.isShutdown());
            log.info("  - 执行任务总数: {}", metaData.getNumberOfJobsExecuted());
            log.info("  - 运行中任务: {}", scheduler.getCurrentlyExecutingJobs().size());

        } catch (SchedulerException e) {
            log.error("任务状态监控失败：storeyId={}", fStoreyId, e);
        }
    }

    /**
     * 监控所有任务状态
     */
    public void monitorAllTasksStatus() {
        try {
            String JOB_GROUP = "DEVICE_TASKS";
            String TRIGGER_GROUP = "DEVICE_TRIGGERS";

            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(JOB_GROUP));
            Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(TRIGGER_GROUP));

            log.info("=== 所有任务状态监控 ===");
            log.info("总任务数: {}, 总触发器数: {}", jobKeys.size(), triggerKeys.size());

            // 按storeyId分组显示
            Map<String, List<JobKey>> jobsByStorey = new HashMap<>();
            for (JobKey jobKey : jobKeys) {
                String jobName = jobKey.getName();
                // 解析storeyId：COMM_501_1_123 中的 123
                String[] parts = jobName.split("_");
                if (parts.length >= 4) {
                    String storeyId = parts[3];
                    jobsByStorey.computeIfAbsent(storeyId, k -> new ArrayList<>()).add(jobKey);
                }
            }

            for (Map.Entry<String, List<JobKey>> entry : jobsByStorey.entrySet()) {
                log.info("StoreyId {} 的任务数: {}", entry.getKey(), entry.getValue().size());
                for (JobKey jobKey : entry.getValue()) {
                    List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                    for (Trigger trigger : triggers) {
                        Trigger.TriggerState state = scheduler.getTriggerState(trigger.getKey());
                        log.info("  - {}: 状态={}, 下次执行={}",
                                jobKey.getName(), state, trigger.getNextFireTime());
                    }
                }
            }

        } catch (SchedulerException e) {
            log.error("所有任务状态监控失败", e);
        }
    }

    /**
     * 检查调度器健康状态
     */
    public void checkSchedulerHealth() {
        try {
            SchedulerMetaData metaData = scheduler.getMetaData();
            log.info("=== 调度器健康检查 ===");
            log.info("调度器名称: {}", metaData.getSchedulerName());
            log.info("调度器实例ID: {}", metaData.getSchedulerInstanceId());
            log.info("已启动: {}", scheduler.isStarted());
            log.info("待机模式: {}", scheduler.isInStandbyMode());
            log.info("运行中任务: {}", scheduler.getCurrentlyExecutingJobs().size());
            log.info("线程池大小: {}", metaData.getThreadPoolSize());
            log.info("执行任务总数: {}", metaData.getNumberOfJobsExecuted());

            // 健康状态判断
            if (!scheduler.isStarted()) {
                log.error("❌ 调度器未启动！");
            } else if (scheduler.isInStandbyMode()) {
                log.warn("⚠️ 调度器处于待机模式");
            } else {
                log.info("✅ 调度器运行正常");
            }

        } catch (SchedulerException e) {
            log.error("调度器健康检查失败", e);
        }
    }
}
