package com.foreverwin.mesnac.quartz.util;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 定时任务工具类
 *
 * @author ruoyi
 */
public class ScheduleUtil {
    private static final Logger log = LoggerFactory.getLogger(ScheduleUtil.class);

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, String jobName, String jobClass, String jobGroupName, String description, String cronExpression, Map<String, Object> jobParam) {
        try {
            // 构建job信息
            JobDetail jobDetail = createJobDetail(jobName, jobClass, jobGroupName, description);
            // 表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            cronScheduleBuilder = cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();
            // 按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(TriggerKey.triggerKey(jobName, jobGroupName)).withSchedule(cronScheduleBuilder).build();
            // 放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().putAll(jobParam);
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            log.error("createScheduleJob 异常：", e);
        }
    }

    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, String jobId, String jobGroupName, String cronExpression, Map<String, Object> jobParam) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobId, jobGroupName);
            // 表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            cronScheduleBuilder = cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
            // 参数
            trigger.getJobDataMap().putAll(jobParam);
            // 按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            log.error("SchedulerException 异常：", e);
        }
    }

    /**
     * 立即执行任务
     */
    public static void runScheduleJob(Scheduler scheduler, String jobId, String jobGroupName, Map<String, Object> jobParam) {
        try {
            // 参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.putAll(jobParam);
            scheduler.triggerJob(JobKey.jobKey(jobId, jobGroupName), dataMap);
        } catch (SchedulerException e) {
            log.error("runScheduleJob 异常：", e);
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobId, String jobGroupName) {
        try {
            scheduler.pauseJob(JobKey.jobKey(jobId, jobGroupName));
        } catch (SchedulerException e) {
            log.error("pauseScheduleJob 异常：", e);
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeScheduleJob(Scheduler scheduler, String jobId, String jobGroupName) {
        try {
            scheduler.resumeJob(JobKey.jobKey(jobId, jobGroupName));
        } catch (SchedulerException e) {
            log.error("resumeScheduleJob 异常：", e);
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobId, String jobGroupName) {
        try {
            scheduler.deleteJob(JobKey.jobKey(jobId, jobGroupName));
        } catch (SchedulerException e) {
            log.error("deleteScheduleJob 异常：", e);
        }
    }

    public static JobDetail createJobDetail(String jobName, String jobClass, String jobGroupName, String description) throws Exception {
        Class clazz = Class.forName(jobClass);
        JobDetail jobDetail = JobBuilder.newJob(clazz)
                .withIdentity(JobKey.jobKey(jobName, jobGroupName))
                .withDescription(description)
                .build();
        return jobDetail;
    }


    /*public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
            throws TaskException
    {
        switch (job.getMisfirePolicy())
        {
            case ScheduleConstants.MISFIRE_DEFAULT:
                return cb;
            case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
                return cb.withMisfireHandlingInstructionIgnoreMisfires();
            case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
                return cb.withMisfireHandlingInstructionFireAndProceed();
            case ScheduleConstants.MISFIRE_DO_NOTHING:
                return cb.withMisfireHandlingInstructionDoNothing();
            default:
                throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() + "' cannot be used in cron schedule tasks", TaskException.Code.CONFIG_ERROR);
        }
    }*/
}
