package com.multictrl.modules.job.utils;

import com.multictrl.common.exception.ExceptionUtils;
import com.multictrl.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronExpression;

import java.text.ParseException;
import java.util.Date;

/**
 * cron表达式解析
 *
 * @author Sdy
 * @since 1.0.0 2025/7/22
 */
@Slf4j
public class CronParser {

    /**
     * 获取下一次执行时间
     */
    public static String getNextTime(String cronExpression) {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            Date now = new Date(); // 当前时间
            Date nextTime = cron.getNextValidTimeAfter(now); // 获取下一次执行时间
            return DateUtils.format(nextTime, "yyyy-MM-dd HH:mm");
        } catch (ParseException e) {
            log.error(ExceptionUtils.getErrorStackTrace(e));
            return null;
        }
    }

    /**
     * 是否有效
     */
    public static boolean isValid(String cronExpression, Date now) {
        try {
            boolean validExpression = CronExpression.isValidExpression(cronExpression);
            if (validExpression) {
                CronExpression cron = new CronExpression(cronExpression);
                Date nextFireTime = cron.getNextValidTimeAfter(now);
                return !(nextFireTime == null || nextFireTime.before(now));
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
}
