package com.yonge.cooleshow.portal.component;

import com.yonge.cooleshow.mall.common.enums.OrderCacheEnum;
import com.yonge.cooleshow.mbg.model.OmsOrder;
import com.yonge.cooleshow.portal.service.OmsPortalOrderService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.payment.util.DistributedLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 取消订单消息的消费者
 * Created by macro on 2018/9/14.
 */
@Component
@RabbitListener(queues = "mall.order.cancel")
public class CancelOrderReceiver {
    private static Logger logger =LoggerFactory.getLogger(CancelOrderReceiver.class);
    @Autowired
    private OmsPortalOrderService portalOrderService;

    @Autowired
    private RedissonClient redissonClient;

    @RabbitHandler
    public void handle(Long orderId){
        try {
            OmsOrder omsOrder = portalOrderService.getOrderById(orderId);

            DistributedLock.of(redissonClient)
                           .runIfLockCanGet(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(omsOrder.getOrderSn())
                                   , () -> {
                               try {
                                   portalOrderService.cancelOrder(orderId, "超时取消", null);
                               }catch (Exception e) {
                                   logger.warn("超时队列 ： {}",e.fillInStackTrace());
                               }
                                   }, 60L, TimeUnit.SECONDS);

        } catch (BizException e) {
            e.printStackTrace();
            logger.warn(e.getLocalizedMessage());
        }
        logger.info("process orderId:{}", orderId);
    }
}
