package com.buy507.mall.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.buy507.mall.dto.ReceivingQueueEnum;

/**
 * 自动确认收货消息队列配置
 */
@Configuration
public class RabbitMqReceivingConfig {

    /**
     * 自动确认收货消息实际消费队列所绑定的交换机
     */
    @Bean
    DirectExchange receivingDirect() {
        return (DirectExchange) ExchangeBuilder
                .directExchange(ReceivingQueueEnum.QUEUE_RECEIVING_CONFIRM.getExchange())
                .durable(true)
                .build();
    }

    /**
     * 自动确认收货延迟队列队列所绑定的交换机
     */
    @Bean
    DirectExchange receivingTtlDirect() {
        return (DirectExchange) ExchangeBuilder
                .directExchange(ReceivingQueueEnum.QUEUE_TTL_RECEIVING_CONFIRM.getExchange())
                .durable(true)
                .build();
    }

    /**
     * 自动确认收货实际消费队列
     */
    @Bean
    public Queue receivingQueue() {
        return new Queue(ReceivingQueueEnum.QUEUE_RECEIVING_CONFIRM.getName());
    }

    /**
     * 自动确认收货延迟队列（死信队列）
     */
    @Bean
    public Queue receivingTtlQueue() {
        return QueueBuilder
                .durable(ReceivingQueueEnum.QUEUE_TTL_RECEIVING_CONFIRM.getName())
                .withArgument("x-dead-letter-exchange", ReceivingQueueEnum.QUEUE_RECEIVING_CONFIRM.getExchange())//到期后转发的交换机
                .withArgument("x-dead-letter-routing-key", ReceivingQueueEnum.QUEUE_RECEIVING_CONFIRM.getRouteKey())//到期后转发的路由键
                .build();
    }

    /**
     * 将自动确认收货队列绑定到交换机
     */
    @Bean
    Binding receivingBinding(DirectExchange receivingDirect, Queue receivingQueue){
        return BindingBuilder
                .bind(receivingQueue)
                .to(receivingDirect)
                .with(ReceivingQueueEnum.QUEUE_RECEIVING_CONFIRM.getRouteKey());
    }

    /**
     * 将自动确认收货延迟队列绑定到交换机
     */
    @Bean
    Binding receivingTtlBinding(DirectExchange receivingTtlDirect, Queue receivingTtlQueue){
        return BindingBuilder
                .bind(receivingTtlQueue)
                .to(receivingTtlDirect)
                .with(ReceivingQueueEnum.QUEUE_TTL_RECEIVING_CONFIRM.getRouteKey());
    }

}
