package com.ssj.service.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.sys.homework.domain.HomeworkPicture;
import com.ssj.framework.core.rabbitmq.TopicRabbitConfig;
import com.ssj.service.sys.homework.service.HomeworkPictureService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


@Component
public class TopicRabbitHomeWorkPictureConsumer {
	
	  private static Logger logger = LoggerFactory.getLogger(TopicRabbitHomeWorkPictureConsumer.class);

	@Autowired
	private HomeworkPictureService homeworkPictureService;

	@Autowired
	private PlatformTransactionManager transactionManager;

	  
	  @RabbitListener(queues = {TopicRabbitConfig.topic_homework_picture_discern})
	  @RabbitHandler
	  public void handleMessage(Message message){
	  	  try {
			  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			  ////新发起一个事务
			  def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
			  TransactionStatus status = transactionManager.getTransaction(def);
			  logger.info("作业修改队列开始消费...");
			  HomeworkPicture homeworkPicture = JSONObject.parseObject(message.getBody(), HomeworkPicture.class);
			  logger.error("开始消费推送信息队列数据："+JSONObject.toJSONString(homeworkPicture));
			  homeworkPictureService.delete(homeworkPicture);
			  transactionManager.commit(status);
			  homeworkPictureService.save(homeworkPicture);
			  transactionManager.commit(status);

		  } catch (Exception e){
	  	  	  logger.error("消费队列消费异常" + e);
		  }
	  }
}


