<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\CombindBninfo;use app\admin\model\CombindStockInfo;use app\admin\model\GoodCombind;use app\admin\model\GoodStock;use app\admin\model\GoodStockInfo;use think\App;use think\facade\Db;use think\facade\Validate;

class CombindStock extends Base
{
	private  $combind ;
	private  $combindStock ;
	private  $combindStockInfo ;
	private  $combindBninfo;
	public function __construct(App $app) {
		parent::__construct($app);
		$this->combindStock =new \app\admin\model\CombindStock();
		$this->combindStockInfo =new \app\admin\model\CombindStockInfo();
		$this->combindBninfo =new \app\admin\model\CombindBninfo();
		$this->combind =new \app\admin\model\GoodCombind();
	}
 
	public function list(){
		$param=$this->request->only(['spuCode'=>'','wsm_code'=>'','good_name'=>'','cat_id'=>'','status'=>'','flag'=>'',
		"create_start"=>"2023-01-01 00:00:00","create_end"=>date("Y-m-d H:i:s")],'post','trim');
		$where=[["createtime","between",[$param['create_start'],$param['create_end']]]];
		$param['spuCode']?? $where[]=["spuCode","like","%{$param['spuCode']}%"];
		$param['wsm_code']?? $where[]=["wsm_code","like","%{$param['wsm_code']}%"];
		$param['good_name']?? $where[]=["good_name","like","%{$param['good_name']}%"];
		$param['cat_id']?? $where[]=["good_basic.cat_id","=",$param['cat_id']];
		$list = $this->combindStock->withJoin(["wsminfo","good"],"left")->order("id desc")->paginate
		(["page"=>$param['page'],"list_rows"=>$param['size']]);
		return app_show(0,"获取成功",["list"=>$list->items(),"count"=>$list->total()]);
		
	}
	/**@param spuCode 商品编号
	 **@param wsm_code 仓库编号
	 **@param stock_num  库存数量
	 **@param flag  0 减库存 1 加库存
	 * @return \think\response\Json|void
	 */
	public function create(){
		$param =$this->request->only(["spuCode"=>"","wsm_code"=>"","stock_num"=>"",'flag'=>''],"post","trim");
		$valid =Validate::rule([
			"spuCode|商品编号"=>"require",
			"wsm_code|仓库编号"=>"require",
			"stock_num|库存数量"=>"require|number|gt:0",
			"flag|库存变化标识"=>"require|number|in:0,1"]);
		if($valid->check($param)==false)return error_show(1004,$valid->getError());
		$goodbasic =Db::name("good")->where("spuCode",$param["spuCode"])->find();
		if($goodbasic==false) return error_show(1004,"未找到组合商品信息");
		if($goodbasic['is_combind']==0) return error_show(1004,'商品不是组合商品');
		if($param['flag']==0){//减库存 先判断库存是否足够
			if($goodbasic['usable_stock']<$param['stock_num'])return error_show(1004,"商品库存数不足");
			$stock = Db::name("good_stock")->where(["spuCode"=>$param['spuCode'],"wsm_code"=>$param["wsm_code"]])->value("usable_stock",0);
			if($stock< $param['stock_num'])return error_show(1004,'商品库存数不足');
		}
		
		$combindList = $this->combind->where([["spuCode"=>$param["spuCode"],"is_del"=>0]])->select()->toArray();
		if(empty($combindList)) return error_show(1004,"未找到组合商品的商品组合信息");
		$childarr= Db::name('good')->whereIn('spuCode',array_unique(array_column($combindList,'childCode')))->column("spuCode,usable_stock,is_combind","spuCode");
		
		$stockCode=makeNo("CB");
		$this->combindStock->startTrans();
		try{
			$data=[
				"stockCode"=>$stockCode,
				"spuCode"=>$param["spuCode"],
				"wsm_code"=>$param["wsm_code"],
				"good_name"=>$goodbasic['good_name'],
				"flag"=>$param["flag"],
				"stock_num"=>$param['stock_num'],
				"apply_name"=>$this->uname,
				"apply_id"=>$this->uid,
				"status"=>1
			];
			$up =$this->combindStock->save($data);
			if($up==false) throw new \Exception("创建失败");
			if($param["flag"]==0){
				$stockup = Db::name('good')->where('spuCode',$param['spuCode'])->dec('usable_stock',$param["stock_num"])
					->update();
				if($stockup==false) throw new \Exception('组合商品库存占用失败');
			}else{
				foreach ($combindList as $item){
					if(!isset($childarr[$item['childCode']])) throw new \Exception('未找到组合商品的子商品信息');
					$num = bcmul($item['child_num'],$param['stock_num'],2);
					if($childarr[$item['childCode']]['usable_stock']<$num)throw new \Exception($item['childCode'].'组合商品的子商品库存不足');
					
					$stockup = Db::name("good")->where("spuCode",$item["childCode"])->dec("usable_stock",intval($num))
					->update();
					if($stockup==false) throw new \Exception($item["childCode"].'组合商品的子商品信息库存占用失败');
				}
			}
			$this->combindStock->commit();
		}catch (\Exception $exception){
			$this->combindStock->rollback();
			return error_show(1004,$exception->getMessage());
		}
		return app_show(0,"数据创建成功",$stockCode);
	}
	
	
	public function info(){
		$param=$this->request->only(["id"=>""],"post","trim");
		$info =$this->combindStock->withJoin(["good","wsminfo"],"left")->with(['combindgood'])->findOrEmpty($param['id']);
		if($info->isEmpty())return error_show(1004,"未找到数据");
		if(!empty($info->combindgood)){
			foreach ($info->combindgood as &$item){
				$item['stock'] = bcmul($info->stock_num,$item['child_num']);
			}
		}
		return app_show(0,"获取成功",$info);
	}
	
	//status 1 待审核 2审核通过 3 审核驳回
	public  function status(){
		$param=$this->request->only(['id'=>'',"status"=>"","remark"=>""],'post','trim');
		$valid=Validate::rule(["id|主键ID"=>"require","status|状态"=>"require|number|in:2,3"]);
		if($valid->check($param)==false)return error_show(1004,$valid->getError());
		$row = $this->combindStock->findOrEmpty($param['id']);
		if($row->status!=1)return error_show(1004,"数据状态有误");
		$goodinfo = (new \app\admin\model\GoodBasic())->where(['spuCode'=>$row->spuCode])->findOrEmpty();
		if($goodinfo->isEmpty())return error_show(1004,'未找到对应得组合商品信息');
		
		$comblist = (new GoodCombind())->where(["spuCode"=>$row->spuCode,"is_del"=>0])->select()->toArray();
		if(empty($comblist)) return error_show(1004,'组合商品子商品信息未找到');
		
		$row->status = $param['status'];
		$row->remark = $param['remark'];
		$row->startTrans();
		try{
			$up =$row->save();
			if($up==false) throw new \Exception("数据状态更新失败");
			if($param['status']==2){
				$GoodStock =new GoodStock();
				$stock =$GoodStock->where(["spuCode"=>$row->spuCode,"wsm_code"=>$row->wsm_code])->findOrEmpty();
				if($row->flag==1){
					$bn = makeNo('BN');
					if($stock->isEmpty()){
						$wsm_stock = [
							"spuCode"=>$row->spuCode,
							"wsm_code"=>$row->wsm_code,
							"usable_stock"=>$row->stock_num,
							"total_stock"=>$row->stock_num,
							];
						$id =$stock->insertGetId($wsm_stock);
						if($id<=0) throw new \Exception('仓库库存数更新失败');
					}else{
						$wsm_stock=[
							'usable_stock'=>bcadd($stock->usable_stock,$row->stock_num),
							'total_stock'=>bcadd($stock->total_stock,$row->stock_num)
							];
						$up=$stock->save($wsm_stock);
						if($up==false) throw new \Exception("仓库库存数更新失败");
						$id = $stock->id;
					}
					$good= (new \app\admin\model\Good())->where(["spuCode"=>$row->spuCode])->findOrEmpty();
					if($good->isEmpty()==false){
						$good->usable_stock=bcadd($good->usable_stock,$row->stock_num);
						$upe=$good->save();
						if($upe==false)throw new \Exception('商品可用库存数更新失败');
					}
					
					$origin = Db::name('good_nake')->where([['spuCode', '=', $row->spuCode], ['min_num', '<=',
					$row->stock_num], ['is_del', '=', 0]])->order('min_num desc')->find();
		            if ($origin == false) {
		                throw new \Exception( '未找到相关阶梯成本价格');
		            }
		            $origin_price = $origin['nake_total'];
		            $stcoc=GoodStockInfo::AddBn($id,$bn,$row->stock_num,$origin_price);
		            if($stcoc==false)  throw new \Exception( '组合商品bn库存生成失败');
		            $stockCodeLog= (new CombindStockInfo())->save(["stockCode"=>$row->stockCode,"flag"=>1,
		            "stock_num"=>$row->stock_num,"bnCode"=>$bn,"origin_price"=>$origin_price]);
					if($stockCodeLog==false)throw new \Exception( '组合商品bn库存生成失败');
					$bnlist =$this->combind->AddStock($row->spuCode,$row->stock_num);
					(new CombindBninfo())->AaddBNLog($row->spuCode,$bn,$bnlist);
				}else{
					if($stock->usable_stock < $row->stock_num)  throw new \Exception('仓库可用库数不足');
					$up =GoodStockInfo::SaleBn($stock->id,intval($row->stock_num));
			        if(empty($up)) throw new \Exception('未找到对应子商品BN库存信息');
					foreach ($up as $item){
							$bnlist =$this->combind->subStock($row->spuCode,$item['bnCode'],$item['num']);
							if($bnlist==false)throw new \Exception('子商品BN库存信息更新失败');
					}
				}
			}
			if($param['status']==3){
				$good= (new \app\admin\model\Good())->where(['spuCode'=>$row->spuCode])->findOrEmpty();
					if($good->isEmpty()==false){
						if($row->flag==0){
							$good->usable_stock = bcadd($good->usable_stock ,$row->stock_num);
						$stockup = $good->save();
						if($stockup==false) throw new \Exception('组合商品库存解除驳回失败');
						}else{
							foreach ($comblist as $item){
								$num = bcmul($item['child_num'],$row->stock_num);
								$stockup = Db::name('good')->where('spuCode',$item['childCode'])->inc('usable_stock',intval
								($num))->update();
								if($stockup==false) throw new \Exception('组合商品的子商品信息库存占用驳回失败');
							}
						}
					}
			}
			$row->commit();
		}catch (\Exception $exception){
		 $row->rollback();
		 return error_show(1004,$exception->getMessage());
		}
		return app_show(0,"数据更新成功");
	}
}