package com.kxs.gateway.api.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.*;
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.util.UUID;

/**
 * mq 接口数据同步
 *
 * @author 没秃顶的码农
 * @date 2024-04-25
 */
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
public class RabbitDtsMethodQueueMQ extends AbstractMQ {


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

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

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

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

        /**
         * 接口地址
         */
        private String url;

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

        /**
         * 请求参数
         */
        private String param;

    }

    @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 RabbitDtsMethodQueueMQ build(MsgEntity message){

        return new RabbitDtsMethodQueueMQ(message);
    }

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

}
