package xtools.boot.mq.rabbit.handle;

import jakarta.annotation.Resource;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import xtools.boot.mq.base.handle.BaseMqHandle;
import xtools.boot.mq.rabbit.params.RabbitMqParams;
import xtools.core.StringUtils;

/**
 * <p>Title : RabbitMqHandle</p>
 * <p>Description : RabbitMqHandle</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/2/4 14:14
 */
@Component
public class RabbitMqHandle implements BaseMqHandle {

    /**
     * 默认监听方法
     */
    private final static String DEFAULT_LISTENER_METHOD = "baseHandleMessage";

    @Resource
    private ConnectionFactory connectionFactory;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 初始化消息队列
     *
     * @param queueName 消息队列名称
     */
    @Override
    public void initQueue(String queueName) {
        Queue queue = new Queue(queueName, true);
        new RabbitAdmin(connectionFactory).declareQueue(queue);
    }

    /**
     * 添加消息队列监听
     *
     * @param queueName      消息队列
     * @param delegate       监听类
     * @param listenerMethod 监听方法
     * @param params         参数
     */
    @Override
    public void addListen(String queueName, Object delegate, String listenerMethod, Object params) {
        if (StringUtils.isBlank(listenerMethod)) {
            listenerMethod = DEFAULT_LISTENER_METHOD;
        }
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        // 设置参数
        if (params instanceof RabbitMqParams rabbitMqParams) {
            // 并发参数
            String concurrency = rabbitMqParams.getConcurrency();
            if (StringUtils.isNotBlank(concurrency)) {
                container.setConcurrency(concurrency);
            }
        }
        container.setMessageListener(new MessageListenerAdapter(delegate, listenerMethod));
        container.start();
    }

    /**
     * 推送消息
     *
     * @param routingKey 路由 key
     * @param data       消息数据
     */
    @Override
    public void push(String routingKey, Object data) {
        rabbitTemplate.convertAndSend(routingKey, data);
    }

}
