package com.mortals.xhx.base.framework.config;


import com.mortals.xhx.base.framework.listener.RabbitLoggingErrorHandler;
import com.mortals.xhx.base.framework.listener.SimpleDynamicListener;
import com.mortals.xhx.base.system.message.MessageCallbackService;
import com.mortals.xhx.base.system.message.impl.MessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.AsyncRabbitTemplate;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
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.DirectMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Order(1)
@Slf4j
public class RabbitConfig {
    @Autowired
    private SimpleDynamicListener simpleDynamicListener;
    @Autowired
    private RabbitLoggingErrorHandler rabbitLoggingErrorHandler;
    @Autowired
    private MessageProducer messageProducer;
    @Autowired
    private MessageCallbackService messageCallbackService;

    //@Bean("simpleMessageListenerContainer")
    public SimpleMessageListenerContainer simpleMessageListenerContainer(CachingConnectionFactory cachingConnectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setConcurrentConsumers(10);
        container.setMaxConcurrentConsumers(100);
        container.setMessageListener(simpleDynamicListener);//配置队列监听器
        container.start();
        return container;
    }

    @Bean
    public DirectMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
        DirectMessageListenerContainer container = new DirectMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //后置处理器，接收到的消息都添加头信息
        container.setAfterReceivePostProcessors(message -> {
            message.getMessageProperties().setContentType("application/json");
            return message;
        });

        container.setDefaultRequeueRejected(false);

        //设置异常处理
        //container.setErrorHandler(rabbitLoggingErrorHandler);
        // 并发消费，不使用
        // container.setConsumersPerQueue(3);
        // container.setMaxConcurrentConsumers(10);
      //  container.setMessageListener(directDynamicListener);
        return container;
    }


    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

/*        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

            }
        });*/

/*        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(!ObjectUtils.isEmpty(correlationData)){
                    // 发送消息的时候发送的业务id
                    log.info("发送消息id:{},ack:{}",correlationData.getId(),ack);
                }
            }
        });*/

        rabbitTemplate.setReturnCallback(messageCallbackService);

/*        rabbitTemplate.setReturnCallback(messageCallbackService);

        rabbitTemplate.setConfirmCallback(messageCallbackService);*/
        return rabbitTemplate;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        return rabbitAdmin;
    }


    //@Bean(name = "consumerBatchContainerFactory")
    public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
        // 创建 SimpleRabbitListenerContainerFactory 对象
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        // 额外添加批量消费的属性
        factory.setBatchListener(true);
        factory.setBatchSize(20);
        factory.setReceiveTimeout(5 * 1000L);
        factory.setConsumerBatchEnabled(true);
        return factory;
    }

    //修改系列和与反序列化转换器
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    //@Bean
    public AsyncRabbitTemplate asyncRabbitTemplate(RabbitTemplate rabbitTemplate) {
        AsyncRabbitTemplate asyncRabbitTemplate = new AsyncRabbitTemplate(rabbitTemplate);
        asyncRabbitTemplate.setReceiveTimeout(10000);
        return asyncRabbitTemplate;
    }


}
