package com.ruoyi.web.controller.task;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mall.service.IMallOrderOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 订单定时任务
 */
@Component
public class OrderOrderTask {

    //日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /** 订单自动发货 */
    private static final String TASK_ORDER_DELIVERY_TIMEOUT = "task-order-delivery-timeout";

    private static final String ORDER_CANCEL_LOCK = "ORDER_CANCEL_LOCK";

    @Resource
    private RedisCache redisCache;

    @Resource
    private IMallOrderOrderService orderOrderService;

    /**
     * 订单超时一天自动收货
     * 每日的0点0分执行该任务
     * cron = "0 0 0 * * ?"
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void orderTimeout(){
        logger.info("订单自动收货----->");
        // redis锁
        // if (redisCache.isExist(TASK_ORDER_DELIVERY_TIMEOUT)){
        //     logger.error("退回->"+TASK_ORDER_DELIVERY_TIMEOUT+":"+new Date());
        //     return;
        // }else {
        //     redisCache.setCacheObject(TASK_ORDER_DELIVERY_TIMEOUT,TASK_ORDER_DELIVERY_TIMEOUT);
            orderOrderService.orderTimeout(TASK_ORDER_DELIVERY_TIMEOUT);
        // }

    }

    /**
     * 订单超时未支付取消
     * 每分钟执行一次
     */
    @Scheduled(fixedDelay = 60000 )
    public void orderCancel(){
        Date nowDate = DateUtils.getNowDate();
        if(!redisCache.hasKey(ORDER_CANCEL_LOCK)){
            // 执行任务
            logger.info("定时任务: 订单超时未支付取消 任务开始执行 "+nowDate);
            orderOrderService.orderCancel(ORDER_CANCEL_LOCK);
        }else{
            logger.info("定时任务: 订单超时未支付取消 退回{"+ORDER_CANCEL_LOCK+":"+ nowDate+"}");
        }
    }

}
