package com.yunzhupaas.flowable.job;

import com.yunzhupaas.flowable.model.trigger.TimeTriggerModel;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.RedisUtil;
import org.quartz.JobDataMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

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

/**
 * 类的描述
 *
 * @author YUNZHUPAASYUNZHUPAAS开发组
 * @version 5.0.x
 * @since 2024/9/20 14:55
 */
@Component
public class TimeTriggerRunner implements ApplicationRunner {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> hashValues = redisUtil.getHashValues(TriggerJobUtil.TRIGGER_MODEL);
        for (String value : hashValues) {
            TimeTriggerModel model = JsonUtil.getJsonToBean(value, TimeTriggerModel.class);
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.putAll(JsonUtil.entityToMap(model));
            Date startTime = new Date(model.getStartTime());
            Date endTime = null != model.getEndTime() ? new Date(model.getEndTime()) : null;
            boolean isAdd = null != endTime ? endTime.getTime() > System.currentTimeMillis() : true;
            if (isAdd) {
                QuartzJobUtil.addJob(model.getId(), model.getCron(), TimeTriggerJob.class, jobDataMap, startTime,
                        endTime);
            }
        }
    }
}
