package cn.superdesk.uniorder.executor.scheduler.utils;

import cn.hutool.core.date.DateUtil;
import cn.superdesk.uniorder.common.enums.thirdpart.jd.SysQuartzScheduleTaskStatementOfAccountIsPauseEnum;
import cn.superdesk.uniorder.common.exception.BadRequestException;
import cn.superdesk.uniorder.dao.entity.scheduler.SysQuartzJob;
import cn.superdesk.uniorder.dto.param.scheduler.SysQuartzJobParam;
import cn.superdesk.uniorder.dubbo.consumer.scheduler.SysQuartzJobDubboConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static org.quartz.TriggerBuilder.newTrigger;


/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2020/12/23 上午11:05
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020/12/23 上午11:05
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Component
public class QuartzManage {

    private static final String JOB_NAME = "TASK_";

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    @Resource
    private SysQuartzJobDubboConsumerService sysQuartzJobDubboConsumerService;

    public void addJob(SysQuartzJob quartzJob) {


        try {

            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class).withIdentity(JOB_NAME + quartzJob.getId()).build();

            // 通过触发器名和cron 表达式创建 Trigger
            Trigger cronTrigger = newTrigger()
                    .withIdentity(JOB_NAME + quartzJob.getId())
                    .startNow()
                    .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()))
                    .build();

            cronTrigger.getJobDataMap().put(SysQuartzJobParam.JOB_KEY, quartzJob);

            // 重置启动时间
            ((CronTriggerImpl) cronTrigger).setStartTime(DateUtil.date());

            // 执行定时任务
            scheduler.scheduleJob(jobDetail, cronTrigger);

            // 暂停任务 状态:1-暂停;0-启用;
            if (quartzJob.getIsPause().equals(SysQuartzScheduleTaskStatementOfAccountIsPauseEnum.暂停.getKey())) {
                pauseJob(quartzJob);
            }

        } catch (Exception e) {
            log.error("创建定时任务失败", e);
            throw new BadRequestException("创建定时任务失败");
        }
    }

    /**
     * 更新job cron表达式
     *
     * @param quartzJob /
     */
    public void updateJobCron(SysQuartzJob quartzJob) {

        try {

            TriggerKey  triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger    = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            }

            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            // 重置启动时间
            ((CronTriggerImpl) trigger).setStartTime(DateUtil.date());
            trigger.getJobDataMap().put(SysQuartzJobParam.JOB_KEY, quartzJob);

            scheduler.rescheduleJob(triggerKey, trigger);

            // 暂停任务 状态:1-暂停;0-启用;
            if (quartzJob.getIsPause().equals(SysQuartzScheduleTaskStatementOfAccountIsPauseEnum.暂停.getKey())) {
                pauseJob(quartzJob);
            }

        } catch (Exception e) {
            log.error("更新定时任务失败", e);
            throw new BadRequestException("更新定时任务失败");
        }

    }

    /**
     * 删除一个job
     *
     * @param quartzJob /
     */
    public void deleteJob(SysQuartzJob quartzJob) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);
            scheduler.deleteJob(jobKey);

        } catch (Exception e) {
            log.error("删除定时任务失败", e);
            throw new BadRequestException("删除定时任务失败");
        }
    }

    /**
     * 恢复一个job
     *
     * @param quartzJob /
     */
    public void resumeJob(SysQuartzJob quartzJob) {

        try {

            TriggerKey  triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger    = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }

            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.resumeJob(jobKey);

        } catch (Exception e) {
            log.error("恢复定时任务失败", e);
            throw new BadRequestException("恢复定时任务失败");
        }
    }

    /**
     * 立即执行job
     *
     * @param quartzJob /
     */
    public void runJobNow(SysQuartzJob quartzJob) {

        try {

            TriggerKey  triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
            CronTrigger trigger    = (CronTrigger) scheduler.getTrigger(triggerKey);

            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                addJob(quartzJob);
            }

            JobDataMap dataMap = new JobDataMap();
            dataMap.put(SysQuartzJobParam.JOB_KEY, quartzJob);

            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());

            scheduler.triggerJob(jobKey, dataMap);
        } catch (Exception e) {
            log.error("定时任务执行失败", e);
            throw new BadRequestException("定时任务执行失败");
        }
    }

    /**
     * 暂停一个job
     *
     * @param quartzJob /
     */
    public void pauseJob(SysQuartzJob quartzJob) {

        try {

            JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
            scheduler.pauseJob(jobKey);

        } catch (Exception e) {
            log.error("定时任务暂停失败", e);
            throw new BadRequestException("定时任务暂停失败");
        }
    }
}
