package cn.ysk.cashier.utils;

import cn.ysk.cashier.cons.rabbit.RabbitConstants;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class RabbitMsgUtils implements RabbitTemplate.ConfirmCallback {
    private final RabbitTemplate rabbitTemplate;

    public RabbitMsgUtils(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info(" 回调id:{}", correlationData);
        if (ack) {
            log.info("消息成功消费");
        } else {
            log.info("消息消费失败:{}", cause);
        }
    }

    private  <T> void sendMsg(String exchange, String routingKey, T data, String note, boolean isJson) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        log.info("开始发送{}mq消息, msgId: {}, exchange: {}, routingKey: {}, data: {}", correlationId.getId(), note, exchange, routingKey, data);
        rabbitTemplate.convertAndSend(exchange, routingKey, isJson ? JSONObject.toJSONString(data) : data, correlationId);
    }

    public <T> void sendOrderCollectMsg(T data) {
        sendMsg(RabbitConstants.CART_ORDER_COLLECT_PUT, RabbitConstants.CART_ORDER_COLLECT_ROUTINGKEY_PUT, data, "订单信息收集", true);
    }

    public void printTicket(String orderId){
        sendMsg(RabbitConstants.PRINT_MECHINE_COLLECT_PUT, RabbitConstants.PRINT_MECHINE_COLLECT_ROUTINGKEY_PUT, orderId, "打印票", false);
    }

    public <T> void sendStockMsg(T mqData) {
        // 发送库存记录mq消息
        sendMsg(RabbitConstants.EXCHANGE_STOCK_RECORD, RabbitConstants.ROUTING_STOCK_RECORD_SALE, mqData, "库存记录", true);
    }
}
