<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\model\CompanyCgdLog;use app\admin\model\PurcheaseOrder;use app\admin\model\WarehouseInfo;use app\model\Headquarters;use think\App;use think\facade\Validate;use think\Request;

class CompanyCgd extends Base
{
    public $model=null;
	public function __construct(App $app) {
		parent::__construct($app);
		$this->model=new \app\admin\model\CompanyCgd();
	}
	
	/**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $param = $this->request->only(['companyNo'=>'','is_cgd'=>0,"page"=>1,"size"=>10],'post');
        $where=[];
        $param["companyNo"]==""?:$where[]=["companyNo","=",$param["companyNo"]];
        $param["is_cgd"]==""?:$where[]=["is_cgd","=",$param["is_cgd"]];
        $list = $this->model->where($where)->order('id','desc')->paginate(['page'=>$param['page'],'list_rows'=>$param['size']]);
       return app_show(0,'获取成功',['list'=>$list->items(),'count'=>$list->total()]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
       $param = $this->request->only(["companyNo"=>'',"is_cgd"=>0],"post");
       $valid=Validate::rule(["companyNo|业务公司"=>"require|max:255|unique:\app\admin\model\CompanyCgd"]);
       if($valid->check($param)==false)return error_show(1004,$valid->getError());
        $data=[
        	"companyNo"=>$param["companyNo"],
        	"companyName"=>Headquarters::where("code",$param['companyNo'])->value("name",''),
        	"is_cgd"=>$param["is_cgd"]??0,
        	"apply_id"=>$this->uid,
        	"apply_name"=>$this->uname
        	];
        \app\admin\model\CompanyCgd::create($data);
        return app_show(0,"创建成功");
    }
    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update()
    {
       $param = $this->request->only(['id'=>'','is_cgd'=>0],'post');
       $valid=Validate::rule(['id|数据主键'=>'require|number',"is_cgd|是否启用"=>"require|number|in:0,1"]);
       if($valid->check($param)==false)return error_show(1004,$valid->getError());
       $info = $this->model->findOrEmpty($param["id"]);
       if($info->isEmpty())return error_show(1004,"未找到数据");
       $info->is_cgd = $param['is_cgd'];
       $info->apply_id = $this->uid;
       $info->apply_name =  $this->uname;
       $info->save();
        return app_show(0,'修改成功');
    }
    
    public function loglist(){
    	$param = $this->request->only(['companyNo'=>'','code'=>'','good_code'=>'',"start"=>'',"end"=>"",'page'=>1,
    	'size'=>10],'post');
        $where=[["a.source","=",2]];
        $param['companyNo']==''?:$where[]=['b.companyNo','=',$param['companyNo']];
        $param['code']==''?:$where[]=['a.code','=',$param['code']];
        $param['good_code']==''?:$where[]=['b.spuCode','=',$param['good_code']];
       $param['start']==""||$param['end']==""?:$where[]=['a.createtime','between',[startTime($param['start']),endTime
        ($param['end'])]];
        $model =new \app\admin\model\DataChange();
        $list =$model->alias("a")
        ->leftJoin("purchease_order b","a.code=b.cgdNo")
        ->where($where)
        ->field("a.*,b.companyNo,b.companyName")
        ->json(["before","after"])
        ->order('id','desc')
        ->paginate(['page'=>$param['page'],'list_rows'=>$param['size']]);
       return app_show(0,'获取成功',['list'=>$list->items(),'count'=>$list->total()]);
    }

    public function LogCreate(){
    	$param = $this->request->only(['supplierNo'=>'','cgdNo'=>'','price'=>''],'post');
    	$valid=Validate::rule([
    		'cgdNo|采购单编号'=>'require|max:255',
    		'supplierNo|供应商编号'=>'require|max:255',
    		'price|采购价格'=>'require|float',
    		]);
       if($valid->check($param)==false)return error_show(1004,$valid->getError());
    	$info  = PurcheaseOrder::where("cgdNo",$param['cgdNo'])->findOrEmpty();
    	if($info->status>0)return error_show(1004,"采购单当前状态不可修改");
    	if($info->order_source!=2)return error_show(1004,"非咨询采购单不可修改");
    	$ist = $this->model->where([["companyNo","=",$info->companyNo],["is_cgd","=",1]])->findOrEmpty();
    	if($ist->isEmpty())return error_show(1004,'采购单业务公司无修改权限');
    	$before = [
    			'supplierNo'=>$info->supplierNo,
    			'supplier_name'=>$info->supplier_name,
    			'good_price'=>$info->good_price,
    			'total_fee'=>$info->origin_total,
    			"cgder_id"=>$info->cgder_id,
    			"cgder"=>$info->cgder,
    			'good_createrid'=>$info->good_createrid,
    			'good_creater'=>$info->good_creater,
    			];
    	$after = [
    			'supplierNo'=>$param['supplierNo'],
    			'supplier_name'=>Headquarters::where('code',$param['supplierNo'])->value('name',''),
    			'good_price'=>$param['price'],
    			'total_fee'=>bcmul($info->good_num,$param['price'],2),
    			'cgder_id'=>$this->uid,
    			'cgder'=>$this->uname,
    			'good_createrid'=>$this->uid,
    			'good_creater'=>$this->uname,
    			];
    	if($before['good_price']<=$after['good_price'])return error_show(1004,'修改成本必须小于当前成本');
    	$dataChange=new \app\admin\model\DataChange();
    	$this->model->startTrans();
    	try{
    		$before = json_encode($before,JSON_UNESCAPED_UNICODE);
		    $after = json_encode($after,JSON_UNESCAPED_UNICODE);
		    $data=[
		        'code'=>$param['cgdNo'],
		        'type'=>1,
		        'source'=>2,
		        'before'=>$before,
		        'after'=>$after,
		        'apply_id'=>$this->uid,
		        'apply_name'=>$this->uname,
		        'creater_id'=>$this->uid,
		        'creater'=>$this->uname,
		        'status'=>2,
		        ];
    		$save=$dataChange->save($data);
    		if($save){
    			$dataChange->cgdUpdate($data);
    		}
    		
    	}catch (\Exception $exception){
    	    $this->model->rollback();
    	    return error_show(1004,$exception->getMessage());
    	}
    	$this->model->commit();
        return app_show(0,"修改成功");
    }
}