package com.erp.task.config;

import org.springframework.boot.autoconfigure.quartz.QuartzProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

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

/**
 * Quartz配置
 */
@Configuration
@EnableConfigurationProperties(QuartzProperties.class)
public class QuartzConfig {

    private final QuartzProperties quartzProperties;

    private final ApplicationContext applicationContext;

    public QuartzConfig(QuartzProperties quartzProperties, ApplicationContext applicationContext) {
        this.quartzProperties = quartzProperties;
        this.applicationContext = applicationContext;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setDataSource(dataSource);
        factory.setApplicationContext(applicationContext);
        factory.setQuartzProperties(quartzProperties());
        factory.setOverwriteExistingJobs(true);
        factory.setAutoStartup(true);
        factory.setWaitForJobsToCompleteOnShutdown(true);
        return factory;
    }

    private Properties quartzProperties() {
        Properties props = new Properties();
        props.putAll(quartzProperties.getProperties());
        return props;
    }
}
