package org.xyzh.crontab.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.xyzh.common.dto.crontab.TbCrontabTask;
import org.xyzh.crontab.mapper.CrontabTaskMapper;

import java.util.List;

/**
 * @description 定时任务初始化器，启动时加载所有运行中的任务
 * @filename SchedulerInitializer.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-25
 */
@Component
public class SchedulerInitializer implements CommandLineRunner {

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

    @Autowired
    private CrontabTaskMapper taskMapper;

    @Autowired
    private SchedulerManager schedulerManager;

    @Override
    public void run(String... args) throws Exception {
        try {
            logger.info("开始初始化定时任务...");
            
            // 查询所有运行中的任务（系统级，不受权限限制）
            List<TbCrontabTask> runningTasks = taskMapper.selectAllRunningTasks();
            
            if (runningTasks != null && !runningTasks.isEmpty()) {
                for (TbCrontabTask task : runningTasks) {
                    try {
                        schedulerManager.scheduleTask(task);
                        logger.info("加载定时任务: {} [{}]", task.getTaskName(), task.getCronExpression());
                    } catch (Exception e) {
                        logger.error("加载定时任务失败: {}", task.getTaskName(), e);
                    }
                }
                logger.info("定时任务初始化完成，共加载 {} 个任务", runningTasks.size());
            } else {
                logger.info("没有需要加载的定时任务");
            }
        } catch (Exception e) {
            logger.error("定时任务初始化异常: ", e);
        }
    }
}

