package com.diagbot.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diagbot.entity.SysTaskCron;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.facade.BehospitalInfoFacade;
import com.diagbot.facade.SysTaskCronFacade;
import com.diagbot.util.StringUtil;
import com.diagbot.vo.TaskVO;
import lombok.extern.slf4j.Slf4j;
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 java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description:
 * @author: gaodm
 * @time: 2024/4/15 17:45
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Slf4j
public class TASK_CX implements SchedulingConfigurer {
    @Autowired
    private SysTaskCronFacade sysTaskCronFacade;

    private SysTaskCron task = new SysTaskCron();

    private String param = "";

    @Autowired
    private BehospitalInfoFacade behospitalInfoFacade;

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                //1.添加任务内容(Runnable)
                if (null != task
                        && task.getIsDeleted().equals(IsDeleteEnum.N.getKey())
                        && task.getIsUsed().equals(1)) {
                    log.info("执行动态定时任务: " + LocalDateTime.now().toLocalTime());
                    TaskVO taskVO = new TaskVO();
                    taskVO.setType(1); // 类型过滤(1：出院时间比当前时间早3天前的病历（例如：长兴病历）)
                    taskVO.setIndividuation(Arrays.asList(1)); //个性化需求【1：近3天不含当天的病历强制评分更新】
                    behospitalInfoFacade.execute(taskVO, param);

                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //2.1 从数据库获取执行周期
                task = sysTaskCronFacade.getOne(new QueryWrapper<SysTaskCron>()
                        .eq("cron_code", "TASK_CX"), false);
                String cron = "0/5 * * * * ?";
                //2.2 合法性校验.
                if (null != task && StringUtil.isNotBlank(task.getCron())) {
                    cron = task.getCron();
                    param = task.getParam();
                }
                CronTrigger trigger = new CronTrigger(cron);
                return trigger.nextExecutionTime(triggerContext);
            }
        });
    }
}
