package com.cku.oa.groomer.mq;

import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.cku.oa.groomer.service.GroomerWrittenExamInfoService;
import com.rabbitmq.client.Channel;

@Configuration
public class DelayedMessageConsumer {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GroomerWrittenExamInfoService groomerWrittenExamInfoService;
	@Autowired
	private  Queue delayedQueue;

	@Bean
	public SimpleMessageListenerContainer messageContainer(ConnectionFactory connectionFactory) {
		
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
		container.setQueues(delayedQueue);
		container.setExposeListenerChannel(true);
		container.setMaxConcurrentConsumers(1);
		container.setConcurrentConsumers(1);
		// 设置确认模式手工确认
		container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
		container.setMessageListener(new ChannelAwareMessageListener() {
			@Override
			public void onMessage(Message message, Channel channel) throws Exception {
				byte[] body = message.getBody();
				logger.debug("=============接收：" + LocalDateTime.now());
				String s = new String(body).replaceAll("\"", "");
				logger.debug("=============内容：" + s);

				// 不读取消息，消息队列中保留当前消息未被查看状态
				// channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
				// 确认消息成功消费，删除消息队列中的消息
				// channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
				boolean flag = groomerWrittenExamInfoService.close(s);
				if (flag) {
					// 确认消息成功消费，删除消息队列中的消息，他跟上面一样
					channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
				} else {
					// 不读取消息并且将当前消息抛弃掉，消息队列中删除当前消息
					channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
				}

			}
		});
		return container;
	}

}