package com.diagbot.task;

import java.time.LocalDateTime;
import java.util.Date;

import com.diagbot.facade.data.ADoctorAdviceFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.entity.SysTaskCron;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.SysTaskCronFacade;
import com.diagbot.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Slf4j
public class DoctorAdviceTask implements SchedulingConfigurer{

	@Autowired
    private SysTaskCronFacade sysTaskCronFacade;

    private SysTaskCron task001 = new SysTaskCron();

    @Autowired
	private ADoctorAdviceFacade aDoctorAdviceFacade;
    
    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                //1.添加任务内容(Runnable)
                if (null != task001
                        && task001.getIsDeleted().equals(IsDeleteEnum.N.getKey())
                        && task001.getIsUsed().equals(1)) {
                    log.info("执行动态定时任务: " + LocalDateTime.now().toLocalTime());
                    aDoctorAdviceFacade.executeDoctorAdvice();
                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //2.1 从数据库获取执行周期
                task001 = sysTaskCronFacade.getOne(new QueryWrapper<SysTaskCron>()
                        .eq("cron_code", "TASK009"), false);
                String cron = "0 0/1 * * * ?";
                //2.2 合法性校验.
                if (null != task001 && StringUtil.isNotBlank(task001.getCron())) {
                    cron = task001.getCron();
                }
                CronTrigger trigger = new CronTrigger(cron);
                return trigger.nextExecutionTime(triggerContext);
            }
        });
    }
}
