
package com.tmerclub.cloud.group.listener;

import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.bo.OrderStatusBO;
import com.tmerclub.cloud.common.order.vo.ShopCartOrderMergerVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.group.bo.GroupOrderBO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;


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

    @DubboReference
    private OrderFeignClient orderFeignClient;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object mergerOrder) {
        orderFeignClient.submit((ShopCartOrderMergerVO) mergerOrder);
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        GroupOrderBO groupOrderBO = Json.parseObject((byte[]) msg.getPayload(), GroupOrderBO.class);
        Long orderId = groupOrderBO.getOrderId();
        ServerResponseEntity<List<OrderStatusBO>> ordersStatusResponse = orderFeignClient.getOrdersStatus(Collections.singletonList(orderId));
        if (!ordersStatusResponse.isSuccess()) {
            throw new LuckException(ordersStatusResponse.getMsg());
        }
        if (!ordersStatusResponse.isSuccess()) {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        List<OrderStatusBO> data = ordersStatusResponse.getData();
        // 如果订单状态没有，也就是没有创建成功订单，直接回滚
        if (data.get(0).getStatus() == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
