package org.springblade.modules.api.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.constant.CommonConstant;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.api.service.ITradeService;
import org.springblade.modules.finance.entity.OrderGrant;
import org.springblade.modules.finance.service.IOrderGrantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

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

import static org.springblade.modules.api.task.ConsignSchedulingTask.isStartTask;

//@Component
public class PlatAuthSchedulingTask implements SchedulingConfigurer {

	private static final Logger log = LoggerFactory.getLogger(PlatAuthSchedulingTask.class);

	private static final String PATTERN_DATE = org.springblade.core.tool.utils.DateUtil.PATTERN_DATE;

	private static final String TASK_NAME = "【解冻特殊账号】";
	@Autowired
	private IOrderGrantService orderGrantService;

	@Autowired
	private ITradeService tradeService;

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		if(!isStartTask){
			return;
		}

		Runnable task = new Runnable() {
			@Override
			public void run() {
				log.info(TASK_NAME + "定时任务开始: " + LocalDateTime.now());
				log.info(TASK_NAME + "定时任务结束: " + LocalDateTime.now());
			}
		};

		Trigger trigger = new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				//任务触发，可修改任务的执行周期.
				//每一次任务触发，都会执行这里的方法一次，重新获取下一次的执行时间
				//cron = timerQueryMapper.getCronTime();
				//0/5 * * * * ?
				//0 0 1 * * ?
				int taskTime = Integer.parseInt(ParamCache.getValue(CommonConstant.TASK_GRANT_TIME));//分钟
				if(StringUtil.isEmpty(taskTime)){
					taskTime = 10;
				}
				log.info(TASK_NAME + "定时时间间隔: " + taskTime);
				String cron = "0 0/" + taskTime + " * * * ?";
				//String cron = "0 0/5 * * * ?";
				CronTrigger trigger = new CronTrigger(cron);
				return trigger.nextExecutionTime(triggerContext);
			}
		};
		taskRegistrar.addTriggerTask(task, trigger);
	}

	/**
	 * 平台授权解冻
	 */
	private void platFormUnfreeze(){

	}
}
