
package com.njcn.system.timer;

import cn.hutool.cron.CronUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.system.pojo.enums.TimerJobStatusEnum;
import com.njcn.system.pojo.param.TimersParam;
import com.njcn.system.pojo.po.Timers;
import com.njcn.system.service.ITimersService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : hongawen
 */
@Component
public class TimerTaskInitListener implements ApplicationRunner, Ordered {

    /**
     *
     * @param args incoming application arguments
     */
    @Override
    public void run(ApplicationArguments args) {
        ITimersService sysTimersService = SpringUtil.getBean(ITimersService.class);
        TimerExeService timerExeService = SpringUtil.getBean(TimerExeService.class);
        // 获取所有开启状态的任务
        LambdaQueryWrapper<Timers> lambdaQueryChainWrapper = new LambdaQueryWrapper<>();
        lambdaQueryChainWrapper.eq(Timers::getJobStatus,TimerJobStatusEnum.RUNNING.getCode())
                .ne(Timers::getState, DataStateEnum.DELETED.getCode());
        List<Timers> list = sysTimersService.list(lambdaQueryChainWrapper);
        // 添加定时任务到调度器
        for (Timers sysTimers : list) {
            timerExeService.startTimer(String.valueOf(sysTimers.getId()), sysTimers.getCron(), sysTimers.getActionClass());
        }

        // 设置秒级别的启用
        CronUtil.setMatchSecond(true);

        // 启动定时器执行器
        CronUtil.start();
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE-10;
    }
}
