package cc.smtweb.system.bpm.web.sys.base.job;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.*;

/**
 * Created by Akmm at 13-2-27 下午9:32
 * 定时任务工厂
 */
@Slf4j
public class JobUtils {
    private static Scheduler scheduler = null;
    private static JobUtils instance = null;
    private Map<String, JobEntity> mapJob = new HashMap<>();


    public static Scheduler getScheduler() {
        return scheduler;
    }

    public static JobUtils getInstance() {
        if (instance == null) {
            synchronized (JobUtils.class) {
                if (instance == null) {
                    instance = new JobUtils();
                }
            }
        }
        return instance;
    }

    private JobUtils() {
        try {
            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            scheduler = schedulerFactory.getScheduler();
        } catch (Exception e) {
            log.error("计划任务初始化失败", e);
            e.printStackTrace();
        }
    }

    //初始化所有任务
    private void initJob() throws Exception {
        Collection<JobEntity> list = JobCache.getInstance().getAll();
        for (JobEntity job : list) {
            if (job.isEnable()) {
                addJob(job);
            }
        }

    }

    public void start() {
        try {
            clear();
            if (!scheduler.isStarted()) scheduler.start();
            initJob();
        } catch (Exception e) {
            log.error("计划任务开始失败", e);
            e.printStackTrace();
        }
    }

    public void stop() {
        try {
            if (!scheduler.isShutdown()) {
                clear();
                scheduler.shutdown();
            }
        } catch (Exception e) {
            log.error("计划任务开始失败", e);
            e.printStackTrace();
        }
    }

    public void clear() throws SchedulerException {
        for (JobEntity job : mapJob.values()) {
            try {
                deleteJob(job);
            } catch (Exception e) {
                log.debug("任务" + job.getId() + "删除失败!");
            }
        }
    }

    //添加任务
    public synchronized void addJob(JobEntity job) throws Exception {
        String jobId = String.valueOf(job.getId());
        JobDetail jobDetail = JobBuilder.newJob((Class<? extends org.quartz.Job>) Class.forName(job.getExeClass()))
                .withIdentity(jobId).build();
        jobDetail.getJobDataMap().put("job", job);
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobId)
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    //删除任务
    public synchronized void deleteJob(JobEntity job) throws Exception {
        String jobId = String.valueOf(job.getId());

        scheduler.pauseTrigger(TriggerKey.triggerKey(jobId));
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobId));
        scheduler.deleteJob(JobKey.jobKey(jobId));
    }
}
