
package com.tmerclub.cloud.user.listener;

import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.user.bo.mongo.MongoUserBalanceLogBO;
import com.tmerclub.cloud.user.service.UserBalanceLogService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 确认收货事务监听
 *
 * @author tmerclub
 * @date 2021/1/7
 */
@Component
@RocketMQTransactionListener(rocketMQTemplateBeanName = "balancePayTemplate", maximumPoolSize = 20)
public class BalancePayTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private UserBalanceLogService userBalanceLogService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object userBalanceLog) {
        Long payId = Json.parseObject((byte[]) msg.getPayload(), Long.class);
        // 扣减余额，并将余额记录的支付状态变为已支付
        userBalanceLogService.updateToOrderPaySuccess(payId, (MongoUserBalanceLogBO) userBalanceLog);
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        Long payId = Json.parseObject((byte[]) msg.getPayload(), Long.class);
        // 查询支付状态
        MongoUserBalanceLogBO userBalanceLog = userBalanceLogService.getByPayId(payId);
        if (!Objects.equals(userBalanceLog.getIsPayed(), 0)) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
