package com.example.demo.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.example.demo.service.OrderService;

/**
 * 订单定时任务调度器
 * 处理订单超时自动取消等定时任务
 */
@Component
public class OrderScheduler {

    private static final Logger logger = LoggerFactory.getLogger(OrderScheduler.class);

    @Autowired
    private OrderService orderService;

    /**
     * 自动取消超时订单
     * 每5分钟执行一次，取消超过30分钟未支付的订单
     */
    @Scheduled(fixedRate = 300000) // 5分钟 = 300000毫秒
    public void autoCancelTimeoutOrders() {
        try {
            logger.debug("开始执行订单超时自动取消任务...");
            int cancelledCount = orderService.autoCancelTimeoutOrders();
            if (cancelledCount > 0) {
                logger.info("订单超时自动取消任务完成，取消了 {} 个订单", cancelledCount);
            }
        } catch (Exception e) {
            logger.error("订单超时自动取消任务执行异常", e);
        }
    }
}
