package com.hs.admin.service.impl;

import com.hs.admin.bean.SysTask;
import com.hs.admin.service.JobManagerService;
import com.hs.admin.util.JsonUtils;
import org.quartz.*;
import org.quartz.utils.Key;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.net.URL;

/**
 * @author xieheng
 */
@Service
public class JobManagerServiceImpl implements JobManagerService {
    @Resource
    Scheduler scheduler;

    /**
     * 添加任务
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean addJob(SysTask task) {
        try {
            deleteJob(task);
            String key = String.valueOf(task.getJcbId());
            String value = String.valueOf(task.getCid());

            // 创建jobDetail实例，绑定Job实现类
            // 指明job的名称，所在组的名称，以及绑定job类
            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(task.getBeanClass()).newInstance().getClass());
            // 任务名称和组构成任务key
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(key, value).build();
            // 定义调度触发规则
            // 使用cornTrigger规则
            // 触发器key
            TriggerBuilder builder = TriggerBuilder.newTrigger().withIdentity(key, value)
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND));
            if (!ObjectUtils.isEmpty(task.getCronExpression())) {
                builder.withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression()));
            }
            Trigger trigger = builder.startNow().build();
            trigger.getJobDataMap().put("triggerTask", JsonUtils.beanToJson(task));
            // 把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @description: 暂停任务
     * @return: void
     * @author: XieHeng
     * @date: 2021/4/27 5:35 下午
     */
    @Override
    public boolean pauseJob(SysTask task) {
        JobKey jobKey = JobKey.jobKey(String.valueOf(task.getJcbId()), String.valueOf(task.getCid()));
        try {
            boolean b = scheduler.checkExists(jobKey);
            if (b) {
                scheduler.deleteJob(jobKey);
            }
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @description: 恢复任务
     * @return: void
     * @author: XieHeng
     * @date: 2021/4/27 5:35 下午
     */
    @Override
    public boolean resumeJob(SysTask task) {
        JobKey jobKey = JobKey.jobKey(String.valueOf(task.getJcbId()), String.valueOf(task.getCid()));
        try {
            boolean b = scheduler.checkExists(jobKey);
            if (b) {
                scheduler.resumeJob(jobKey);
            } else {
                addJob(task);
            }
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @description: 删除任务
     * @return: void
     * @author: XieHeng
     * @date: 2021/4/27 5:35 下午
     */
    @Override
    public boolean deleteJob(SysTask task) {
        try {
            JobKey jobKey = JobKey.jobKey(String.valueOf(task.getJcbId()), String.valueOf(task.getCid()));
            scheduler.deleteJob(jobKey);
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * @description: 立马执行任务
     * @return: void
     * @author: XieHeng
     * @date: 2021/4/27 5:35 下午
     */
    @Override
    public boolean runJobNow(SysTask task) {
        JobKey jobKey = JobKey.jobKey(String.valueOf(task.getJcbId()), String.valueOf(task.getCid()));
        try {
            scheduler.triggerJob(jobKey);
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @description: 更新cron表达式
     * @return: void
     * @author: XieHeng
     * @date: 2021/4/27 5:36 下午
     */
    @Override
    public boolean updateJobCron(SysTask task) {
        TriggerKey triggerKey = TriggerKey.triggerKey(String.valueOf(task.getJcbId()), String.valueOf(task.getCid()));
        try {
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCronExpression());
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
            scheduler.rescheduleJob(triggerKey, trigger);
            return true;
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }

}
