package com.qmth.themis.mq.listener;

import com.qmth.themis.business.util.JacksonUtil;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @Description: 事务消息实现
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/28
 */
@Service
@RocketMQTransactionListener
public class RocketConsumerTransaction implements RocketMQLocalTransactionListener {
    private final static Logger log = LoggerFactory.getLogger(RocketConsumerTransaction.class);

    /**
     * - 发送prepare消息成功此方法被回调，该方法用于执行本地事务
     * - @param message 回传的消息，利用transactionId即可获取到该消息的唯一Id
     * - @param arg 调用send方法时传递的参数，当send时候若有额外的参数可以传递到send方法中，这里能获取到
     * - @return 返回事务状态，COMMIT：提交 ROLLBACK：回滚 UNKNOW：回调
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(org.springframework.messaging.Message message, Object arg) {
//            try {
//                log.info("【本地业务执行完毕】 msg:{}, Object:{}", message, o);
//                localTrans.put(message.getHeaders().getId()+"", message.getPayload());
//                return RocketMQLocalTransactionState.COMMIT;
//            } catch (Exception e) {
//                e.printStackTrace();
//                log.error("【执行本地业务异常】 exception message:{}", e.getMessage());
//                return RocketMQLocalTransactionState.ROLLBACK;
//            }
        log.info("本地事务和消息发送:{},o:{}", JacksonUtil.parseJson(message), JacksonUtil.parseJson(arg));
        return RocketMQLocalTransactionState.UNKNOWN;
    }

    /**
     * - @param message 通过获取transactionId来判断这条消息的本地事务执行状态
     * - @return 返回事务状态，COMMIT：提交 ROLLBACK：回滚 UNKNOW：回调
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(org.springframework.messaging.Message message) {
//            log.info("【执行检查任务】");
//            return RocketMQLocalTransactionState.UNKNOWN;
        log.info("回查信息:{}", JacksonUtil.parseJson(message));
        return RocketMQLocalTransactionState.COMMIT;
    }
}
