package com.duiba.tuia.youtui.web.service.impl;

import cn.com.duiba.stock.service.api.constant.ConsumeStockTypes;
import cn.com.duiba.stock.service.api.remoteservice.RemoteStockService;
import cn.com.duiba.wolf.dubbo.DubboResult;
import com.duiba.tuia.youtui.web.service.BaseService;
import com.duiba.tuia.youtui.web.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockServiceImpl extends BaseService implements StockService {

    @Autowired
    RemoteStockService remoteStockService;

    @Override
    public Long find(Long stockId) {
        if (null == stockId) return null;
        try {
            DubboResult<Long> stockResult = remoteStockService.find(stockId);

            // 2.查询库存失败， 降级走福袋
            if (!stockResult.isSuccess()) {
                logger.warn("[Stock-Center] remoteStockService.find return error, the stockId=[{}], and because of =[{}]",
                        stockId, stockResult.getMsg());
                return null;
            }

            return stockResult.getResult();
        } catch (Exception e) {
            logger.warn("remoteStockService.find happen error, the stockId=[{}], and because of =[{}]", stockId, e.getMessage());
            return null;
        }
    }

    @Override
    public boolean consumeStock(String orderId, Long stockId) {
        DubboResult<Boolean> consumeStockResult = remoteStockService.consumeStockOne(ConsumeStockTypes.ActivityOrder.getType(), orderId, stockId);
        if (!consumeStockResult.isSuccess()) {
            logger.warn("[STOCK] remoteStockService.consumeStockOne failed, the orderId=[{}], the stockId=[{}], and because of=[{}]", orderId, stockId, consumeStockResult.getMsg());
            return false;
        }
        return true;
    }

    @Override
    public boolean consumeStock (String orderId, Long stockId,int num) {
        DubboResult<Boolean> consumeStockResult = remoteStockService.consumeStockNum(ConsumeStockTypes.ActivityOrder.getType(), orderId, stockId, num);
        if (!consumeStockResult.isSuccess()) {
            logger.warn("[STOCK] remoteStockService.consumeStockNum failed, the orderId=[{}], the stockId=[{}], and because of=[{}]", orderId, stockId, consumeStockResult.getMsg());
            return false;
        }
        return true;
    }
}
