package com.iamberry.wechat.handles.mq;

import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.zk.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.lang.reflect.Method;

@Component
@EnableAsync
public class MQTimer {

	@Autowired
	private DataSourceTransactionManager transactionManager;

	private static final Logger LOGGER = LoggerFactory.getLogger(MQTimer.class);

	@Async
	@EventListener
	public void run(MQMessage mqMessage) {
		// 订阅
		try {
			LOGGER.info("收到订阅请求...");
			// 远程调用 Service
			Object object = SpringContextHolder.getBean(mqMessage.getServiceHandlerObjectName());
			if (object == null) {
				throw new RuntimeException(mqMessage.getServiceHandlerObjectName() + "{} 对象不存在，请设置");
			}
			Class classes = object.getClass();
			// 获取方法
			Method method = classes.getMethod(mqMessage.getServiceHandlerMethodName(), MQMessage.class);
			if (method == null) {
				throw new RuntimeException(mqMessage.getServiceHandlerMethodName() + "{} 方法不存在，请设置");
			} else {
				// 执行方法，对方法启动事务
				DefaultTransactionDefinition def = new DefaultTransactionDefinition();
				def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
				TransactionStatus status = transactionManager.getTransaction(def);
				try {
					//逻辑代码
					method.invoke(object, mqMessage);
					transactionManager.commit(status);
				} catch (Exception e) {
					transactionManager.rollback(status);
				}
			}
		} catch (Exception e) {
			LOGGER.error("{}", e.getMessage());
		}
	}

}
