package com.multictrl.modules.job.init;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.multictrl.modules.job.dao.ScheduleJobDao;
import com.multictrl.modules.job.entity.ScheduleJobEntity;
import com.multictrl.modules.job.utils.CronParser;
import com.multictrl.modules.job.utils.ScheduleUtils;
import lombok.RequiredArgsConstructor;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 初始化定时任务数据
 *
 * @author Sdy
 */
@Component
@RequiredArgsConstructor
public class JobCommandLineRunner implements CommandLineRunner {
    private final Scheduler scheduler;
    private final ScheduleJobDao scheduleJobDao;

    @Override
    public void run(String... args) {
        Date now = new Date();
        List<ScheduleJobEntity> scheduleJobList = scheduleJobDao.selectList(new QueryWrapper<ScheduleJobEntity>().ne("status", -1));
        Iterator<ScheduleJobEntity> iterator = scheduleJobList.iterator();
        while (iterator.hasNext()) {
            ScheduleJobEntity item = iterator.next();
            Integer cronType = item.getCronType();
            if (1 == cronType) {
                boolean valid = CronParser.isValid(item.getCronExpression(), now);
                if (!valid) {
                    scheduleJobDao.update(null, new UpdateWrapper<ScheduleJobEntity>().eq("id", item.getId()).set("status", -1));
                    iterator.remove(); // 安全删除
                }
            }
        }
        for (ScheduleJobEntity scheduleJob : scheduleJobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    }
}