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 DlSendCouponMqConfig {


    public static final String EXCHANGE_NAME = "topic-Exchange";
    public static final String QUEUE_NAME = "send-coupon-order-queue";
    public static final String QUEUE_ROUTING_KEY = "send-coupon-order-queue-routing-key";

    public static final String QUERY_DL_QUEUE_NAME = "send-coupon-order-queue_dl_queue";
    public static final String QUERY_DL_ROUTING_KEY = "send-coupon-order-queue_dl_key";

    @Bean("dlSendCouponMqTopicExchange")
    public Exchange dlSendCouponMqTopicExchange() {
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }
    /**
     * 写入RabbitMQ使用的默认队列
     *
     * @return
     */
    @Bean("sendCouponQueueName")
    public Queue sendCouponChangeQueue() {
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    /**
     * 绑定消息队列
     *
     * @param queue         消息队列
     * @param topicExchange RabbitMQ Fanout Exchange
     * @return 消息队列绑定
     */
    @Bean("bindingSendCouponQueueChange")
    Binding bindingSendCouponChange(@Qualifier("sendCouponQueueName") Queue queue, @Qualifier("dlSendCouponMqTopicExchange") Exchange topicExchange) {
        return BindingBuilder.bind(queue).to(topicExchange).with(QUEUE_ROUTING_KEY).noargs();
    }


    @Bean("sendCouponChangeDlQueue")
    public Queue sendCouponChangeDlQueue() {
        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", QUEUE_ROUTING_KEY);
        return QueueBuilder.durable(QUERY_DL_QUEUE_NAME).withArguments(delayQueueParams).build();
    }

    @Bean("bindingSendCouponDlChange")
    Binding bindingSendCouponDlChange(@Qualifier("sendCouponChangeDlQueue") Queue queue, @Qualifier("dlSendCouponMqTopicExchange") 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", QUEUE_ROUTING_KEY);
        return BindingBuilder.bind(queue).to(topicExchange).with(QUERY_DL_ROUTING_KEY).and(args);
    }


}
