<?php
namespace app\cxinv\model;

class ProductStock extends Base
{
//设置字段信息
    protected $schema = [
        'id'  =>'bigint',//
        'product_id'  =>'bigint',//商品id
        'residue_stock'  =>'bigint',//剩余库存
        'pending_stock'  =>'bigint',//待出库存
        'total_stock'  =>'bigint',//总库存
        'create_time'  =>'datetime',//
        'update_time'  =>'datetime',//
       ];
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    public function Product(){
        return $this->belongsTo(FinancialProducts::class,'product_id','id')->bind(['goodName','skuCode']);
    }
    public static function AddStock($product_id,$num){
        $product=self::where("product_id",$product_id)->findOrEmpty();
        if(!$product->isEmpty()){
            $product->residue_stock=bcadd($product->residue_stock,$num,8);
            $product->total_stock=bcadd($product->total_stock,$num,8);
            $save=$product->save();
          if(!$save) throw new \Exception('库存添加失败');
        }else{
            $product_data=[
                'product_id'=>$product_id,
                'residue_stock'=>$num,
                'total_stock'=>$num,
            ];
           $creste= self::create($product_data);
           if($creste->isEmpty()) throw new \Exception('库存添加失败');
        }
        return true;
    }

    public static function OutStock($product_id,$num){
        $product=self::where("product_id",$product_id)->findOrEmpty();
        if(!$product->isEmpty()){
            if($product->residue_stock<$num) throw new \Exception('库存不足');
            $product->residue_stock=bcsub($product->residue_stock,$num,8);
            $product->pending_stock=bcadd($product->pending_stock,$num,8);
            $save=$product->save();
            if(!$save) throw new \Exception('库存修改失败');
        }else{
            throw new \Exception('库存不足');
        }
        return true;
    }
}