package com.kxs.system.api.amqp.rabbit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kxs.common.mq.enums.MQSendTypeEnum;
import com.kxs.common.mq.model.AbstractMQ;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * mq 订单普通队列 配置
 *
 * @author 没秃顶的码农
 * @date 2024-04-25
 */
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
public class RabbitOrderQueueMQ extends AbstractMQ {


    /**
     * 订单交易队列
     */
    public static final String QUEUE_NAME = "QUEUE_ORDER_DIVISION";

    /**
     * 死信队列名称
     */
    public static final String DEAD_QUEUE_NAME = "DEAD_QUEUE_ORDER_DIVISION";

    /**
     * 内置msg 消息体定义
     **/
    private MsgEntity msgEntity;

    /**
     *  定义Msg消息载体
     **/
    @Data
    public static class MsgEntity {

        /**
         * 支付订单号
         **/
        private String orderId;

        /**
         * 用户 ID
         */
        private Integer userId;

        /**
         * 商品ID
         */
        private Integer goodsId;

        /**
         * 订单金额
         */
        private BigDecimal totalPrice;

    }

    @Override
    public String getQueueName() {

        return QUEUE_NAME;
    }

    @Override
    public String getDeadQueueName() {

        return DEAD_QUEUE_NAME;
    }

    @Override
    public MQSendTypeEnum getMqType() {

        return MQSendTypeEnum.QUEUE;
    }

    @Override
    public Message toMessage() {
        String message = JSONObject.toJSONString(msgEntity);
        // 构建消息体
        return MessageBuilder.withBody(message.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setMessageId(UUID.randomUUID().toString())
                .build();
    }

    /**
     * 构造发送消息
     */
    public static RabbitOrderQueueMQ build(MsgEntity message){

        return new RabbitOrderQueueMQ(message);
    }

    /**
     * 解析MQ消息， 一般用于接收MQ消息时
     */
    public static MsgEntity parse(String msg){
        return JSON.parseObject(msg, MsgEntity.class);
    }

}
