package com.greenorange.promotion.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.greenorange.promotion.constant.MqConstant;
import com.greenorange.promotion.constant.OrderStatusConstant;
import com.greenorange.promotion.model.entity.CourseOrder;
import com.greenorange.promotion.service.course.CourseOrderService;
import com.greenorange.promotion.utils.MultiDelayMessage;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Component
public class OrderStatusListener {


    @Resource
    private CourseOrderService courseOrderService;


    @Resource
    private RabbitTemplate rabbitTemplate;



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE, delayed = "true"),
            key = MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayMessage(MultiDelayMessage<Long> msg) {
        System.out.println("\n\n\n\n\nOrderStatusListener.listenerDelayMessage msg-------------------------------->：" + msg);
        // 1.获取消息中的订单id
        Long orderId = msg.getData();
        // 2.查询订单，判断状态是否为待支付
        CourseOrder courseOrder = courseOrderService.getById(orderId);
        // 订单不存在或者订单已经支付
        if (courseOrder == null || !courseOrder.getOrderStatus().equals(OrderStatusConstant.PENDING)) {
            return ;
        }
        // 3.订单未支付，判断是否还有剩余延时时间
        if (msg.hasNextDelay()) {
            // 有延迟时间，需要重发延迟消息，先获取延迟时间的int值
            // 发送延时消息
            Long delayValue = msg.removeNextDelay();
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE,
                MqConstant.DELAY_ORDER_ROUTING_KEY, msg, message -> {
                    // 添加延迟消息属性
                    message.getMessageProperties().setDelayLong(delayValue);
                    return message;
            });
            return ;
        }
        // 没有剩余延时时间，说明订单超时未支付，需取消订单
        LambdaUpdateWrapper<CourseOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(CourseOrder::getId, orderId)
                .set(CourseOrder::getOrderStatus, OrderStatusConstant.CLOSED);
        courseOrderService.update(lambdaUpdateWrapper);
    }


}
