package com.wzj.soopin.order.service.impl;

import com.wzj.soopin.order.service.OrderService;
import com.wzj.soopin.order.task.OrderCancelTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.DelayQueue;

/**
 * 订单延迟取消服务
 */
@Service
public class OrderDelayCancelService {
    private final DelayQueue<OrderCancelTask> delayQueue = new DelayQueue<>();
    @Autowired
    private OrderService orderService; // 订单服务，用于修改订单状态

    public OrderDelayCancelService() {
        // 启动一个守护线程处理延迟任务
        Thread daemonThread = new Thread(this::processDelayQueue);
        daemonThread.setDaemon(true);
        daemonThread.start();
    }

    // 添加订单到延迟队列
    public void addOrderToCancelQueue(String orderSn, long delayTime) {
        delayQueue.put(new OrderCancelTask(orderSn, delayTime));
    }

    // 处理延迟队列中的任务
    private void processDelayQueue() {
        while (true) {
            try {
                // 取出到期的任务
                OrderCancelTask task = delayQueue.take();
                // 执行订单取消逻辑
//                orderService.updateOrderStatus(task.getOrderSn(), "CANCELLED");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            } catch (Exception e) {
                // 记录异常，继续处理下一个任务
                e.printStackTrace();
            }
        }
    }
}
