package com.multictrl.modules.job.utils;

import com.multictrl.common.constant.Constant;
import com.multictrl.common.exception.ErrorCode;
import com.multictrl.common.exception.ExceptionUtils;
import com.multictrl.common.exception.RenException;
import com.multictrl.modules.job.entity.ScheduleJobEntity;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.Date;

/**
 * 定时任务工具类
 */
@Slf4j
public class ScheduleUtils {
    private final static String JOB_NAME = "TASK_";
    /**
     * 任务调度参数key
     */
    public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(Long jobId) {
        return TriggerKey.triggerKey(JOB_NAME + jobId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(Long jobId) {
        return JobKey.jobKey(JOB_NAME + jobId);
    }

    /**
     * 获取表达式触发器
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
        try {
            return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
        try {
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getId())).build();

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId())).withSchedule(scheduleBuilder).build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JOB_PARAM_KEY, scheduleJob);

            scheduler.scheduleJob(jobDetail, trigger);

            //暂停任务
            if (scheduleJob.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()) {
                pauseJob(scheduler, scheduleJob.getId(), false);
            }
        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJobEntity scheduleJob) {
        try {
            TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());

            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

            //参数
            trigger.getJobDataMap().put(JOB_PARAM_KEY, scheduleJob);

            scheduler.rescheduleJob(triggerKey, trigger);

            //暂停任务
            if (scheduleJob.getStatus() == Constant.ScheduleStatus.PAUSE.getValue()) {
                pauseJob(scheduler, scheduleJob.getId(), false);
            }

        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 立即执行任务
     */
    public static int run(Scheduler scheduler, ScheduleJobEntity scheduleJob, boolean validateExpired) {
        try {
            Long jobId = scheduleJob.getId();
            if (validateExpired && isJobExpired(scheduler, jobId)) {
                removeExpiredJob(scheduler, jobId);
                return Constant.ScheduleStatus.FAILURE.getValue();
            }

            //参数
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JOB_PARAM_KEY, scheduleJob);

            scheduler.triggerJob(getJobKey(jobId), dataMap);
            return Constant.ScheduleStatus.NORMAL.getValue();
        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 暂停任务
     */
    public static int pauseJob(Scheduler scheduler, Long jobId, boolean validateExpired) {
        try {
            if (validateExpired && isJobExpired(scheduler, jobId)) {
                removeExpiredJob(scheduler, jobId);
                return Constant.ScheduleStatus.FAILURE.getValue();
            }

            scheduler.pauseJob(getJobKey(jobId));
            return Constant.ScheduleStatus.PAUSE.getValue();
        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 恢复任务
     */
    public static int resumeJob(Scheduler scheduler, Long jobId, boolean validateExpired) {
        try {
            if (validateExpired && isJobExpired(scheduler, jobId)) {
                removeExpiredJob(scheduler, jobId);
                return Constant.ScheduleStatus.FAILURE.getValue();
            }

            scheduler.resumeJob(getJobKey(jobId));
            return Constant.ScheduleStatus.NORMAL.getValue();
        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 检查任务是否已过期
     */
    private static boolean isJobExpired(Scheduler scheduler, Long jobId) {
        try {
            Trigger trigger = scheduler.getTrigger(TriggerKey.triggerKey(JOB_NAME + jobId));
            Date nextFireTime = trigger.getNextFireTime();
            return nextFireTime != null && nextFireTime.before(new Date());
           /* TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + jobId);
            // 1. Trigger 不存在（已被删除）→ 视为过期
            if (!scheduler.checkExists(triggerKey)) {
                return true;
            }
            // 2. 检查 Trigger 状态：仅 COMPLETE 表示“已永久完成”
            Trigger.TriggerState state = scheduler.getTriggerState(triggerKey);
            return state == Trigger.TriggerState.COMPLETE;*/
        } catch (SchedulerException e) {
            log.debug("判断任务 {} 是否过期失败", jobId);
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }

    /**
     * 移除过期任务（从调度器中移除并更新状态）
     */
    private static void removeExpiredJob(Scheduler scheduler, Long jobId) {
        try {
            // 从调度器中移除
            scheduler.deleteJob(getJobKey(jobId));

            log.debug("任务 {} 已过期，已从调度器中移除并标记为失效", jobId);
        } catch (SchedulerException e) {
            log.error("移除过期任务失败: {}", ExceptionUtils.getErrorStackTrace(e));
            throw new RenException(ErrorCode.JOB_ERROR, e);
        }
    }
}