package com.zjrs.ggfw.rlzysc.bpo.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjrs.ggfw.rlzysc.blo.DwzpBLO;
import com.zjrs.ggfw.rlzysc.entity.SpringScheduledCronMapper;
import com.zjrs.ggfw.rlzysc.po.SpringScheduledCronPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Configuration
public class ScheduledConfig implements SchedulingConfigurer {

    private static final Logger LOG = LoggerFactory.getLogger(ScheduledConfig.class);

    @Autowired
    private SpringScheduledCronMapper springScheduledCronMapper;

    @Autowired
    private ApplicationContext context;

    @Resource
    private DwzpBLO dwzpBLO;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        LOG.info("执行动态定时任务: " + LocalDateTime.now().toLocalTime());
        List<SpringScheduledCronPO> polist = springScheduledCronMapper.selectList(new QueryWrapper<SpringScheduledCronPO>());
        for (SpringScheduledCronPO springScheduledCron:polist){
            Class<?> clazz;
            Object task;
            try {
                clazz = Class.forName(springScheduledCron.getCronkey());
                task = context.getBean(clazz);
            }
            catch (ClassNotFoundException e) {
                LOG.error("spring_scheduled_cron表数据" + springScheduledCron.getCronkey() + "有误");
                throw new IllegalArgumentException("spring_scheduled_cron表数据" + springScheduledCron.getCronkey() + "有误", e);
            }
            catch (BeansException e) {
                LOG.error(springScheduledCron.getCronkey() + "未纳入到spring管理");
                throw new IllegalArgumentException(springScheduledCron.getCronkey() + "未纳入到spring管理", e);
            }
            Assert.isAssignable(ScheduledOfTask.class, task.getClass(), "定时任务类必须实现ScheduledOfTask接口");
            // 可以通过改变数据库数据进而实现动态改变执行周期
            taskRegistrar.addTriggerTask(((Runnable) task),
                    triggerContext -> {
                        String cronExpression = springScheduledCron.getCronexpression();
                        return new CronTrigger(cronExpression).nextExecutionTime(triggerContext);
                    }
            );
        }
    }
}

