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.springblade.modules.shopping.entity.Consign;
import org.springblade.modules.shopping.service.IConsignService;
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 GrantSchedulingTask implements SchedulingConfigurer {

	private static final Logger log = LoggerFactory.getLogger(GrantSchedulingTask.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;

	@Autowired
	private IConsignService consignService;

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

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

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

	private void alipayUnfreeze(){
		String ymd = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -1), PATTERN_DATE);
		List<OrderGrant> list = orderGrantService.list(Wrappers.<OrderGrant>lambdaQuery()
			.eq(OrderGrant::getStatus, 1)
			//.eq(OrderGrant::getDataDate, ymd)
			.gt(OrderGrant::getNowNum, 0)
			.last(" AND EXISTS (select 1 from t_consign f where f.consign_config_id = bat_no  AND f.end_time < NOW()) ")
		);
		log.info("已授权冻结的数据：" + list.size());
		if (list.size() > 0){
			tradeService.orderGrant(list);
		}

		/**
		 * 查询寄售数据中平台需要兜底的数据，
		 * 	1、目的把寄售状态改为待付款
		 * 	2、状态为1：寄售中
		 * 	3、剩余数量为 1
		 * 	4、寄售价台的寄售价相等的数据
		 */
		Consign platform = new Consign();
		platform.setConsignState(2);//待付款
		platform.setNowStock(0);//被平台抢
		consignService.update(platform, Wrappers.<Consign>lambdaQuery()
			.eq(Consign::getConsignState, 1) //寄售中才变动
			.eq(Consign::getConsignFor,2)
			.lt(Consign::getEndTime, new Date()));
	}
}
