package com.kxs.product.biz.mq;

import com.alibaba.fastjson.JSON;
import com.kxs.product.api.amqp.rabbit.RabbitShopTimeoutQueueMQ;
import com.kxs.product.api.model.KxsShopOrder;
import com.kxs.product.biz.constant.enums.KxsShopEnum;
import com.kxs.product.biz.service.KxsShopOrderService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * rabbit 队列侦听器 商品下单过期队列
 *
 * @author Pota1ovO
 * @date 2024-05-07
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class RabbitShopQueueListener {
	private final KxsShopOrderService kxsShopOrderService;

	/**
	 * 监听 商品下单过期 队列的处理器
	 *
	 * @param message 消息
	 */
	@RabbitListener(queues = RabbitShopTimeoutQueueMQ.QUEUE_NAME, ackMode = "MANUAL")
	@RabbitHandler
	public void onMessage(String msg, Message message, Channel channel){
		log.info("商品下单过期队列: " + RabbitShopTimeoutQueueMQ.parse(msg));
        try {
			RabbitShopTimeoutQueueMQ.MsgEntity parse = RabbitShopTimeoutQueueMQ.parse(msg);
			Integer id = parse.getId();
			//根据订单号查询该订单是否付款成功,如果仍未付款成功,关闭订单
			KxsShopOrder order = kxsShopOrderService.getById(id);
			if (order != null && order.getStatus().equals(KxsShopEnum.ORDER_NO_PAY.getType())){

				order.setStatus(KxsShopEnum.ORDER_CANCEL.getType());
				kxsShopOrderService.updateById(order);
			}
			channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
			log.error("商品下单过期队列消费失败:{}", JSON.toJSONString(msg), e);
			try {
				channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
			} catch (IOException ex) {
				log.error("商品下单过期进入死信队列失败" + ex.getMessage(), ex);
			}
        }
    }

	/**
	 * 监听死信 队列的处理器
	 *
	 * @param message 消息
	 */
	@RabbitListener(queues = RabbitShopTimeoutQueueMQ.DEAD_QUEUE_NAME)
	@RabbitHandler
	public void onDeadMessage(String msg, Message message, Channel channel){
		log.info("商品下单过期死信队列: " + RabbitShopTimeoutQueueMQ.parse(msg));
        try {
			RabbitShopTimeoutQueueMQ.MsgEntity parse = RabbitShopTimeoutQueueMQ.parse(msg);
        } catch (Exception e) {
			log.error(e.getMessage(), e);

        }
    }

//	/**
//	 * 监听死信 队列的处理器
//	 *
//	 * @param message 消息
//	 */
//	@RabbitListener(queues = RabbitGdActQueueMQ.QUEUE_NAME)
//	@RabbitHandler
//	public void onGdMessage(String msg, Message message, Channel channel){
//		log.info("广电报备队列Payload: " + RabbitGdActQueueMQ.parse(msg));
//        try {
//			RabbitGdActQueueMQ.MsgEntity parse = RabbitGdActQueueMQ.parse(msg);
//        } catch (Exception e) {
//			log.error(e.getMessage(), e);
//
//        }
//    }
}