<?php
declare (strict_types = 1);

namespace app\admin\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class GoodCombind extends Model
{
	protected $createTime="createtime";
	protected $updateTime="updatetime";
	protected $append=["usable_stock"];
	  // 定义全局的查询范围
    protected $globalScope = ['is_del'];
    
    
    public function scopeIsDel($query)
    {
        $query->where('is_del',0);
    }
    
    public function GoodZx(){
    	return $this->belongsTo(GoodZixun::class,"childCode","spuCode");
    }
    public function GoodBasic(){
    	return $this->belongsTo(GoodBasic::class,'childCode','spuCode');
    }
	public function getUsableStockAttr($v,$row){
		return (new GoodStock())->withJoin(['wsminfo'] , 'left')
		                 ->where(['spuCode'=>$row['childCode'] , 'wsm_type'=>[2 , 5]])
		                 ->sum('usable_stock');
	}

	public function  AddStock($spuCode='',$num="0"){
		$comblist = $this->where(['spuCode'=>$spuCode,'is_del'=>0])->select()->toArray();
		if(empty($comblist))throw new \Exception("未找到对应子商品信息");
		$GoodStock=new GoodStock();
		$returnBn=[];
		foreach ($comblist as $item){
			 $row =$GoodStock->withJoin(["wsminfo"],"left")
            ->field('id,usable_stock')
            ->where(['spuCode' => $item['childCode'], 'warehouse_info.wsm_type'=>[2,5]])
            ->findOrEmpty();
			 if($row->isEmpty()) throw new \Exception('未找到对应子商品信息');
			 $stocknum =bcmul($num,$item["child_num"]);
			 $up =GoodStockInfo::StockBnSub($row->id,intval($stocknum));
			 if(empty($up)) throw new \Exception('未找到对应子商品BN库存信息');
			$returnBn=array_merge($returnBn,$up);
		}
		
		return $returnBn;
	}
	/**
	* @param string $spuCode
	* @param string $bnCode
	* @param string $num
	* @param string $stockCode  库存变化申请编号
	* @param int $flag 0 解除库存 1 占用库存驳回
	 * @return bool
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	 */
	public function subStock($spuCode='',$bnCode='',$num='0',$stockCode=''){
		$comblist = $this->where(['spuCode'=>$spuCode,'is_del'=>0])->select()->toArray();
		if(empty($comblist))throw new \Exception('未找到对应子商品信息');
				$goodinfo = new Good();
				$combind = new CombindBninfo();
		foreach ($comblist as $item){
			 $stocknum =bcmul($num.'',$item['child_num']);
			 $good = $goodinfo->where(["spuCode"=>$item['childCode']])->findOrEmpty();
			 if($good->isEmpty()==false){
			 	$good->usable_stock = bcadd($good->usable_stock,$stocknum);
			 	$gdup=$good->save();
			 	if($gdup==false)throw new \Exception('子商品库存更新失败');
			 }
			$up=$combind->subBN($spuCode,$bnCode,$item['childCode'],$stocknum,$stockCode);
			if($up==false)throw new \Exception('子商品库存更新失败');
		}
		return true;
	}

	public function goodTax(){
		return $this->belongsTo(GoodTax::class,"childCode","spuCode")
		->bind(['short_name','merge_code',"tax","inv_good_name","tax_id","companyNo"]);
	}
}