package com.neusoft.smart.pos.inventory.service;

import com.alibaba.fastjson.JSON;
import com.neusoft.smart.pos.dto.inventory.request.SellAndWarehouseOutRequest;
import com.neusoft.smart.pos.framework.utils.BeanUtil;
import com.neusoft.smart.pos.inventory.persistent.domain.InventoryGoodsInfo;
import com.neusoft.smart.pos.inventory.persistent.domain.InventoryGoodsLimit;
import com.neusoft.smart.pos.inventory.persistent.mapper.InventoryGoodsLimitMapper;
import lombok.Data;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 数量限卖
 */
@Service
public class WarehouseOutCountLimit implements WarehouseOutLimitInterface {
    
    @Resource
    private InventoryGoodsLimitMapper inventoryGoodsLimitMapper;
    
    @Override
    public Pair<Boolean, String> checkLimit(InventoryGoodsLimit limit, InventoryGoodsInfo inventoryGoodsInfo, SellAndWarehouseOutRequest.OrderItem orderItem) {
        CountLimitData countLimitData = BeanUtil.parse(limit.getLimitJson(), CountLimitData.class);
        if (countLimitData.getLeftCount() == 0) {
            return Pair.of(false, inventoryGoodsInfo.getName() + "限卖已售罄");
        }
        Integer sellCount = orderItem.getStorageNum().multiply(new BigDecimal(Math.pow(10, orderItem.getScale()))).intValue();
        if (sellCount > countLimitData.getLeftCount()) {
            return Pair.of(false, inventoryGoodsInfo.getName() + "限卖剩余数量不足");
        }
        countLimitData.setLeftCount(countLimitData.getLeftCount() - sellCount);
        limit.setLimitJson(JSON.toJSONString(countLimitData));
        inventoryGoodsLimitMapper.updateByPrimaryKey(limit);
        return Pair.of(true, "");
    }
    
    @Data
    public static class CountLimitData {
        
        private Integer limitCount;
        
        private Integer leftCount;
        
        private Integer status;
    }
}
