
package com.tmerclub.cloud.order.listener;

import com.tmerclub.cloud.common.order.constant.ReturnProcessStatusEnum;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.order.constant.PlatformInterventionStatus;
import com.tmerclub.cloud.order.dto.multishop.OrderRefundDTO;
import com.tmerclub.cloud.order.service.OrderRefundService;
import com.tmerclub.cloud.order.vo.OrderRefundVO;
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 = "orderRefundTemplate", maximumPoolSize = 20)
public class OrderRefundTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderRefundService orderRefundService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        OrderRefundVO orderRefundVO = Json.parseObject((byte[]) msg.getPayload(), OrderRefundVO.class);

        OrderRefundDTO orderRefundParam = (OrderRefundDTO) arg;
        // 同意退款
        int updateStats = orderRefundService.agreeRefund(orderRefundVO, orderRefundParam);

        if (updateStats == 0) {
            // 如果啥都没有更新，就检查一下
            return checkLocalTransaction(msg);
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        OrderRefundVO orderRefundVO = Json.parseObject((byte[]) msg.getPayload(), OrderRefundVO.class);
        OrderRefundVO dbRefundStatus = orderRefundService.getByRefundId(orderRefundVO.getRefundId());
        if (Objects.equals(dbRefundStatus.getPlatformInterventionStatus(),-1) && !Objects.equals(dbRefundStatus.getReturnMoneySts(), ReturnProcessStatusEnum.PROCESSING.value())) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        if (!Objects.equals(dbRefundStatus.getPlatformInterventionStatus(),-1) && !Objects.equals(dbRefundStatus.getPlatformInterventionStatus(), PlatformInterventionStatus.AGREE.value())) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }


}
