package org.wcs.starter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.wcs.constant.enums.common.TrueOrFalseEnum;
import org.wcs.mapper.intf.AppQuartzConfigService;
import org.wcs.model.po.app.AppQuartzConfig;
import org.wcs.plugin.quartz.QuartzComponent;
import org.wcs.utils.AppThreadUtils;

import java.util.List;

/**
 * 定时任务启动类
 */
@Slf4j
@Order(9)
@Component
@RequiredArgsConstructor
public class QuartzStarter implements ApplicationRunner {

    private final QuartzComponent quartzComponent;
    private final AppQuartzConfigService quartzConfigService;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        quartzComponent.scanQuartzJob();
        AppThreadUtils.startNewThread(() -> {
            while (true){
                List<AppQuartzConfig> quartzConfigs = quartzConfigService.queryAll();
                if(quartzConfigs == null) {
                    AppThreadUtils.sleep(3000);
                    continue;
                }
                quartzComponent.getQuartzJobBeans().forEach(quartzJobBean -> {
                    List<AppQuartzConfig> configs = quartzConfigs.stream().filter(appQuartzConfig -> appQuartzConfig.getClassName().equals(quartzJobBean.getJobName())).toList();
                    if(configs.isEmpty()) {
                        return;
                    }
                    AppQuartzConfig appQuartzConfig = configs.getFirst();
                    if(appQuartzConfig.getStatus() != TrueOrFalseEnum.TRUE.getCode()) {
                        return;
                    }
                    boolean createJobResult = quartzComponent.createQuartzJob(quartzJobBean, appQuartzConfig.getCron());
                    if(!createJobResult) {
                        log.error("定时任务创建失败;{}", quartzJobBean.getJobName());
                        return;
                    }
                    log.info("定时任务启动成功：{} 描述：{}", quartzJobBean.getJobName(), appQuartzConfig.getJobDesc());
                });
                return;
            }
        });
    }
}
