package cn.freemud.amp.config;

import com.freemud.application.sdk.api.config.TopicExchangeConfig;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class DlPaymentMqConfig {


    public static final String OPEN_STORE_PAYMENT_QUERY_DL_QUEUE = "open_store_payment_query_dl_queue";
    public static final String OPEN_STORE_PAYMENT_QUERY_DL_KEY = "open_store_payment_query_dl_key";

    public static final String OPEN_STORE_PAYMENT_QUERY_QUEUE = "open_store_payment_query_queue";
    public static final String OPEN_STORE_PAYMENT_QUERY_KEY = "open_store_payment_query_key";


    /**
     * 写入RabbitMQ使用的默认队列
     *
     * @return
     */
    @Bean("paymentQueueName")
    public Queue paymentChangeQueue() {
        return QueueBuilder.durable(OPEN_STORE_PAYMENT_QUERY_QUEUE).build();
    }

    /**
     * 绑定消息队列
     *
     * @param queue         消息队列
     * @param topicExchange RabbitMQ Fanout Exchange
     * @return 消息队列绑定
     */
    @Bean("bindingPaymentQueueChange")
    Binding bindingPaymentChange(@Qualifier("paymentQueueName") Queue queue, @Qualifier("orderPushTopicExchange") Exchange topicExchange) {
        return BindingBuilder.bind(queue).to(topicExchange).with(OPEN_STORE_PAYMENT_QUERY_KEY).noargs();
    }


    @Bean("paymentChangeDlQueue")
    public Queue paymentChangeDlQueue() {
        Map<String, Object> delayQueueParams = new HashMap<>(2);
        // DLX，dead letter发送到的exchange
        delayQueueParams.put("x-dead-letter-exchange", TopicExchangeConfig.EXCHANGE_NAME);
        // dead letter携带的routing key
        delayQueueParams.put("x-dead-letter-routing-key", OPEN_STORE_PAYMENT_QUERY_KEY);
        //时间
        //delayQueueParams.put("x-message-ttl", 20*1000);
        return QueueBuilder.durable(OPEN_STORE_PAYMENT_QUERY_DL_QUEUE).withArguments(delayQueueParams).build();
    }

    @Bean("bindingPaymentDlChange")
    Binding bindingPaymentDlChange(@Qualifier("paymentChangeDlQueue") Queue queue, @Qualifier("orderPushTopicExchange") Exchange topicExchange) {
        Map<String, Object> args = new HashMap<>(2);
        args.put("x-dead-letter-exchange", TopicExchangeConfig.EXCHANGE_NAME);
        args.put("x-dead-letter-routing-key", OPEN_STORE_PAYMENT_QUERY_KEY);
        return BindingBuilder.bind(queue).to(topicExchange).with(OPEN_STORE_PAYMENT_QUERY_DL_KEY).and(args);
    }


}
