<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\ActionLog;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 app\admin\model\ProcessOrder;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'=>'','companyNo'=>'','companyName'=>'',
		"create_start"=>"2023-01-01 00:00:00","create_end"=>date("Y-m-d H:i:s"),"page"=>1,"size"=>15],'post','trim');
		$where=[["combind_stock.createtime","between",[$param['create_start']?:  '2023-01-01 00:00:00',$param['create_end']?: date("Y-m-d H:i:s")]]];
		$param['spuCode']==''?:$where[]=["combind_stock.spuCode","like","%{$param['spuCode']}%"];
		$param['wsm_code']==''?:  $where[]=["combind_stock.wsm_code","like","%{$param['wsm_code']}%"];
		$param['good_name']==''?: $where[]=["combind_stock.good_name","like","%{$param['good_name']}%"];
		$param['companyNo']==''?: $where[]=["good.companyNo","like","%{$param['companyNo']}%"];
		$param['companyName']==''?: $where[]=["good.companyName","like","%{$param['companyName']}%"];
		$param['cat_id']==''?:  $where[]=["good.cat_id","=",$param['cat_id']];
		$param['flag']==''?:  $where[]=["combind_stock.flag","=",$param['flag']];
		$param['status']==''?:  $where[]=["combind_stock.status","=",$param['status']];
		$list = $this->combindStock
		->alias("a")
		->withJoin(["wsminfo","good"],"left")
		->where($where)->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_basic")->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){//减库存 先判断库存是否足够
			$stock = (new GoodStock())->where(["spuCode"=>$param['spuCode'],"wsm_code"=>$param["wsm_code"]])
			->findOrEmpty();
			if($stock->isEmpty())return error_show(1004,'商品库存信息为找到');
			if($stock->usable_stock< $param['stock_num'])return error_show(1004,'商品库存数不足');
			$isT = (new \app\admin\model\Good())->where(['spuCode'=>$param['spuCode']])->findOrEmpty();
			if($isT->isEmpty()==false){
				if($isT->usable_stock<  $param['stock_num'])return error_show(1004,'商品库存数不足');
			}
		}
		$isTs = $this->combindStock->where(["spuCode"=>$param['spuCode'],"status"=>1])->findOrEmpty();
		if($isTs->isEmpty()==false) return error_show(1004,"组合商品库存变化存在未完成得流程{$isTs->stockCode}");
		$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"],
				"bnCode"=>$param['flag']==1?makeNo("BN"):"",
				"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){
				if($isT->isEmpty()==false){
					$stockup = Db::name('good')->where('spuCode',$param['spuCode'])->dec('usable_stock',intval($param['stock_num']))->update();
					if($stockup==false) throw new \Exception('组合商品库存占用失败');
				}
				$stock->usable_stock = bcsub($stock->usable_stock,$param['stock_num']);
				$stock->total_stock = bcsub($stock->total_stock ,$param['stock_num']);
				$reld=$stock->save();
				if($reld==false) throw new \Exception('组合商品库存占用失败');
			}else{
				$bnArr=[];
				foreach ($combindList as $item){
					$num = bcmul($item['child_num'],$param['stock_num'],2);
					if(isset($childarr[$item['childCode']])) {
						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'].'组合商品的子商品信息库存占用失败');
					}
					$bnlist= (new GoodStock())->stockSub($item['childCode'],$num);
					$bnArr=array_merge($bnArr,$bnlist);
				}
				if(empty($bnArr)) throw new \Exception('组合商品的子商品信息库存占用失败');
				(new CombindBninfo())->AaddBNLog($param['spuCode'],$data['bnCode'],$bnArr,$stockCode);
			}
			 $stn = ['order_code' => $stockCode, 'status' =>1, 'action_remark' => '', 'action_type' => 'add'];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn, $param["flag"]==0?'ZHJC':"ZHTJ", 1,$data);
                			$process=[
                            'order_type' => $param["flag"]==0?'ZHJC':"ZHTJ",
                            'order_code' => $stockCode,//出库单号
                            'order_id' => $this->combindStock->id ,
                            'order_status' => 1,
                            'before_status' =>1,
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
			$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,'组合商品子商品信息未找到');
		$good= (new \app\admin\model\Good())->where(['spuCode'=>$row->spuCode])->findOrEmpty();
		$GoodStock =new GoodStock();
		$stock =$GoodStock->where(['spuCode'=>$row->spuCode,'wsm_code'=>$row->wsm_code])->findOrEmpty();
		$row->status = $param['status'];
		$row->remark = $param['remark'];
		$row->startTrans();
		try{
			$up =$row->save();
			if($up==false) throw new \Exception("数据状态更新失败");
			if($param['status']==2){
				if($row->flag==1){
					$bn = $row->bnCode;
					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;
					}
					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(intval($id),$bn,intval($row->stock_num),floatval($origin_price) );
		            if($stcoc==false)  throw new \Exception( '组合商品bn库存生成失败');
		            $stockCodeLog= $this->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库存生成失败');
				}
				else{
					$up =GoodStockInfo::StockBnSub($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'],$row->stockCode);
						if($bnlist==false)throw new \Exception('子商品BN库存信息更新失败');
						$stockLog=$this->combindStockInfo->save(["stockCode"=>$row->stockCode,"flag"=>$row->flag,
						'stock_num'=>$item['num'],'bnCode'=>$item['bnCode'],'origin_price'=>$item['origin_price']]);
						if($stockLog==false)throw new \Exception( '组合商品bn库存修改失败');
					}
				}
			}
			if($param['status']==3){
						if($row->flag==0){
							if($good->isEmpty()==false){
								$good->usable_stock = bcadd($good->usable_stock ,$row->stock_num);
								$stockup = $good->save();
								if($stockup==false) throw new \Exception('组合商品库存解除驳回失败');
							}
							$stock->usable_stock = bcadd($stock->usable_stock,$row->stock_num);
							$stock->total_stock = bcadd($stock->total_stock ,$row->stock_num);
							$reld=$stock->save();
							if($reld==false) throw new \Exception('组合商品库存解除驳回失败');
						}else{
							$bnlist =$this->combindBninfo->stockSub($row->stockCode);
							if($bnlist==false)throw new \Exception('子商品BN库存信息更新失败');
						}
					}
				$stn = ['order_code' => $row->stockCode, 'status' =>1, 'action_remark' => '', 'action_type' => 'add'];
                ActionLog::logAdd(['id'=>$this->uid,'nickname'=>$this->uname], $stn,  $row->flag==0?'ZHJC':'ZHTJ',
                 $param['status'],$param);
                			$process=[
                            'order_type' => $row->flag==0?'ZHJC':'ZHTJ',
                            'order_code' =>$row->stockCode,//出库单号
                            'order_id' => $row->id ,
                            'order_status' => $param['status'],
                            'before_status' =>1,
                            'holder_id'=>0,
                        ];
			ProcessOrder::AddProcess(['id'=>$this->uid,'nickname'=>$this->uname],$process);
			$row->commit();
		}catch (\Exception $exception){
		 $row->rollback();
		 return error_show(1004,$exception->getMessage());
		}
		return app_show(0,"数据更新成功");
	}
}