package com.yunfeiyun.agmp.common.framework.config;

import com.yunfeiyun.agmp.common.config.SystemConfig;
import com.yunfeiyun.agmp.common.constant.AmqpConstant;
import com.yunfeiyun.agmp.common.framework.config.properties.RouterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.util.Properties;

@Order(0)
@Configuration
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "enabled", havingValue = "true")
public class TopicRabbitConfig {

    private static final Logger log = LoggerFactory.getLogger(TopicRabbitConfig.class);
    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private SystemConfig systemConfig;

    @Autowired
    private RouterProperties routerProperties;

    //PTS分发给第三方服务
    @PostConstruct
    public void start() {
        if(routerProperties.getQueue() != null){
            for (String queueName : routerProperties.getQueue().getProductRouter()) {
                createMQIfNotExist( queueName, AmqpConstant.FanoutExchangeName );
            }
        }else{
            log.error("您没有配置生产者队列");
        }

    }

    private void createMQIfNotExist(String queueName ,String exchangeName) {
        //判断队列是否存在
        Properties properties = rabbitAdmin.getQueueProperties(queueName);
        if(properties == null){
        }else{ log.info("业务方={} 交换器={}  队列={} 已经存在",systemConfig.getName(), exchangeName , queueName); }
        Queue queue = new Queue(queueName, true, false, false, null);
        log.info("业务方={} 新建交换器={}  队列={}  发布者队列创建成功",systemConfig.getName(),exchangeName , queueName);
        FanoutExchange fanoutExchange = new FanoutExchange(exchangeName);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareExchange(fanoutExchange);
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(fanoutExchange));

    }


}
