package com.czg.config;

import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author GYJoker
 */
@Service
@Slf4j
public class RabbitPublisher {

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 订单取消消息
     * 目前 用来回滚库存
     * @param orderId 订单id
     */
    public void sendOrderCancelMsg(String orderId) {
        sendMsg(RabbitConstants.Queue.ORDER_CANCEL_QUEUE, orderId);
    }

    /**
     * 库存损耗消息
     * @param orderId 订单id
     */
    public void sendOrderStockMsg(String orderId) {
        sendMsg(RabbitConstants.Queue.ORDER_STOCK_QUEUE, orderId);
    }

    /**
     * 退款库存回滚消息(未校验商品退款是否退回库存)
     * @param refundMap Map <Long,BigDecimal> 商品Id,退单数量
     */
    public void sendOrderRefundMsg(String refundMap) {
        sendMsg(RabbitConstants.Queue.ORDER_REFUND_QUEUE, refundMap);
    }

    /**
     * 订单打印消息
     * @param orderId 订单id
     * @param printOrder 是否打印结算单
     */
    public void sendOrderPrintMsg(String orderId, boolean printOrder) {
        log.info("开始发送打印mq消息, orderId: {}, printOrder: {}", orderId, printOrder);
        //厨房票
        sendMsg(RabbitConstants.Queue.ORDER_MACHINE_PRINT_QUEUE, new JSONObject().fluentPut("orderId", orderId).fluentPut("printOrder", printOrder).toString());
        //前台票
        if (printOrder) {
            sendMsg(RabbitConstants.Queue.ORDER_PRINT_QUEUE, orderId);
        }
    }

    /**
     * 退款订单打印消息
     * @param orderId 订单id
     */
    public void sendOrderReturnPrintMsg(String orderId) {
        //厨房票
        sendMsg(RabbitConstants.Queue.ORDER_MACHINE_PRINT_QUEUE, new JSONObject().fluentPut("orderId", orderId).fluentPut("printOrder", true).toString());
    }

    /**
     * 交班小票打印消息
     *
     * @param handoverRecordId 交班记录id
     */
    public void sendHandoverPrintMsg(String handoverRecordId) {
        sendMsg(RabbitConstants.Queue.ORDER_HANDOVER_PRINT_QUEUE, handoverRecordId);
    }

    /**
     * 商品信息变动消息
     *
     * @param shopId 店铺id
     */
    public void sendProductInfoChangeMsg(String shopId) {
        sendMsg(RabbitConstants.Queue.PRODUCT_INFO_CHANGE_QUEUE, shopId);
    }

    /**
     * 排队叫号小票打印
     * @param id 叫号队列id
     */
    public void printCallNumTicket(Long id) {
        sendMsg(RabbitConstants.Queue.ORDER_HANDOVER_PRINT_QUEUE, id.toString());
    }


    private void sendMsg(String queue, String msg) {
        rabbitTemplate.convertAndSend(activeProfile + "-" + RabbitConstants.Exchange.CASH_EXCHANGE, activeProfile + "-" + queue, msg);
    }

}
