package com.qqchen.deploy.backend.schedule.config;

import org.quartz.Scheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 定时任务配置
 * 启用Spring调度功能和Quartz调度器
 * 
 * @author qichen
 */
@Configuration
@EnableScheduling
@EnableAsync
public class ScheduleConfig {

    /**
     * 配置Quartz调度器工厂
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource, QuartzJobFactory quartzJobFactory) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        
        // 设置数据源（可选，如果需要持久化到数据库）
        // factory.setDataSource(dataSource);
        
        // 设置JobFactory，支持Spring依赖注入
        factory.setJobFactory(quartzJobFactory);
        
        // Quartz配置
        Properties properties = new Properties();
        
        // 调度器名称
        properties.put("org.quartz.scheduler.instanceName", "DeployEaseScheduler");
        properties.put("org.quartz.scheduler.instanceId", "AUTO");
        
        // 线程池配置
        properties.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        properties.put("org.quartz.threadPool.threadCount", "10");
        properties.put("org.quartz.threadPool.threadPriority", "5");
        
        // 内存存储（不持久化到数据库）
        properties.put("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
        
        // 如果需要持久化到数据库，使用以下配置
        // properties.put("org.quartz.jobStore.class", "org.springframework.scheduling.quartz.LocalDataSourceJobStore");
        // properties.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        // properties.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        // properties.put("org.quartz.jobStore.isClustered", "false");
        
        factory.setQuartzProperties(properties);
        
        // 延迟启动（秒）
        factory.setStartupDelay(10);
        
        // 应用关闭时等待任务完成
        factory.setWaitForJobsToCompleteOnShutdown(true);
        
        // 覆盖已存在的任务
        factory.setOverwriteExistingJobs(true);
        
        // 自动启动
        factory.setAutoStartup(true);
        
        return factory;
    }

    /**
     * 获取Scheduler实例
     */
    @Bean
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) {
        return schedulerFactoryBean.getScheduler();
    }
}
