package org.jeecg.modules.redission;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.service.IAppOrderService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wangzhiqiang
 * @Date 2025/8/15
 * @Desc 延迟队列实现订单超时取消
 */
@Component
@Slf4j
public class RedissonDelayQueue {

    @Resource
    private RedissonConfig redissonConfig;

    @Resource
    private IAppOrderService appOrderService;

    private RDelayedQueue<String> delayQueue;
    private RBlockingQueue<String> blockingQueue;

    @PostConstruct
    public void init() {
        initDelayQueue();
        startDelayQueueConsumer();
    }

    private void initDelayQueue() {
        RedissonClient redissonClient = redissonConfig.redissonClient();

        blockingQueue = redissonClient.getBlockingQueue("OrderTimeOutTask");
        delayQueue = redissonClient.getDelayedQueue(blockingQueue);
    }

    private void startDelayQueueConsumer() {
        new Thread(() -> {
            while (true) {
                try {
                    String task = blockingQueue.take();
                    log.info("接收到延迟任务:{}", task);

                    //执行业务代码
                    String orderId = Arrays.stream(task.split("_")).collect(Collectors.toList()).get(1);
                    AppOrder appOrder = appOrderService.getById(orderId);
                    if(ObjectUtil.isNotEmpty(appOrder)){
                        if (appOrder.getOrderStatus() == 0){
                            log.info("修改订单：{},支付状态为已取消", orderId);
                            appOrder.setOrderStatus(4);
                            appOrderService.updateById(appOrder);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "OrderTimeOutTask-Consumer").start();
    }

    public void offerTask(String task, long seconds) {
        log.info("添加延迟任务:{} 延迟时间:{}s", task, seconds);
        delayQueue.offer(task, seconds, TimeUnit.SECONDS);
    }

}
