
package com.tmerclub.cloud.order.listener;

import com.tmerclub.cloud.api.seckill.feign.SeckillFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.bo.RedisSeckillOrderBO;
import com.tmerclub.cloud.common.order.vo.ShopCartOrderMergerVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.rocketmq.config.RocketMqConstant;
import com.tmerclub.cloud.order.service.OrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Objects;

/**
 * @author tmerclub
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.SECKILL_ORDER_TIME_OUT_CANCEL_TOPIC, consumerGroup = RocketMqConstant.SECKILL_ORDER_TIME_OUT_CANCEL_TOPIC)
public class SeckillOrderCreateConsumer implements RocketMQListener<RedisSeckillOrderBO> {
    private static final Logger LOG = LoggerFactory.getLogger(SeckillOrderCreateConsumer.class);
    @Autowired
    private OrderService orderService;
    @DubboReference
    private SeckillFeignClient seckillFeignClient;

    /**
     * 秒杀订单超时支付，创建订单
     */
    @Override
    public void onMessage(RedisSeckillOrderBO redisSeckillOrderBO) {
        LOG.info("秒杀订单超时支付，创建订单：{}", redisSeckillOrderBO);
        Long orderId = redisSeckillOrderBO.getOrderId();
        // 查询一下redis中是否有订单数据，没有直接return
        ServerResponseEntity<ShopCartOrderMergerVO> seckillOrderResp = seckillFeignClient.getSeckillOrderByRedis(redisSeckillOrderBO.getOrderId(), redisSeckillOrderBO.getUserId());
        if (!seckillOrderResp.isSuccess()) {
            throw new LuckException(seckillOrderResp.getMsg());
        }
        if(Objects.isNull(seckillOrderResp.getData())){
            return;
        }
        orderService.cancelOrderAndGetCancelOrderIds(seckillOrderResp.getData(), Collections.singletonList(orderId));
    }
}
