package com.cpop.core.utils;

import com.cpop.core.base.exception.UtilException;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * @author: DB
 * @Date: 2023/07/12/16:54
 * @Description:
 */
@Component
public class QuartzUtils {

    @Autowired
    private Scheduler scheduler;

    /**
     * @Description: 获取Job信息
     * @param name
     * @param group
     * @return String
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        Trigger trigger = scheduler.getTrigger(triggerKey);
        if (trigger == null) {
            throw new UtilException("获取定时任务失败");
        }
        CronTrigger cronTrigger = (CronTrigger) trigger;
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(),
                scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * @Description: 修改某个任务的执行时间
     * @param name
     * @param group
     * @param time
     * @return boolean
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public boolean modifyJob(String name, String group, String time) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        Trigger triggerResult = scheduler.getTrigger(triggerKey);
        if (triggerResult != null) {
            CronTrigger cronTrigger = (CronTrigger) triggerResult;
            String oldTime = cronTrigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(time)) {
                CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
                CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group)
                        .withSchedule(cronScheduleBuilder).build();
                date = scheduler.rescheduleJob(triggerKey, trigger);
            }
            return date != null;
        } else {
            return false;
        }
    }

    /**
     * @Description: 暂停所有任务
     * @param
     * @return
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * @Description: 暂停某个任务
     * @param name
     * @param group
     * @return
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public void pauseJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.pauseJob(jobKey);
    }

    /**
     * @Description: 恢复所有任务
     * @param
     * @return
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * @Description: 恢复某个任务
     * @param name
     * @param group
     * @return
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public void resumeJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.resumeJob(jobKey);
    }

    /**
     * @Description: 删除某个任务
     * @param name
     * @param group
     * @return
     * @author DB
     * @Date: 2023/7/12 0012 16:57
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.deleteJob(jobKey);
    }

    /**
     * @Description: 日期转Cron
     * @param date
     * @return String
     * @author DB
     * @Date: 2023/7/14 0014 11:26
     */
    public String convertToCron(Date date) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int seconds = calendar.get(Calendar.SECOND);
        int minutes = calendar.get(Calendar.MINUTE);
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        // Calendar中的月份从0开始，所以需要加1
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);
        return seconds + " " +
                minutes + " " +
                hours + " " +
                dayOfMonth + " " +
                month + " " +
                "? " + year;
    }

    /**
     * 获取任务执行时间
     * @author DB
     * @since 2024/2/22
     * @param name
     * @param group
     * @return LocalDateTime
     */
    public LocalDateTime getJobExecuteTime(String name, String group) throws SchedulerException {
        String jobInfo = getJobInfo(name, group);
        String[] split = jobInfo.split(",")[0].replaceAll("time:", "").split(" ");
        return LocalDateTime.of(Integer.parseInt(split[6]), Integer.parseInt(split[4]), Integer.parseInt(split[3]), Integer.parseInt(split[2]), Integer.parseInt(split[1]), Integer.parseInt(split[0]));
    }
}
