
package com.njcn.system.timer.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.Log;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.system.enums.SystemResponseEnum;
import com.njcn.system.timer.TimerExeService;
import com.njcn.system.timer.TimerTaskRunner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * hutool方式的定时任务执行
 *
 * @author hongawen
 */
@Service
@Slf4j
public class HutoolTimerExeServiceImpl implements TimerExeService {

    @Value("${runTake.maxRetryCount}")
    private Integer maxRetryCount;
    @Value("${runTake.delayTime}")
    private Integer delayTime;
    @Override
    public void startTimer(String taskId, String cron, String className) {

        if (ObjectUtil.hasEmpty(taskId, cron, className)) {
            throw new BusinessException(SystemResponseEnum.EXE_EMPTY_PARAM);
        }

        // 预加载类看是否存在此定时任务类
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new BusinessException(SystemResponseEnum.TIMER_NOT_EXISTED);
        }

        // 定义hutool的任务
        Task task = () -> {
            try {
                TimerTaskRunner timerTaskRunner = (TimerTaskRunner) SpringUtil.getBean(Class.forName(className));
                runTaskWithRetryAndDelay(timerTaskRunner);
            } catch (ClassNotFoundException e) {
                log.error(">>> 任务执行异常：{}", e.getMessage());
            } catch (InterruptedException e) {
                log.error(">>> 运行任务执行异常：{}", e.getMessage());
            }
        };

        // 开始执行任务
        CronUtil.schedule(taskId, cron, task);
    }

    @Override
    public void stopTimer(String taskId) {
        CronUtil.remove(taskId);
    }

    public void runTaskWithRetryAndDelay(TimerTaskRunner timerTaskRunner) throws InterruptedException {
        // 重试次数计数器
        int retryCount = 0;
        while (retryCount < maxRetryCount) {
            try {
                System.out.println(LocalDateTime.now()+"自动重试机制："+(retryCount+1));
                timerTaskRunner.action(null);
                return; // 任务执行成功，跳出循环
            } catch (Exception e) {
                e.printStackTrace();
                // 处理异常
                // 增加重试次数
                retryCount++;
                // 等待一段时间
                Thread.sleep(delayTime);
            }
        }
    }
}
