package com.skr.mdm.quartz;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.skr.mdm.bean.bo.QuartzJobBO;
import com.skr.mdm.quartz.trigger.CronTriggerHandler;
import com.skr.mdm.util.JobUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author nfq
 * @date 2022-11-01 17:30
 */
@Component
@Slf4j
public class SchedulerHandler {

    @Autowired
    private Scheduler scheduler;

    public void scheduleJob(JobDetail jobDetail, Trigger trigger) {
        try {
            scheduler.scheduleJob(jobDetail, trigger);
            if (!scheduler.isStarted()) {
                scheduler.start();
            }
        } catch (SchedulerException e) {
            log.error("quartz start异常：", e);
            throw new RuntimeException(e);
        }
    }

    public void deleteJob(List<String> jobKeyIdList) {
        try {
            for (String jobKeyId : jobKeyIdList) {
                TriggerKey triggerKey = JobUtil.getTriggerKey(jobKeyId);
                JobKey jobKey = JobUtil.getJobKey(jobKeyId);
                if (scheduler.checkExists(triggerKey)) {
                    // 暂停触发器
                    scheduler.pauseTrigger(triggerKey);
                    // 移除触发器中的任务
                    scheduler.unscheduleJob(triggerKey);
                }
                if (scheduler.checkExists(jobKey)) {
                    log.info("quartz job删除 jobKeys:{}", JSONUtil.toJsonStr(jobKey));
                    scheduler.deleteJob(jobKey);
                }
            }
        } catch (SchedulerException e) {
            log.error("quartz 删除异常：", e);
            throw new RuntimeException(e);
        }
    }

    public void handleJob(QuartzJobBO quartzJobBO, Class <? extends Job> jobClass) {
        // 获取自定义quartz key
        String quartzKey = JobUtil.getQuartzKey(quartzJobBO.getPrefix(), quartzJobBO.getId(),
                DateUtil.formatTime(quartzJobBO.getExecuteTime()));

        JobDetail jobDetail = JobDetailHandler.build(jobClass, quartzKey);
        JobDetailHandler.putJobDataMap(jobDetail, JSONUtil.toJsonStr(quartzJobBO));
        CronTrigger trigger = CronTriggerHandler.build(jobDetail, quartzKey, quartzJobBO.getExecuteTime());
        deleteJob(ListUtil.toList(quartzKey));
        scheduleJob(jobDetail, trigger);
    }


}
