<?php


namespace app\admin\controller;


use app\admin\model\ActionLog;
use app\admin\model\DataGroup as DataGroupModel;
use app\admin\model\ProcessOrder;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Validate;

//采购单相关功能
class Purch extends Base
{

    public $noble=[];
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->noble=\think\facade\Config::get("noble");
    }

    //采购单列表
    public function  list(){
        $page = isset($this->post['page']) && $this->post['page'] !=="" ? intval($this->post['page']):"1";
        $size = isset($this->post['size']) && $this->post['size'] !=="" ? intval($this->post['size']):"10";
        $where = [['po.is_del', "=", 0]];
        $bkcode = isset($this->post['bk_code']) && $this->post['bk_code']!="" ? trim($this->post['bk_code']):"";
        if($bkcode!=""){
            $where[]=['po.bkcode',"like", "%{$bkcode}%"];
        }
        $status = isset($this->post['status']) && $this->post['status']!=="" ? intval($this->post['status']):"";
        if($status!==""){
            // $where['status'] = $status;
            $where[]=['po.status',"=", $status];
        }
        $cgdNo = isset($this->post['cgdNo']) && $this->post['cgdNo']!="" ? trim($this->post['cgdNo']) :"";
        if($cgdNo!=""){
            //$where['cgdNo'] = Db::Raw("like '%{$cgdNo}%'");
            $where[]=['po.cgdNo',"like", "%{$cgdNo}%"];
        }

        $apply_name = isset($this->post['apply_name']) && $this->post['apply_name']!="" ? trim($this->post['apply_name']):"";
        if($apply_name!=""){
            // $where['cgder'] =Db::Raw("like '%{$apply_name}%'");
            $where[]=['po.cgder',"like", "%{$apply_name}%"];
        }
        $wsm_code = isset($this->post['wsm_code']) && $this->post['wsm_code']!="" ? trim($this->post['wsm_code']):"";
        if($wsm_code!=""){
            // $where['wsm_code'] = $wsm_code;
            $where[]=['po.wsm_code',"=", $wsm_code];
        }
        $wsm_in_code = isset($this->post['wsm_in_code']) && $this->post['wsm_in_code']!="" ? trim($this->post['wsm_in_code']):"";
        if($wsm_in_code!=""){
            $incode = Db::name("purchease_in")->where(["wsm_in_code"=>Db::raw(" like %{$wsm_in_code}%"),"is_del"=>0])->column("cgdNo");
            if(empty($incode)){
                return error_show(1004,"未找到有关入库单信息");
            }
            $where[]=['po.cgdNo',"in", $incode];
        }
        $good_name = isset($this->post['good_name']) && $this->post['good_name']!="" ? trim($this->post['good_name']):"";
        if($good_name!=""){
            //$where['good_name'] = Db::raw(" like %{$good_name}%");
            $where[]=['po.good_name',"like", "%{$good_name}%"];
        }
        $good_code = isset($this->post['good_code']) && $this->post['good_code']!="" ? trim($this->post['good_code']) :"";
        if($good_code!=""){
            // $where['good_code'] = Db::raw(" like %{$good_code}%");
            $where[]=['po.spuCode',"like", "%{$good_code}%"];
        }
        $supplierNo = isset($this->post['supplierNo']) && $this->post['supplierNo']!="" ? trim($this->post['supplierNo']) :"";
        if($supplierNo!=""){
            // $where['good_code'] = Db::raw(" like %{$good_code}%");
            $where[]=['po.supplierNo',"like", "%{$supplierNo}%"];
        }
        $wsm_supplierNo = isset($this->post['wsm_supplierNo']) && $this->post['wsm_supplierNo']!="" ? trim($this->post['wsm_supplierNo']) :"";
        if($wsm_supplierNo!=""){
            $supplier = Db::name("supplier")->where(["code"=>$wsm_supplierNo])->find();
            if(empty($supplier)){
                return error_show(1004,"未找到供应商信息");
            }
            $wsmcode = Db::name("warehouse_info")->where(["is_del"=>0,"supplierNo"=>$wsm_supplierNo])->column("wsm_code");
            $where[]=['po.wsm_code',"in", $wsmcode];
        }
        $start = isset($this->post['start']) && $this->post['start']!="" ?$this->post['start']:"";
        if($start!=""){
            // $where['addtime'] = Db::raw(" >= '{$start}'");
            $where[]=['po.addtime',">=", $start." 00:00:00"];
        }
        $end = isset($this->post['end']) && $this->post['end']!="" ?$this->post['end']:"";
        if($end!=""){
            $where[]=['po.addtime',"<=", $end." 23:59:59"];
        }
        $last_start = isset($this->post['last_start']) && $this->post['last_start']!="" ?$this->post['last_start']:"";
        if($last_start!=""){
            //$where['lasttime'] = Db::raw(" >= '{$last_start}'");
            $where[]=['po.lasttime',">=", $last_start." 00:00:00"];

        }
        $last_end = isset($this->post['last_end']) && $this->post['last_end']!="" ?$this->post['last_end']:"";
        if($last_end!=""){
            //$where['lasttime'] = Db::raw(" <= '{$last_end}'");
            $where[]=['po.lasttime',"<=", $last_end." 23:59:59"];
        }
        $orderCode = isset($this->post['orderCode']) && $this->post['orderCode']!="" ?$this->post['orderCode']:"";
        if($orderCode!=""){
            //$where['lasttime'] = Db::raw(" <= '{$last_end}'");
            $where[]=['on.orderCode',"like", '%'.$orderCode.'%'];
        }

        //筛选供应商名称
        $supplier_name = isset($this->post['supplier_name']) && $this->post['supplier_name'] != "" ? $this->post['supplier_name'] : "";
        if ($supplier_name != '') $where[] = ['po.supplier_name', 'like', '%' . $supplier_name . '%'];

        $relaComNo = isset($this->post['relaComNo']) && $this->post['relaComNo'] != "" ? trim($this->post['relaComNo']) : "";
        if ($relaComNo != "") $where[] = ['po.supplierNo|po.companyNo', '=', $relaComNo];

//		$whereor=[];
//        if(!empty($role['write'])){
////            $whereor[]=["po.cgder_id","in",$role['write']];
////            $whereor[]=["sip.personid","=",$this->uid];
//            $whereor[]=["sip.personid","in",$role['write']];//最后的筛选条件
////            $whereor[]=["po.cgder_id","=",$this->uid];
//        }
//		$role = $this->checkDataShare();
//        if (!empty($role[DataGroupModel::$type_全部])) $where[] = ["sip.personid", "in", $role[DataGroupModel::$type_全部]];

         $role = $this->checkDataShare();
        $hand = resign_hand_user($this->uid,0);
        if (!empty($role[DataGroupModel::$type_全部])) {
        	$arr= array_unique(array_merge($hand,$role[DataGroupModel::$type_全部]));
			$where[] = ['sip.personid', 'in',$arr];
        }


        $company_name = isset($this->post['company_name']) && $this->post['company_name'] !== "" ? trim($this->post['company_name']) : "";
        if ($company_name !== "") $where[] = ["po.cgder_id", 'in', get_company_item_user_by_name($company_name)];

//        if(!empty($role['platform']) ){
//            $where[]=["po.platform_id","in",$role['platform']];
//        }

        $count = Db::name("purchease_order")
            ->alias('po')
            ->leftJoin('order_num on', 'on.cgdNo=po.cgdNo')
            ->leftJoin("depart_user u", "u.uid=po.cgder_id AND u.is_del=0")
            ->leftJoin('supplier sip', 'sip.code=po.supplierNo')
            ->where($where)
            ->where(function ($query) use ($where) {
                $query->whereOr([['po.order_type', '<>', 1], ['po.order_source', '=', 0]]);
            })->count();
        $total = ceil($count/$size);
        $page = $page >= $total ? $total : $page;
        $list = Db::name("purchease_order")
            ->alias('po')
            ->leftJoin('order_num on','on.cgdNo=po.cgdNo')
            ->leftJoin("depart_user u", "u.uid=po.cgder_id AND u.is_del=0")
            ->leftJoin('supplier sip', 'sip.code=po.supplierNo')
            ->field('po.*,on.orderCode,u.itemid,sip.personid as supplier_cgderid,sip.person as supplier_cgder')
            ->where($where)
            ->where(function($query) use ($where){$query->whereOr([['po.order_type', '<>', 1],['po.order_source', '=', 0]]);})
            ->page($page,$size)
            ->order("po.addtime desc")
            ->select()
            ->toArray();

        $account = checkHasAccountBySupplierNos(array_column($list,'supplierNo'));
        $data=[];
        foreach ($list as $value){
            $value['wsm_name']="";
            if($value['wsm_code']!=""){
                $wsmcode = Db::name("warehouse_info")->alias("a")->leftJoin("supplier b","a.supplierNo=b.code")
                    ->where(["a.wsm_code"=>$value['wsm_code']])->field("a.name as wsm_name,b.name,b.code")->find();
                $value['wsm_name'] =isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
                $value['wsm_supplier'] =isset($wsmcode['name']) ? $wsmcode['name']:"";
                $value['wsm_supplierNo'] =isset($wsmcode['code']) ? $wsmcode['code']:"";
            }
//			$supplierCgder =Db::name("supplier")->where(["code"=>$value['supplierNo']])->findOrEmpty();
//            $value['supplier_cgderid'] = $supplierCgder['personid'] ??'';
//            $value['supplier_cgder'] = $supplierCgder['person'] ??'';
            if($value['order_type']==3){
                $goon = Db::name("good_zixun")->where(["spuCode"=>$value['spuCode'],"is_del"=>0])->find();
                $value["speclist"]=isset($goon['specinfo'])&&$goon['specinfo']!=""? json_decode($goon['specinfo'],true):"";
            }else {
                $goon =Db::name('good_basic')->where(['spuCode'=>$value['spuCode']])->find();
                $spec = Db::name("good_spec")->where(["spuCode"=>$goon['spuCode'],"is_del"=>0])->select()->toArray();
                $speclist=[];
                if(!empty($spec)){
                    foreach ($spec as $val){
                        $temp=[];
                        $temp['id']=$val['id'];
                        $temp['spuCode']=$val['spuCode'];
                        $temp['spec_id']=$val['spec_id'];
                        $temp['spec_value_id']=$val['spec_value_id'];
                        $sp = Db::name("specs")->where(["id"=>$val['spec_id']])->find();
                        $temp['spec_name']=isset($sp["spec_name"]) ? $sp["spec_name"]:"";
                        $spv = Db::name("spec_value")->where(["id"=>$val['spec_value_id']])->find();
                        $temp['spec_value']=isset($spv["spec_value"]) ? $spv["spec_value"]:"";
                        $speclist[]=$temp;
                    }
                }
                $value["speclist"]=empty($speclist)?[]:$speclist;
            }

            //采购单详情字段order_type 为1或者2时,取线上商品库 商品创建人   order_type 为3或者4时 取采购反馈的商品库 商品反馈人
//            $value['cgder_id'] = $goon['createrid'];
//            $value['cgder'] = $goon['creater'];

            $inorder= Db::name("purchease_in")->where(['cgdNo'=>$value['cgdNo'],"is_del"=>0])->select();
            $value['child']=empty($inorder)? [] : $inorder;
            $value['send_num'] -=$value['th_num'];
            $value['total_fee'] =round($value['total_fee']-$value['th_fee'],2);
            //补充orderCode
//            $value['orderCode']=isset($all_orderCodes[$value['cgdNo']])?$all_orderCodes[$value['cgdNo']]:'';
            $value['company_name'] = implode('/', array_column(GetPart($value['itemid']), 'name'));

            $value['has_account'] = (int)isset($account[$value['supplierNo']]);

            //是否具有编辑权限
            $value['is_allow_update'] = 0;
            if (in_array($this->roleid, [1, 33]) || in_array($value['cgder_id'], $role[DataGroupModel::$type_可编辑])) $value['is_allow_update'] = 1;

            $data[]=$value;
        }
        return app_show(0,"获取成功",["list"=>$data ,"count"=>$count]);
    }

    public function info(){
        $cgdNo = isset($this->post['cgdNo']) && $this->post['cgdNo']!="" ?trim($this->post['cgdNo']):"";
        if($cgdNo==""){
            return error_show(1004,"参数cgdNo 不能为空");
        }
        //采购单
        $data = Db::name("purchease_order")->where(["cgdNo"=>$cgdNo,"is_del"=>0])->find();
        if(empty($data)){
            return error_show(1004,"未找到数据");
        }
        //采购退货单
        $im = Db::name('purchease_back')->where(['cgdNo'=>$data['cgdNo'],'is_del'=>0])->select();
        $var=[];
        foreach ($im as $value){
            if($data['order_type']==3){
                $goo = Db::name("good_zixun")->where(["spuCode"=>$value['spuCode'],"is_del"=>0])->find();
            }else {
                $goo =Db::name('good_basic')->where(['spuCode'=>$value['spuCode']])->find();
            }
            if($goo==false) {
                return error_show(1002, "未找到商品数据");
            }
            $cat= isset($goo['cat_id']) && $goo['cat_id'] !=0 ? made($goo['cat_id']):[];
            $value['cant']=$cat;
            $var[]=$value;
        }
        //采购工差单
        $dom = Db::name("purchease_diff")->where(['cgdNo'=>$data['cgdNo'],'is_del'=>0])->find();
        if($data['order_type']==3){
            $goon = Db::name("good_zixun")->where(["spuCode"=>$data['spuCode'],"is_del"=>0])->find();
        }else {
            $goon =Db::name('good_basic')->where(['spuCode'=>$data['spuCode']])->find();
        }
        if(empty($goon)){
            return error_show(1002,"未找到商品数据");
        }else{
            $goon['exclusive']=isset($goon['is_exclusive'])?makeExcluse($goon['is_exclusive']):"";
            $unit =Db::name("unit")->where(["id"=>$goon['good_unit']])->find();
            $goon['unit'] = isset($unit['unit'])?$unit['unit']:'';
            $spec = Db::name("good_spec")->where(["spuCode"=>$goon['spuCode'],"is_del"=>0])->select()->toArray();
            $speclist=[];
            if(!empty($spec)){
                foreach ($spec as $value){
                    $temp=[];
                    $temp['id']=$value['id'];
                    $temp['spuCode']=$value['spuCode'];
                    $temp['spec_id']=$value['spec_id'];
                    $temp['spec_value_id']=$value['spec_value_id'];
                    $temp['is_del']=$value['is_del'];
                    $sp = Db::name("specs")->where(["id"=>$value['spec_id']])->find();
                    $temp['spec_name']=isset($sp["spec_name"]) ? $sp["spec_name"]:"";
                    $spv = Db::name("spec_value")->where(["id"=>$value['spec_value_id']])->find();
                    $temp['spec_value']=isset($spv["spec_value"]) ? $spv["spec_value"]:"";
                    $speclist[]=$temp;
                }
            }
            $goon["speclist"]=empty($speclist)?[]:$speclist;
            $proof =Db::name("good_proof")->where(["spuCode"=>$goon['spuCode'],"is_del"=>0])->order("updatetime desc")->field("id,proof_type,proof_url")->find();
            $goon['proof'] = isset($proof)&&$proof!=false? $proof:[];
            $goon['origin_place_cn']="";
            $goon['delivery_place_cn']="";
            if(isset($goon['delivery_place'])&&$goon['delivery_place']!==""){
                $place = ["provice_code"=>"","city_code"=>"","area_code"=>""];
                list($place['provice_code'],$place['city_code'],$place['area_code'])=explode(",",$goon['delivery_place']);
                $goon['delivery_place_cn']=GetAddr(json_encode($place));
            }
            if(isset($goon['delivery_place'])&&$goon['origin_place']!==""){
                $place = ["provice_code"=>"","city_code"=>"","area_code"=>""];
                list($place['provice_code'],$place['city_code'],$place['area_code'])=explode(",",$goon['origin_place']);
                $goon['origin_place_cn']=GetAddr(json_encode($place));
            }
            if($goon['brand_id']!=0){
                $brand=Db::name("brand")->where(["id"=>$goon['brand_id']])->find();
                $goon["brand_name"]=isset($brand['brand_name'])?$brand['brand_name']:"";
            }else{
                $goon["brand_name"]="";
                $goon["brand_id"]="";
            }

            $supplier = Db::name("supplier")->where(["code"=>$goon['supplierNo']])->find();
            $goon['supplier_cgderid'] = $supplier['personid'] ??'';
            $goon['supplier_cgder'] = $supplier['person'] ??'';
            $goon['supplierName'] = isset($supplier['name'])?$supplier['name']:"";
            $goon['noble_name']=isset($goon['noble_metal'])&&$goon['noble_metal']!=0?$this->noble[$goon['noble_metal']] :"";
            if(isset($goon['companyNo'])&&$goon['companyNo']!=""){
                $company = Db::name("business")->where(["companyNo"=>$goon['companyNo']])->find();
            }
            $goon['company'] = isset($company['company'])?$company['company']:"";
        }
        $int= isset($goon['cat_id']) && $goon['cat_id'] !=0 ? made($goon['cat_id']):[];
        $data['wsm_name']="";
        if($data['wsm_code']!=""){
            $wsmcode = Db::name("warehouse_info")->alias("a")->leftJoin("supplier b","a.supplierNo=b.code")
                ->leftJoin("warehouse_addr c","a.wsm_code=c.wsm_code and c.is_del=0")
                ->where(["a.wsm_code"=>$data['wsm_code']])->field("a.name as wsm_name,b.name,b.code,c.wsm_name as wsm_contactor,c.wsm_mobile,c.wsm_addr,c.addr_code")->find();
            $data['wsm_name'] =isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
            $data['wsm_supplier'] =isset($wsmcode['name']) ? $wsmcode['name']:"";
            $data['wsm_supplierNo'] =isset($wsmcode['code']) ? $wsmcode['code']:"";
            $data['wsm_contactor'] =isset($wsmcode['wsm_contactor']) ? $wsmcode['wsm_contactor']:"";
            $data['wsm_mobile'] =isset($wsmcode['wsm_mobile']) ? $wsmcode['wsm_mobile']:"";
            // $data['wsm_addr'] =isset($wsmcode['wsm_addr']) ? $wsmcode['wsm_addr']:"";
            $data['addr_code'] =isset($wsmcode['addr_code']) ? $wsmcode['addr_code']:"";
            $data['wsm_addr'] =isset($wsmcode['addr_code']) ? GetAddr($wsmcode['addr_code']):"";
            $data['wsm_addr'].=isset($wsmcode['wsm_addr']) ? $wsmcode['wsm_addr']:"";
            $inorder= Db::name("purchease_in")->where(['cgdNo'=>$data['cgdNo'],"is_del"=>0])->select();
            $data['child']=empty($inorder)? [] : $inorder;
        }

        $data['can'] = $int;
        $data['goodinfo'] = $goon;
        $data['purcheasediff'] = $dom;
        $data['send_num'] -=$data['th_num'];
        $data['total_fee'] =round($data['total_fee']-$data['th_fee'],2);
        if(isset($data['companyNo'])&&$data['companyNo']!=""){
            $company = Db::name("business")->where(["companyNo"=>$data['companyNo']])->find();
        }
        $data['company'] = isset($company['company'])?$company['company']:"";
        //$data['info'] = $var;
        $data['purcheaseback'] = $var;

        //补充orderCode
        $data['orderCode'] = Db::name('order_num')
            ->where('cgdNo', $data['cgdNo'])
            ->value('orderCode', '');

//        //补充收货地址
//        $addr = Db::name('order_addr')
//            ->field('id,addr,addr_code,contactor,mobile,receipt_quantity')
//            ->where(['orderCode' => $data['orderCode'], 'is_del' => 0])
//            ->select()
//            ->toArray();
//        if (!empty($addr)) {
//             foreach ($addr as &$vv){
//                $temp = explode(',', $vv['addr_code']);
//                $temp_ = GetAddr(json_encode(['provice_code' => isset($temp[0]) ? $temp[0] : '', 'city_code' => isset($temp[1]) ? $temp[1] : '', 'area_code' => isset($temp[2]) ? $temp[2] : '']));
//                $vv['addr_code'] = $temp_ . $vv['addr'];
//            }
//        }else
        $addr=[];
        $data['addr_info'] = $addr;

        //补充客户名称
        if (empty($data['orderCode'])) $data['customer'] = [];
        else {
            $data['customer'] = Db::name('sale')
                ->alias('s')
                ->field('c.companyNo,c.companyName')
                ->leftJoin('customer_info c', 'c.companyNo=s.customer_code AND c.is_del=0')
                ->where(['s.orderCode' => $data['orderCode']])
                ->find();
        }

        $data['has_account'] = (int)isset(checkHasAccountBySupplierNos([$data['supplierNo']])[$data['supplierNo']]);

        //补充商品创建人字段
        $data['good_createrid']=$goon['createrid']??'';
        $data['good_creater']=$goon['creater']??'';

        return app_show(0, "获取成功", $data);
    }

    public function edit(){
        $cgdNo = isset($this->post['cgdNo']) && $this->post['cgdNo']!="" ?trim($this->post['cgdNo']):"";
        if($cgdNo==""){
            return error_show(1004,"参数cgdNo 不能为空");
        }
        $data = Db::name("purchease_order")->where(["cgdNo"=>$cgdNo,"is_del"=>0])->find();
        if(empty($data)){
            return error_show(1004,"未找到数据");
        }
        $order = ["order_code"=>$cgdNo,"status"=> $data['status'] ,"action_remark"=>$this->post['remark'],"action_type"=>"edit"];
        $wsm_code = isset($this->post['wsm_code'])&&$this->post['wsm_code']!=""? trim($this->post['wsm_code']):"";
        if($wsm_code!=""){
            $ware = Db::name("warehouse_info")->where(["wsm_code"=>$wsm_code,"is_del"=>0])->find();
            if(empty($ware)){
                return error_show(1004,"未找到仓库信息");
            }
//            $good = Db::name("good_stock")->where(["wsm_code"=>$wsm_code,"good_type_code"=>$data['good_type_code'],"is_del"=>0])->find();
//            if(empty($good)){
//                return error_show(1004,"未找到仓库下商品信息");
//            }
            $data['wsm_code'] = $wsm_code;
        }

        $cgdid = isset($this->post['cgder_id'])&&$this->post['cgder_id']!=""?intval($this->post['cgder_id']):"";
        if($cgdid!=''){
            $cgduser = GetInfoById($this->post['token'],["id"=>$cgdid]);
            if((!empty($cgduser) && $cgduser['code']!=0) ||empty($cgduser) ){
                return error_show($cgduser['code'],$cgduser['message']);
            }
            $userinfo = $cgduser['data'];
            $data['cgder_id'] = $cgdid;
            $data['cgder'] = $userinfo['nickname'];
        }
        $good_num = isset($this->post['good_num'])&&$this->post['good_num']!=""?intval($this->post['good_num']):"";
        if($good_num!=""){
            $data['good_num'] = $good_num;
        }
        $good_price = isset($this->post['good_price'])&&$this->post['good_price']!=""?$this->post['good_price']:"";
        if($good_price!=""){
            $data['good_price'] = $good_price;
        }
//        $total_fee = isset($this->post['total_fee'])&&$this->post['total_fee']!=""?$this->post['total_fee']:"";
//        if($total_fee!=""){
//            $data['total_fee'] = $total_fee;
//        }
        $pakge_fee = isset($this->post['pakge_fee'])&&$this->post['pakge_fee']!=""?$this->post['pakge_fee']:"";
        if($pakge_fee!=""){
            $data['pakge_fee'] = $pakge_fee;
        }

        $cert_fee = isset($this->post['cert_fee'])&&$this->post['cert_fee']!=""?$this->post['cert_fee']:"";
        if($cert_fee!=""){
            $data['cert_fee'] = $cert_fee;
        }

        $open_fee = isset($this->post['open_fee'])&&$this->post['open_fee']!=""?$this->post['open_fee']:"";
        if($open_fee!=""){
            $data['open_fee'] = $open_fee;
        }
        $delivery_fee = isset($this->post['delivery_fee'])&&$this->post['delivery_fee']!=""?$this->post['delivery_fee']:"";
        if($delivery_fee!=""){
            $data['delivery_fee'] = $delivery_fee;
        }
        $mark_fee = isset($this->post['mark_fee'])&&$this->post['mark_fee']!=""?$this->post['mark_fee']:"";
        if($mark_fee!=""){
            $data['mark_fee'] = $mark_fee;
        }
        $teach_fee = isset($this->post['teach_fee'])&&$this->post['teach_fee']!=""?$this->post['teach_fee']:"";
        if($teach_fee!=""){
            $data['teach_fee'] = $teach_fee;
        }

        $nake_fee = isset($this->post['nake_fee'])&&$this->post['nake_fee']!=""?$this->post['nake_fee']:"";
        if($nake_fee!=""){
            $data['nake_fee'] = $nake_fee;
        }
        $weight = isset($this->post['weight'])&&$this->post['weight']!=""?$this->post['weight']:"";
        if($weight!=""){
            $data['weight'] = $weight;
        }
        $diff_weight = isset($this->post['diff_weight'])&&$this->post['diff_weight']!=""?$this->post['diff_weight']:"";
        if($diff_weight!=""){
            $data['diff_weight'] = $diff_weight;
        }
        $diff_fee = isset($this->post['diff_fee'])&&$this->post['diff_fee']!=""?$this->post['diff_fee']:"";
        if($diff_fee!=""){
            $data['diff_fee'] = $diff_fee;
        }
        $supplierNo = isset($this->post['supplierNo'])&&$this->post['supplierNo']!=""?trim($this->post['supplierNo'])
            :"";
        if($supplierNo!=""){
            $supplier =Db::name("supplier")->where(['code'=>$supplierNo])->find();
            if(empty($supplier)){
                return error_show(1004,"未找到供应商信息");
            }
            $data['supplierNo'] = $supplierNo;
            $data['supplier_name'] = $supplier['name'];
        }
        $remark = isset($this->post['remark'])&&$this->post['remark']!=""?trim($this->post['remark']):"";
        if($remark!=""){
            $data['remark'] = $remark;
        }
        $data['good_price'] = round(($data['pakge_fee']+$data['weight']*$data['gold_price']+$data['nake_fee']+$data['mark_fee']+$data['cert_fee']+$data['open_fee']/$data['good_num']+$data['teach_fee']*$data['weight']+$data['delivery_fee']),2);
        $data['total_fee'] = round($data['good_price']*$data['good_num'],2);
        $data['updatetime'] =date("Y-m-d H:i:s");
        $upd=Db::name("purchease_order")->save($data);
        if($upd){
//            ActionLog::logAdd($this->post['token'],$order,'cgd',$data['status'],$this->post);

            //修改状态,添加待办
            ActionLog::logAdd($this->post['token'], $order, "CGD", $data['status'], $this->post);

//            ProcessOrder::AddProcess($this->post['token'], [
//                "order_type" => 'CGD',
//                "order_code" => $cgdNo,//销售单code
//                "order_id" => $data['id'],
//                "order_status" => $data['status'],"before_status"=>1
//            ]);


            return app_show(0,"更新成功");
        }else{
            return error_show(1004,'更新失败');
        }
    }

    //修改采购单
    public function editNew()
    {

        $param = $this->request->only(['cgdNo', 'supplierNo', 'token', 'wsm_code' => ''], 'post', 'trim');

        $val = Validate::rule([
            'cgdNo|采购单号' => 'require',
            'supplierNo|供应商编号' => 'require',
            'token' => 'require',
        ]);

        if (!$val->check($param)) return error_show(1004, $val->getError());

        Db::startTrans();

        try {

            $rs = Db::name('purchease_order')
                ->alias('po')
                ->field('po.id,po.order_type,po.order_source,po.status,po.cgder_id,po.cgder,po.supplierNo,po.supplier_name,po.wsm_code,wi.name wsm_name')
                ->leftJoin('warehouse_info wi', 'wi.wsm_code=po.wsm_code AND wi.is_del=0')
                ->where([
                    'po.cgdNo' => $param['cgdNo'],
                    'po.is_del' => 0,
                    'po.status' => 0
                ])->find();

            if (empty($rs)) throw new Exception('采购单不存在或不允许修改');

            $update = ['updatetime' => date('Y-m-d H:i:s')];

            //order_type==1备库
            if ($rs['order_type'] == 1 && $rs['order_source']==0) {

                if (empty($param['wsm_code'])) throw new Exception('备库单请传入仓库编码');
                else {

                    $wsm_rs = Db::name('warehouse_info')
                        ->field('id,wsm_code,name wsm_name')
                        ->where([
                            'wsm_code' => $param['wsm_code'],
                            'is_del' => 0,
                        ])->find();

                    if (empty($wsm_rs)) throw new Exception('查不到该仓库的记录');
                    else $update['wsm_code'] = $wsm_rs['wsm_code'];
                }
            }

            //供应商信息
            $supplier_rs = Db::name('supplier')
                ->field('id,name supplierName,code supplierNo,person,personid')
                ->where(['is_del' => 0, 'code' => $param['supplierNo']])
                ->find();


            if (empty($supplier_rs)) throw new Exception('查不到该供应商的记录');
            else {
                $update['cgder_id'] = $supplier_rs['personid'];
                $update['cgder'] = $supplier_rs['person'];
                $update['supplierNo'] = $supplier_rs['supplierNo'];
                $update['supplier_name'] = $supplier_rs['supplierName'];
            }

            //是否修改内容确定
            if (isset($update['wsm_code'])) {
                if ($update['wsm_code'] == $rs['wsm_code'] && $update['supplierNo'] == $rs['supplierNo']) throw new Exception('没有修改的内容,不能提交');
            } elseif ($update['supplierNo'] == $rs['supplierNo']) throw new Exception('没有修改的内容,不能提交');

            if ($update['supplierNo'] == $rs['supplierNo'] && $param['wsm_code'] == $rs['wsm_code']) throw new Exception('没有修改的内容');


            //修改
            Db::name('purchease_order')
                ->where([
                    'id' => $rs['id'],
                    'is_del' => 0,
                    'status' => 0
                ])->update($update);

            $user = GetUserInfo($param['token']);
            $creater_id = isset($user['data']['id']) ? $user['data']['id'] : 0;
            $creater = isset($user['data']['nickname']) ? $user['data']['nickname'] : '';

            //添加修改记录
            Db::name('purchease_change_supplier_log')
                ->insert([
                    'cgdNo' => $param['cgdNo'],
                    'cgder_id_old' => $rs['cgder_id'],
                    'cgder_id' => $update['cgder_id'],
                    'cgder_old' => $rs['cgder'],
                    'cgder' => $update['cgder'],
                    'supplierNo_old' => $rs['supplierNo'],
                    'supplierNo' => $update['supplierNo'],
                    'supplier_name_old' => $rs['supplier_name'],
                    'supplier_name' => $update['supplier_name'],
                    'wsm_code_old' => $rs['wsm_code'],
                    'wsm_code' => isset($update['wsm_code']) ? $update['wsm_code'] : $rs['wsm_code'],
                    'wsm_name_old' => $rs['wsm_name'],
                    'wsm_name' => isset($wsm_rs['wsm_name']) ? $wsm_rs['wsm_name'] : $rs['wsm_name'],
                    'addtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s'),
                    'creater_id' => $creater_id,
                    'creater' => $creater,
                ]);

            //记录日志
            ActionLog::logAdd(['id' => $creater_id, 'nickname' => $creater], $rs, "CGD", $rs['status'], $param);

//            ProcessOrder::AddProcess($this->post['token'], [
//                "order_type" => 'CGD',
//                "order_code" => $param['cgdNo'],//销售单code
//                "order_id" => $rs['id'],
//                "order_status" => $rs['status']
//            ]);

            //维护台账
            Db::name('standing_book')
                ->where('cgdNo', $param['cgdNo'])
                ->update(['supplierNo' => $param['supplierNo'], 'updatetime' => date('Y-m-d H:i:s')]);

            Db::commit();

            return app_show(0, '修改成功');
        } catch (Exception $exception) {
            Db::rollback();
            return error_show(1005, $exception->getMessage());
        }

    }

    public function status()
    {
        $cgdNo = isset($this->post['cgdNo']) && $this->post['cgdNo'] != "" ? $this->post['cgdNo'] : [];

        if (empty($cgdNo)) {
            return error_show(1004, "参数cgdNo 不能为空");
        }
        $remark = isset($this->post['remark']) && $this->post['remark'] != "" ? trim($this->post['remark']) : "";
        $status = isset($this->post['status']) && $this->post['status'] !== "" ? intval($this->post['status']) : "";
        if ($status === "") {
            return error_show(1004, "参数status 不能为空");
        }

        Db::startTrans();
        try {

            if ($status == 0) {
                $data = Db::name("purchease_order")
                    ->field('id,cgdNo,spuCode')
                    ->whereIn('cgdNo', $cgdNo)
                    ->where(["is_del" => 0])
                    ->where('send_status', '>', 1)
                    ->find();
                if (!empty($data)) throw new Exception($data['cgdNo'] . "采购单发货中无法取消");

            }
//        if($data['send_status']>1 && $status==0){
//            return error_show(1004,"采购单发货中无法取消");
//        }
//        $order = ["order_code"=>$cgdNo,"status"=> $data['status'] ,"action_remark"=>$remark,"action_type"=>"status"];
//        $data['status'] = $status;
//        $data['remark'] = $remark;
//        $data['updatetime'] =date("Y-m-d H:i:s");

            //原始数据
            $info = Db::name("purchease_order")
                ->whereIn('cgdNo', $cgdNo)
                ->column('id,cgdNo,status,supplierNo,spuCode,order_type', 'cgdNo');

            $upd = Db::name("purchease_order")
                ->whereIn('cgdNo', $cgdNo)
                ->save([
                    'status' => $status,
                    'remark' => $remark,
                    'updatetime' => date("Y-m-d H:i:s"),
                ]);
            if ($upd) {

                $supplier_cgderid = Db::name('supplier')
                    ->where('is_del', 0)
                    ->whereIn('code', array_column($info, 'supplierNo'))
                    ->column('personid', 'code');
//            ->leftJoin('supplier sip', 'sip.code=po.supplierNo')
//                ->field('po.*,on.orderCode,u.itemid,sip.personid as supplier_cgderid,sip.person as supplier_cgder')

//            $user=GetUserInfo($this->post['token']);
                $uid = $this->uid;
                $uname = $this->uname;



                foreach ($cgdNo as $vlue) {
					$isreturn = cgd_sale_return($vlue);
			        if($isreturn){
			          throw new Exception("{$vlue}关联销售单存在退货单正在进行");
			        }
                    if($status == 1 && $uid != $supplier_cgderid[$info[$vlue]['supplierNo']]) throw new Exception('只能由供应商负责人来操作');//与供应商确认的这个操作,只能由供应商负责人来操作

                    if ($status == 1 || $status == 2) {
//                    $orderinfo = Db::name('sale')
//                    ->alias('a')
//                    ->field('a.id,a.orderCode,a.is_stock,a.order_type,a.cgderid')
//                    ->leftJoin('order_num b','b.orderCode=a.orderCode')
//                    ->where([
//                        'a.is_del'=>0,
//                        'b.cgdNo'=>$vlue,
//                    ])->findOrEmpty();
//                        $is_stock = Db::name('good_basic')
//                            ->where(['is_del' => 0, 'spuCode' => $info[$vlue]['spuCode']])
//                            ->value('is_stock');

//                        if ($is_stock == 1) {
//                            //库存品,推给31库管人员、41库管-张凯旋
//                            $uids = Db::name('user_role')
//                                ->where([
//                                    ['is_del', '=', 0],
//                                    ['roleid', 'in', [31, 41]],
//                                    ['status', '=', 1]
//                                ])->column('uid');
////                            if (!in_array($this->uid, $uids)) throw new Exception('库存品订单只能由库管人员操作');
//                            $process = ["order_code" => $vlue, "order_id" => isset($info[$vlue]['id']) ? $info[$vlue]['id'] : 0, "order_status" => $status, "order_type" => 'CGD', "before_status" => isset($info[$vlue]['status']) ? $info[$vlue]['status'] : 0, 'holder_id' => isset($supplier_cgderid[$info[$vlue]['supplierNo']]) ? $supplier_cgderid[$info[$vlue]['supplierNo']] : 0, 'handle_user_list' => implode(',', $uids)];
//                        } elseif ($is_stock == 0 || $info[$vlue]['order_type'] == 3) {
                            //非库存品和采返商品,推给供应商负责人
//                            if ($this->uid != $supplier_cgderid[$info[$vlue]['supplierNo']]) throw new Exception('非库存品和采返商品只能由供应商负责人操作');

                            $process = ["order_code" => $vlue, "order_id" => isset($info[$vlue]['id']) ? $info[$vlue]['id'] : 0, "order_status" => $status, "order_type" => 'CGD', "before_status" => isset($info[$vlue]['status']) ? $info[$vlue]['status'] : 0, 'holder_id' => isset($supplier_cgderid[$info[$vlue]['supplierNo']]) ? $supplier_cgderid[$info[$vlue]['supplierNo']] : 0, 'handle_user_list' => isset($supplier_cgderid[$info[$vlue]['supplierNo']]) ? $supplier_cgderid[$info[$vlue]['supplierNo']] : 0];
//                        }
                    } else $process = ["order_code" => $vlue, "order_id" => isset($info[$vlue]['id']) ? $info[$vlue]['id'] : 0, "order_status" => $status, "order_type" => 'CGD', "before_status" => isset($info[$vlue]['status']) ? $info[$vlue]['status'] : 0, 'holder_id' => isset($supplier_cgderid[$info[$vlue]['supplierNo']]) ? $supplier_cgderid[$info[$vlue]['supplierNo']] : 0];

                    ProcessOrder::AddProcess(['id' => $uid, 'nickname' => $uname], $process);
                    $order = ["order_code" => $vlue, "status" => '', "action_remark" => $remark, "action_type" => "status"];
                    ActionLog::logAdd(['id' => $uid, 'nickname' => $uname], $order, 'CGD', $status, $this->post);
                }
//                return app_show(0, "更新成功");
            } else throw new Exception('更新失败');
//                return error_show(1004, '更新失败');

            Db::commit();
            return app_show(0, "更新成功");
        } catch (Exception $exception) {
            Db::rollback();
            return error_show(1004, '更新失败,' . $exception->getMessage());
        }
    }

    //创建采购工差单
    public function diffcreat(){
        $token = isset($this->post['token']) && $this->post['token'] !=="" ?trim($this->post['token']):"";
        //$cgdNo=makeNo("CG");
        $cgdNo = $this->post['cgdNo'] && $this->post['cgdNo'] !=="" ? trim($this->post['cgdNo']) :"";
        if($cgdNo==""){
            return error_show(1002,"参数good_code不能为空");
        }
        $cg = Db::name('purchease_order')->where(['cgdNo'=>$cgdNo,'is_del'=>0])->find();
        if($cg==""){
            return error_show(1002,"未找到采购单数据");
        }
        if($cg['order_type']==3){
            $gd = Db::name("good_zixun")->where(["spuCode"=>$cg['spuCode']])->find();
        }else {
            $gd =Db::name('good_basic')->where(['spuCode'=>$cg['spuCode']])->find();
        }
        if($gd==""){
            return error_show(1002,"未找到商品数据");
        }
        $diff_weight = isset($this->post['diff_weight']) && $this->post['diff_weight'] !=="" ? floatval($this->post['diff_weight']) :"";
        if($diff_weight===""){
            return error_show(1002,"参数diff_weight不能为空");
        }
//        $apply_id =GetUserInfo($token);
//        if(empty($apply_id)||$apply_id['code']!=0){
//            return error_show(1002,"申请人数据不存在");
//        }
        $rid= $this->uid;
        $rname= $this->uname;
        $diff_price = round($diff_weight*$cg['gold_price']+$diff_weight*$cg['teach_fee'],2);

        //如果有未处理的工差单,不允许创建新的
        $wait_check = Db::name('purchease_diff')
            ->field('id')
            ->where(['apply_id'=>$rid,'status'=>1,'is_del'=>0,"cgdNo"=>$cgdNo])
            ->find();

        if(!empty($wait_check)) return error_show('1005','您还有未处理的工差单,请先处理');

        $data=[
            "cgdNo"=>$cgdNo,
            "good_code"=>$cg['spuCode'],
            "good_name"=>$cg['good_name'],
            "sale_price"=>$cg['good_price'],
            "good_weight"=>$cg['weight']*$cg['good_num'],
            "good_num"=>$cg['good_num'],
            "apply_id"=>$rid,
            "apply_name"=>$rname,
            "diff_weight"=>$diff_weight,
            "diff_price"=>$diff_price,
            "gold_price"=>$cg['good_price'],
            "status"=>1,
            "is_del"=>0,
            "addtime"=>date("Y-m-d H:i:s"),
            "updatetime"=>date("Y-m-d H:i:s")
        ];
        Db::startTrans();
        try{
            $item = Db::name("purchease_diff")->insert($data,true);
            if($item>0){

                $sto = ["order_code"=>$cgdNo,"status"=>1,"action_remark"=>'',"action_type"=>"create"];
                ActionLog::logAdd(['id'=>$rid,'nickname'=>$rname],$sto,"CGGCD",1,$data);
                $process=["order_code"=>$cgdNo,"order_id"=>$item,"order_status"=>1,"order_type"=>'CGGCD',"before_status"=>1,'holder_id'=>$rid];
                ProcessOrder::AddProcess(['id'=>$rid,'nickname'=>$rname],$process);

                $update_standing_book_data = [
                    'cgd_diff_id' => $item,//采购工差单id
                    'updatetime' => date("Y-m-d H:i:s")
                ];

                $orderCode = Db::name("order_num")->where([["cgdNo","=",$cg['cgdNo']],["status","=",1]])->find();
                if($orderCode!=false){
                    $order = Db::name("sale")->where("orderCode", '=', $orderCode['orderCode'])->find();
                    if($order==false){
                        Db::rollback();
                        return error_show(1002,"未找到确认单信息");
                    }

                    $data=[
                        "cgd_diffid"=>$item,
                        "orderCode"=>$orderCode['orderCode'],
                        "good_code"=>$cg['spuCode'],
                        "good_name"=>$cg['good_name'],
                        "diff_weight"=>$diff_weight,
                        "diff_price"=>round($diff_weight*$order['gold_price']+$diff_weight*$order['cost_price'],2),
                        "gold_price"=>$order['sale_price'],
                        "status"=>1,
                        "addtime"=>date("Y-m-d H:i:s"),
                        "updatetime"=>date("Y-m-d H:i:s")
                    ];
                    $cgd = Db::name('sale_diff')->insert($data,true);
                    if($cgd==0){
//                            $sto = ["order_code"=>$cg['bkcode'],"status"=>1,"action_remark"=>'',"action_type"=>"create"];
//                            ActionLog::logAdd($this->post['token'],$sto,"ZXGCD",1,$sto);
//                            $process=["order_code"=>$cg['bkcode'],"order_id"=>$cgd,"order_status"=>1,"order_type"=>'ZXGCD'];
//                            ProcessOrder::AddProcess($this->post['token'],$process);
//                            Db::commit();
//                            return error_show(0,"新建成功");
//                        }else{
                        Db::rollback();
                        return error_show(1002,"新建失败");

                    }
                    $sto = ["order_code"=>$orderCode['orderCode'],"status"=>1,"action_remark"=>'',"action_type"=>"create"];
                    ActionLog::logAdd($this->post['token'],$sto,"XSGCD",1,$data);
                    $process=["order_code"=>$orderCode['orderCode'],"order_id"=>$cgd,"order_status"=>1,"order_type"=>'XSGCD',"before_status"=>1,'holder_id'=>$order['apply_id']];
                    ProcessOrder::AddProcess($this->post['token'],$process);

                    $update_standing_book_data['sale_diff_id']=$cgd;//工差单id

                }

                //维护台账记录
                Db::name('standing_book')
                    ->where('cgdNo', $cgdNo)
                    ->update($update_standing_book_data);

                Db::commit();
                return error_show(0,"新建成功");
            }else{
                Db::rollback();
                return error_show(1002,"新建失败");
            }
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1002,$e->getMessage());
        }
    }
    public function difflist(){
        $page = isset($this->post['page']) && $this->post['page'] !==""? intval($this->post['page']):"1";
        $size = isset($this->post['size']) && $this->post['size'] !==""? intval($this->post['size']):"10";
        $where = [['a.is_del',"=",0]];
        $cgdNo = isset($this->post['cgdNo']) && $this->post['cgdNo']!="" ? trim($this->post['cgdNo']):"";
        if($cgdNo!=""){
            $where[]=['a.cgdNo',"like", "%$cgdNo%"];
        }
        $status = isset($this->post['status']) && $this->post['status'] !==""? intval($this->post['status']):"";
        if($status!==""){
            $where[]=['a.status',"=",$status];
        }
        $start= isset($this->post['start']) && $this->post['start'] !== "" ? $this->post['start']:"";
        if ($start !="") {
            $where[]= ["a.addtime",'>=',$start];
        }
        $end = isset($this->post['end']) && $this->post['end'] !== "" ? $this->post['end'] :"";
        if($end !=""){
            $where[]= ["a.addtime",'<=',$end];
        }
        $apply_name = isset($this->post['apply_name']) && $this->post['apply_name'] !==""? intval($this->post['apply_name']):"";
        if($apply_name!==""){
            $where[]=['a.apply_name',"like","%$apply_name%"];
        }
        $company_name = isset($this->post['company_name']) && $this->post['company_name'] !== "" ? trim($this->post['company_name']) : "";
        if ($company_name !== "") $where[] = ["a.apply_id", 'in', get_company_item_user_by_name($company_name)];

//        $role = $this->checkDataShare();
//        if (!empty($role[DataGroupModel::$type_全部])) $where[] = ['a.apply_id', 'in', $role[DataGroupModel::$type_全部]];
         $role = $this->checkDataShare();
        $hand = resign_hand_user($this->uid,0);
        if (!empty($role[DataGroupModel::$type_全部])) {
        	$arr= array_unique(array_merge($hand,$role[DataGroupModel::$type_全部]));
			$where[] = ['a.apply_id', 'in',$arr];
        }

        $count = Db::name('purchease_diff')
            ->alias('a')
            ->join("good b","b.spuCode=a.good_code","left")
            ->where($where)
            ->count();
        $total = ceil($count/$size);
        $page = $page >= $total ? $total : $page;
        $list = Db::name('purchease_diff')
            ->alias('a')
            ->join("good b","b.spuCode=a.good_code","left")
            ->leftJoin("depart_user u", "u.uid=a.apply_id AND u.is_del=0")
            ->where($where)
            ->page($page,$size)
            ->order("a.addtime desc")
            ->field("a.*,b.cat_id,u.itemid")
            ->cursor();
        $data=[];
        foreach ($list as $value){
            $value['can']= isset($value['cat_id']) && $value['cat_id'] !=0 ? made($value['cat_id']):[];
            $value['company_name'] = implode('/', array_column(GetPart($value['itemid']), 'name'));

            //是否具有编辑权限
            $value['is_allow_update'] = 0;
            if (in_array($this->roleid, [1, 33]) || in_array($value['apply_id'], $role[DataGroupModel::$type_可编辑])) $value['is_allow_update'] = 1;

            $data[]=$value;
        }
        return app_show(0,"获取成功",['list'=>$data,'count'=>$count]);
    }
    public function diffinfo(){
        $id = isset($this->post['id']) && $this->post['id'] !=="" ? trim($this->post['id']) :"";
        if($id==""){
            return error_show(1002,"参数id 不能为空");
        }
        $idinf = Db::name('purchease_diff')->where(['id'=>$id,'is_del'=>0])->find();
        if($idinf==false){
            return error_show(1002,"未找到采购工差单数据");
        }
        $dn = Db::name('purchease_order')->where(['cgdNo'=>$idinf['cgdNo'],'is_del'=>0])->find();

        if($dn['order_type']==3){
            $goon = Db::name("good_zixun")->where(["spuCode"=>$dn['spuCode'],"is_del"=>0])->find();
        }else {
            $goon =Db::name('good_basic')->where(['spuCode'=>$dn['spuCode']])->find();
        }
//        $goon = Db::name('good')->where(['spuCode'=>$idinf['good_code']])->find();
        if(empty($goon)){
            return error_show(1002,"未找到商品数据");
        }
        $idinf['wsm_name'] ="";
        $idinf['wsm_supplier'] ="";
        $idinf['wsm_supplierNo'] ="";
        $idinf['wsm_contactor'] ="";
        $idinf['wsm_mobile'] ="";
        $idinf['addr_code'] ="";
        $idinf['wsm_addr'] ="";
        if($dn['wsm_code']!=""){
            $wsmcode = Db::name("warehouse_info")->alias("a")->leftJoin("supplier b","a.supplierNo=b.code")
                ->leftJoin("warehouse_addr c","a.wsm_code=c.wsm_code and c.is_del=0")
                ->where(["a.wsm_code"=>$dn['wsm_code']])->field("a.name as wsm_name,b.name,b.code,c.wsm_name as wsm_contactor,c.wsm_mobile,c.wsm_addr,c.addr_code")->find();
            $idinf['wsm_name'] =isset($wsmcode['wsm_name']) ? $wsmcode['wsm_name']:"";
            $idinf['wsm_supplier'] =isset($wsmcode['name']) ? $wsmcode['name']:"";
            $idinf['wsm_supplierNo'] =isset($wsmcode['code']) ? $wsmcode['code']:"";
            $idinf['wsm_contactor'] =isset($wsmcode['wsm_contactor']) ? $wsmcode['wsm_contactor']:"";
            $idinf['wsm_mobile'] =isset($wsmcode['wsm_mobile']) ? $wsmcode['wsm_mobile']:"";
            $idinf['addr_code'] =isset($wsmcode['addr_code']) ? $wsmcode['addr_code']:"";
            $idinf['addr_cn'] =isset($wsmcode['addr_code']) ? GetAddr($wsmcode['addr_code']):"";
            $idinf['wsm_addr']=isset($wsmcode['wsm_addr']) ? $wsmcode['wsm_addr']:"";
        }
        $idinf['info'] =$dn;
        $int= isset($goon['cat_id']) && $goon['cat_id'] !=0 ? made($goon['cat_id']):[];
        $idinf['can']=$int;
        $idinf['order_type']=$dn['order_type'];
        $idinf['order_source']=$dn['order_source'];

        //取出销售的工差单信息
        $diff = Db::name('sale_diff')->field('id,customer_remark,is_act,remark')->where('cgd_diffid',$id)->find();

        $idinf['diff_customer_remark']=$diff['customer_remark'];
        $idinf['diff_is_act']=$diff['is_act'];
        $idinf['diff_remark']=$diff['remark'];

        return  app_show(0,"获取成功",$idinf);

    }
    public function diffstatu(){
        $id = isset($this->post['id']) && $this->post['id'] !=="" ? intval($this->post['id']) :"";
        if($id==""){
            return error_show(1002,"参数id不能为空");
        }
        $dio = Db::name('purchease_diff')->where(['id'=>$id,'is_del'=>0])->find();
        if(empty($dio)){
            return error_show(1002,"工差订单未找到");
        }
        $cgd = Db::name("purchease_order")->where(['cgdNo'=>$dio['cgdNo']])->find();
        if(empty($cgd)){
            return error_show(1002,"采购单未找到");
        }
        $salediff=Db::name("sale_diff")->where(["cgd_diffid"=>$dio['id']])->find();
        if($salediff==false){
            return error_show(1002,"销售工差单未找到");
        }
        $status = isset($this->post['status']) && $this->post['status'] !=="" ? intval($this->post['status']) :"";
        if($status===""){
            return error_show(1002,"参数status不能为空");
        }
        Db::startTrans();
        try{
            $temp = $dio['status'];
            $dio['status']=$status;
            $dio['updatetime']=date("Y-m-d H:i:s");
            $item = Db::name("purchease_diff")->save($dio);
            if ($item){
                if($status==2){
                    $cgd['diff_fee'] =$dio['diff_price'];
                    $cgd['diff_weight'] =$dio['diff_weight'];
                    $cgd['updatetime'] =date("Y-m-d H:i:s");
                    $cgp=Db::name("purchease_order")->save($cgd);
                    if($cgp==false){
                        Db::rollback();
                        return error_show(1002,"采购单更新失败");
                    }
                    if($salediff['is_act']==1){
                        $saled=[
                            "diff_fee"=>$salediff['diff_price'],
                            "diff_weight"=>$salediff['diff_weight'],
                            "updatetime"=>date("Y-m-d H:i:s")
                        ];
                        $up =Db::name("sale")->where(["orderCode"=>$salediff['orderCode']])->save($saled);
                        if($up==false){
                            Db::rollback();
                            return error_show(1002,"销售单更新失败");
                        }
                    }
                }
                $sto = ["order_code" => $dio['cgdNo'], "status" => 1, "action_remark" => '', "action_type" => "create"];
                ActionLog::logAdd(['id' => $this->uid, 'nickname' => $this->uname], $sto, "CGGCD", $status, $this->post);
                $process = ["order_code" => $dio['cgdNo'], "order_id" => $dio['id'], "order_status" => $status, "order_type" => 'CGGCD', "before_status" => 1, 'holder_id' => $dio['apply_id']];
                ProcessOrder::AddProcess(['id' => $this->uid, 'nickname' => $this->uname], $process);
                Db::commit();
                return error_show(0,"更新成功");
            }else{
                Db::rollback();
                return error_show(1002,"更新失败");
            }
        }catch (\Exception $e){
            Db::rollback();
            return error_show(1002,$e->getMessage()."|".$e->getLine());
        }


    }

    //修改采购单的实时金价
    public function editGoldPrice()
    {

        $param = $this->request->only(['cgdNo', 'gold_price'], 'post', 'trim');

        $val = Validate::rule(['cgdNo|采购单号' => 'require', 'gold_price|实时金价' => 'require|float']);

        if (!$val->check($param)) return error_show(1004, $val->getError());

        //采购单
        $data = Db::name("purchease_order")
            ->field('id,demo_fee,good_num,weight,open_fee,teach_fee,pakge_fee,mark_fee,cert_fee,nake_fee,delivery_fee,status')
            ->where(["cgdNo" => $param['cgdNo'], "is_del" => 0])
            ->find();

        if (empty($data)) return error_show(1004, "未找到该采购单数据");
        if ($data['status'] != 0) return error_show(1005, '该状态下不允许修改实时金价');
        $sale_price =  round($data['demo_fee'] / $data['good_num'] + $data['open_fee'] / $data['good_num'] +$data['weight']  * $param["gold_price"] + $data['teach_fee'] *  $data['weight']  +
            $data['pakge_fee'] +  $data['mark_fee'] + $data['cert_fee'] +$data['nake_fee'] + $data['delivery_fee'],2);
        $total_price = round($data['good_num']*$sale_price,2);

        $rs = Db::name("purchease_order")
            ->where('id', $data['id'])
            ->update(['updatetime' => date('Y-m-d H:i:s'), 'gold_price' => $param['gold_price'],"good_price"=>$sale_price,"total_fee"=>$total_price]);

        return $rs ? app_show(0, '修改采购单实时金价成功') : error_show(1005, '修改采购单实时金价失败');

    }


    //采购单导出
    public function exportCgdList()
    {
        $cgdNos = $this->request->post('cgdNos', [], 'trim');

        if (empty($cgdNos)) return error_show(1004, '要导出的采购单编号不能为空');

        $i = 1;
        $send_type = [1 => '直接发货', 2 => '延时发货'];
        $status = [0 => '待与供应商确认', 1 => '待入库', 2 => '部分入库', 3 => '入库完成', 4 => '已取消订单'];
        $list = Db::name("purchease_order")
            ->alias('po')
            ->field('"" as 序号,po.addtime as 创建时间,po.cgdNo as 采购单编号,po.status as 采购单状态,
            po.cgder as 采购员,s.orderCode as 确认单号,s.addtime as 确认单时间,po.spuCode as 产品编号,po.good_name as 产品名称,"" as 规格,
            "" as 单位,po.supplier_name as 供应商名称,po.supplierNo as 供应商编号,po.nake_fee as 裸价,po.delivery_fee as 物流费,
            s.send_type as 发货方式,po.good_price as 采购单价,s.remark as 确认单备注,po.good_num as 采购数量,po.total_fee as 采购货款,
            b.company as 购买方公司,s.arrive_time as 到货时间,"" 税率,oa.addr 收货地址,oa.mobile 电话,oa.contactor 联系人,s.platform_order 平台订单编号,oa.receipt_quantity 地址发货数量, oa.addr_code,po.order_type')
            ->whereIn('po.cgdNo', $cgdNos)
            ->leftJoin('order_num on', 'on.cgdNo=po.cgdNo')
            ->leftJoin('sale s', 's.orderCode=on.orderCode  AND s.is_del=0')
            ->leftJoin('order_addr oa', 'oa.orderCode=on.orderCode AND oa.is_del=0')
            ->leftJoin('business b', 'b.companyNo=s.supplierNo AND b.is_del=0')
            ->order("po.addtime desc")
            ->withAttr('序号', function () use (&$i) {
                return $i++;
            })->withAttr('采购单状态', function ($val) use ($status) {
                return isset($status[$val]) ? $status[$val] : '';
            })->withAttr('发货方式', function ($val) use ($send_type) {
                return isset($send_type[$val]) ? $send_type[$val] : '';
            })->withAttr('发货方式', function ($val) use ($send_type) {
                return isset($send_type[$val]) ? $send_type[$val] : '';
            })
            ->select()
            ->toArray();

        foreach ($list as &$value) {

            if ($value['order_type'] == 3) {
                $temp = Db::name("good_zixun")
                    ->where(["spuCode" => $value['产品编号'], "is_del" => 0])
                    ->field('id,specinfo,good_unit,tax')
                    ->find();
                $good_unit = isset($temp['good_unit']) ? $temp['good_unit'] : 0;
                $specinfo = isset($temp['specinfo']) ? json_decode($temp['specinfo'], true) : [];

                $speclist = [];
                foreach ($specinfo as $val) {
                    $speclist[] = $val['spec_name'] . ':' . $val['spec_value_name'];
                }
                $value['税率'] = $temp['tax'] . '%';
            } else {
                $good_unit = Db::name('good_basic')
                    ->field('id,good_unit,tax')
                    ->where(['spuCode' => $value['产品编号']])
                    ->find();
                $spec = Db::name("good_spec")
                    ->field('id,spec_id,spec_value_id')
                    ->where(["spuCode" => $value['产品编号'], "is_del" => 0])
                    ->select()
                    ->toArray();
                $speclist = [];
                if (!empty($spec)) {
                    foreach ($spec as $val) {
                        $speclist[] = Db::name("specs")->where(["id" => $val['spec_id']])->value('spec_name', '') . ':' . Db::name("spec_value")->where(["id" => $val['spec_value_id']])->value('spec_value', '');

                    }
                }
                $value['税率'] = isset($good_unit['tax']) ? $good_unit['tax'] . '%' : '';
            }

            $value['规格'] = empty($speclist) ? '' : implode(',', $speclist);;
            $value['单位'] = isset($good_unit['good_unit']) ? Db::name('unit')->where(['id' => $good_unit['good_unit'], 'is_del' => 0])->value('unit', '') : '';

            if (!empty($value['addr_code'])) {
                $temp = explode(',', $value['addr_code']);
                $temp_ = GetAddr(json_encode(['provice_code' => $temp[0], 'city_code' => $temp[1], 'area_code' => $temp[2]]));
                $value['收货地址'] = $temp_ . $value['收货地址'];
            }

            unset($value['addr_code']);
            unset($value['order_type']);

        }

        $headerArr = array_keys($list[0]);
        excelSave('采购单导出' . date('YmdHis'), $headerArr, $list);
    }


    //获取采购单修改供应商的记录列表
    public function getChangeSupplierList()
    {

        $param = $this->request->only(['cgdNo' => '', 'start' => '', 'end' => '', 'creater' => '', 'page' => 1, 'size' => 15, 'company_name' => ''], 'post', 'trim');

        $where = [['a.is_del', '=', 0]];
        if (!empty($param['cgdNo'])) $where[] = ['a.cgdNo', 'like', '%' . $param['cgdNo'] . '%'];
        if (!empty($param['start'])) $where[] = ['a.addtime', '>=', $param['start']];
        if (!empty($param['end'])) $where[] = ['a.addtime', '<=', $param['end'] . ' 23:59:59'];
        if (!empty($param['creater'])) $where[] = ['a.creater', 'like', '%' . $param['creater'] . '%'];
        if (!empty($param['company_name'])) $where[] = ["a.creater_id", 'in', get_company_item_user_by_name($param['company_name'])];

        $count = Db::name('purchease_change_supplier_log')
            ->alias('a')
            ->where($where)
            ->count('a.id');

        $list = Db::name('purchease_change_supplier_log')
            ->alias('a')
            ->field('a.*,u.itemid')
            ->leftJoin("depart_user u", "u.uid=a.creater_id AND u.is_del=0")
            ->where($where)
            ->order('a.id', 'desc')
            ->page($param['page'], $param['size'])
            ->append(['company_name'])
            ->withAttr('company_name', function ($val, $data) {
                return implode('/', array_column(GetPart($data['itemid']), 'name'));
            })
            ->select()
            ->toArray();

        return app_show(0, '获取成功', ['list' => $list, 'count' => $count]);

    }

//    public function create(){
//        $customer = isset($this->post['customer_code'])&&$this->post['customer_code']!="" ?trim($this->post['customer_code']):"";
//        if($customer==""){
//            return error_show(1004,"参数customer_code不能为空");
//        }
//        $supplier = isset($this->post['supplier_code'])&&$this->post['supplier_code']!="" ?trim($this->post['supplier_code']):"";
//        if($supplier==""){
//            return error_show(1004,"参数supplier_code不能为空");
//        }
//        $good_code = isset($this->post['good_code']) && $this->post['good_code']!=""?trim($this->post['good_code']):"";
//        if($good_code==""){
//            return error_show(1004,"参数good_code不能为空");
//        }
//        $good_num = isset($this->post['good_num'])&& $this->post['good_num']!==""? intval($this->post['good_num']):"";
//        if($good_num===""){
//            return error_show(1004,"参数good_code不能为空");
//        }
//        $file_url = isset($this->post['file_url'])&& $this->post['file_url']!==""? trim($this->post['file_url']):"";
//        if($file_url===""){
//            return error_show(1004,"参数file_url不能为空");
//        }
//        $mark =isset($this->post['remark'])&&$this->post['remark']!=""?trim($this->post['remark']):"";
//        if($mark==""){
//            return error_show(1004,"参数remark不能为空");
//        }
//
//        $data=[
//            ""
//        ];
//    }

}