<?php

namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\AdminInfor;
use App\Models\Note;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\PjGoods;
use App\Models\Pt;
use App\Models\SendGoods;
use App\Models\User;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use BlueCity\Data\Service\ZhiPei\OrderService as zhiPeiOrder;
use DB;
use App\Models\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SendGoodsService extends Service
{
    //private static $instance;
    private $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new SendGoods();
    }


    /**
     * 获取详细内容
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @param array $type 查询类型
     * @return
     * @author du 2021年8月14日上午9:03:06
     */
    public static function getInfoBy($key, $value, $select = [] , $type = 'get')
    {
    	$db = new SendGoods();
    	if(in_array($key, ['id','send_num'])) {
            $type = 'first';
        }
    	if($type == 'first') {
            if (count($select) == 1) {
                $type = 'value';
            }
        }
    	$list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
    	return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 多条件获取
     * @param array $params 查询条件
     * @param array $select 查询内容
     * @param array $type 查询类型
     * @retrun /multitype:array
     * @author dou 2021/11/24 11:09
     * |---------------------------------------------------------------------------------
    */
    public static function getSendGoodBy($params , $select = [] , $type = 'get')
    {
        $db = new SendGoods();
        if($type == 'first') {
            if (count($select) == 1) {
                $type = 'value';
            }
        }
        $list = CommonService::getMysqlData($db,$params,$select,[],$type);
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取发货单中现存有效商品数
     * @param string $order_num 订单单号
     * @retrun multitype:array
     * @author dou 2021/8/18 16:10
     * |---------------------------------------------------------------------------------
    */
    public static function searchSendNum ( $order_num ){
        $db = Db::table('send_goods');
        $list = CommonService::getMysqlData($db, ['reject'=>1,'recover_noteq'=>2,'order_num_searchin'=>$order_num],['goods_id','msg_id','goods_name','goods_num','recover']);
        if($list){
            $listnum = [];
            foreach($list as $k => $v){
                $recover = 0;
                if($v['recover']==1){
                    $recover = $v['goods_num'];
                }
                if(isset($listnum[$v['goods_id']])){
                    $listnum[$v['goods_id']]['goods_num'] += $v['goods_num'];
                    $listnum[$v['goods_id']]['msg_id'] .= ','.$v['msg_id'];
                    $listnum[$v['goods_id']]['recover'] += $recover;
                }else{
                    $listnum[$v['goods_id']] = $v;
                    $listnum[$v['goods_id']]['recover'] = $recover;
                }
            }
        }
        return $listnum;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取可发货商品
     * @param array $ordermsg 订单商品信息
     * @param array $sendlist 发货单中现存有效商品数
     * @param array $type 是否展示全部商品
     * @retrun multitype:array
     * @author dou 2021/8/18 16:59
     * |---------------------------------------------------------------------------------
     */
    public static function selectSendGoods ( $ordermsg , $sendlist , $type = false){
        $data = [];
        foreach($ordermsg as $k => $v){
            $goods_num = $sendlist[$k]['goods_num']??0;
            $recover = $sendlist[$k]['recover']??0;
            $num = $v['goods_num'] - $goods_num;
            if($num > 0 || $recover>0 || $type){
                if($num>0){
                    $msg_id1 = $sendlist[$k]['msg_id']??'';
                    if($msg_id1){
                        $msg_id1 = explode(',', $msg_id1);
                        $msg_id = explode(',', $v['id']);
                        $msg_id1 = array_unique($msg_id1);
                        $msg_ids = array_unique($msg_id);
                        if(count($msg_id1) != 1 || count($msg_ids) != 1) {
                            foreach ($msg_id as $ka => $va) {
                                if (in_array($va, $msg_id1)) {
                                    unset($msg_id[$ka]);
                                }
                            }
                        }
                        if($msg_id){
                            $msg_id = array_unique($msg_id);
                            $msg_id = implode(',', $msg_id);
                        }else{
                            $msg_id = '';
                        }
                    }else{
                        $msg_id = $v['id'];
                    }
                    $v['id'] = $msg_id;
                }else{
                    $v['id'] = '';
                }
                $v['recover'] = $recover;
                $v['surplus_num'] = $num;
                $data[] = $v;
            }
        }
        return $data;
    }
    /**
     *
     * @param array $data
     * @param array $goodsArr
     * @return int
     * @author du 2021年8月17日下午2:24:19
     */
    public static function createData($data,$goodsArr){
        $poss['warehouse_num'] = $data['warehouse_num'];//库房同步单号
    	$poss['send_num'] = $data['send_num'];
        $poss['send_type'] = $data['send_type'];
    	$poss['sys_num'] = $data['sys_num'];
    	$poss['order_num'] = $data['order_num'];
    	$poss['time'] = date("Y-m-d H:i:s") ;
    	$poss['stores'] = $data['stores'];
    	$poss['receiving_store'] = $data['receiving_store']??'';
    	$poss['user'] = $data['user']??'';
        $poss['name'] = $data['name']??'';
    	$poss['telephone'] = $data['telephone']??'';
    	$poss['collect_type'] = $data['collect_type']??'';//收货类型 1:门店发货 ;2: 客户收货
    	$poss['address'] = $data['address']??'';
    	$poss['expect_time'] = $data['expect_time'];
        $poss['add_num'] = $data['add_num']??0;
        $poss['data_source'] = $data['data_source']??1;
        $poss['category'] = $data['category']??1;
        $poss['afid'] = $data['afid']??0;
        $poss['source'] = $data['source']??1;
        $poss['sheng'] = $data['sheng'];
        $poss['shi'] = $data['shi'];
        $poss['create_id'] = $data['create_id'];
        $poss['create_name'] = $data['create_name'];

//        if($poss['send_type'] == 2){
//            $poss['type'] = 4;
//        }
    	$res = SendGoods::insertGetId($poss);
        if($res) {
            $arr['pid'] = $res;
            $arr['send_num'] = $data['send_num'];
            $arr['send_type'] = $data['send_type'];
            $arr['sys_num'] = $data['sys_num'];
            $arr['order_num'] = $data['order_num'];
            $arr['store_id'] = $data['stores'];
            foreach ($goodsArr as $k => $v) {
                $arr['goods_id'] = $v['goods_id'];
                $arr['goods_name'] = $v['goods_name'];
                $msg_id = explode(',', $v['msg_id']);
                array_splice($msg_id, $v['goods_num']);
                $arr['msg_id'] = implode(',', $msg_id);
                $arr['goods_num'] = $v['goods_num'];
                $ret = Db::table('send_goods')->insert($arr);
                if (!$ret) {
                    return $ret;
                }
            }
        }
    	return $res;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取售后执行单号
     * @param string $order_num 订单单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2021/12/16 11:49
     * |---------------------------------------------------------------------------------
    */
    public static function creactNum ( $order_num ){
        $db = new SendGoods();
        $num = CommonService::getMysqlData($db, ['order_num'=>$order_num],['add_num'],['id'=>'DESC'],'value');
        if($num){
            $num = $num+1;
        }else{
            $num = 1;
        }
        $data['order_num'] = $order_num.'-F'.$num;
        $data['num'] = $num;
        return $data;
    }
    /**
     * 获取列表
     * @param array $input
     * @param array $session
     * @return Ambigous <multitype:, unknown, multitype:unknown NULL >
     * @author du 2021年8月14日下午3:39:38
     */
    public static function getList($input,$session){
    	$Db = new SendGoods();
    	$where = [];
    	$where['gone_send_orders.data_source'] = 1;
    	//订单号
    	if(isset($input['order_num'])){
    		$where['gone_send_orders.order_num_like'] = $input['order_num'];
    	}
    	if(isset($input['status'])){
    		if($input['status'] == 6){//待追回
    			$status = 1;
    			$where['gone_send_orders.recover'] = $status;
                //$where['gone_send_orders.send_type'] = 1;
    		}elseif($input['status'] == 7){//追回已处理
    			$where['gone_send_orders.recover_searchgt'] = '1';
               // $where['gone_send_orders.send_type'] = 1;
    		}elseif($input['status'] == 1){//未发货　1　2
    			$where['gone_send_orders.type_searcheqlt'] = '2';
                //$where['gone_send_orders.send_type'] = 1;
    		}elseif($input['status'] == 4){//车模未审核
                $where['gone_send_orders.type'] = $input['status'];
                $where['gone_send_orders.send_type'] = 2;
            }
    		elseif($input['status'] == 3){//已发货　3　
    			$where['gone_send_orders.type'] = $input['status'];
                //$where['gone_send_orders.send_type'] = 1;
    		}
    	}
    	$end_time = $input['end_time'];

    	if($input['start_time'] == $input['end_time']){
    		$end_time = strtotime($end_time);
    		$end_time = $end_time + "86400";
    		$end_time = date("Y-m-d H:i:s",$end_time);
    	}
    	$end_time_b = $input['end_time_b'];

    	if($input['start_time_b'] == $input['end_time_b']){
    		$end_time_b = strtotime($end_time_b);
    		$end_time_b = $end_time_b + "86400";
    		$end_time_b = date("Y-m-d H:i:s",$end_time_b);
    	}
    	//收货门店
    	if(isset($input['stores'])){
    		$where['gone_send_orders.receiving_store_like'] = $input['stores'];
    	}
    	//发货开始时间
    	if(isset($input['start_time'])){
    		$where['gone_send_orders.send_time_searcheqgt'] = $input['start_time'];
    	}
    	//发货结束时间
    	if(isset($input['end_time'])){
    		$where['gone_send_orders.send_time_searcheqlt'] = $end_time;
    	}
        //申请发货开始时间
    	if(isset($input['start_time_b'])){
    		$where['gone_send_orders.time_searcheqgt']  = $input['start_time_b'];
    	}
    	//申请发货结束时间
    	if(isset($input['end_time_b'])){
    		$where['gone_send_orders.time_searcheqlt'] = $end_time_b;
    	}

        //品类搜索
        if(isset($input['category'])){
            $where['gone_send_orders.category'] = $input['category'];
        }

    	$where = CommonService::jointWhere($where);
    	$page_size = $input['page_size']??10;
        /* if($input['is_excel']==1) {
             DB::connection()->enableQueryLog();#开启执行日志
         }
             $Db = $Db->Rightjoin('send_goods', 'send_goods.pid', '=', 'send_orders.id')->Leftjoin('orders', 'send_goods.order_num', '=', 'orders.order_num');
             $paginate = $Db->whereRaw($where)->select('send_orders.*','send_goods.goods_name','send_goods.goods_num','send_goods.courier_number','send_goods.courier_company','orders.create_time','orders.p_id')->orderBy('id','asc')->paginate($page_size);
         else{
             $paginate = $Db->whereRaw($where)->orderBy('id','asc')->paginate($page_size);
         }*/

        if($input['is_excel']==1){
            DB::connection()->enableQueryLog();#开启执行日志
            $Db = $Db->Rightjoin('send_goods', 'send_goods.pid', '=', 'send_orders.id')->Leftjoin('orders', 'send_goods.order_num', '=', 'orders.order_num');
            $paginate = $Db->whereRaw($where)->select('send_orders.*','send_goods.goods_name','send_goods.goods_num','send_goods.courier_number','send_goods.courier_company','orders.create_time','orders.p_id')->orderBy('id','asc')->paginate($page_size);
        }else{
            $paginate = $Db->whereRaw($where)->orderBy('id','asc')->paginate($page_size);
        }

    	//print_r(DB::getQueryLog());

        //导出所需语句
        $data['sqls'] = DB::getQueryLog()[1];

    	$wfh = SendGoods::where('type','<=','2')->where('data_source',1)->count();//->where('send_type',1)
    	$yfh = SendGoods::where('type','3')->where('data_source',1)->count();//->where('send_type',1)
        $wsh = SendGoods::where('type','4')->where('send_type',2)->where('data_source',1)->count();
    	$dzh = SendGoods::where('recover','1')->where('data_source',1)->count();//->where('send_type',1)
    	$yzh = SendGoods::where('recover','>','1')->where('data_source',1)->count();//->where('send_type',1)
    	$show_Menu = [
    			['show_name'=>"全部",'show_num'=>'--' ,'status'=>''],
                ['show_name'=>"车膜未审核",'show_num'=>$wsh,'status'=>'4'],
    			['show_name'=>"未发货",'show_num'=>$wfh,'status'=>'1'],
    			['show_name'=>"已发货",'show_num'=>$yfh,'status'=>'3'],
    			['show_name'=>"待追回",'show_num'=>$dzh,'status'=>'6'],
    			['show_name'=>"追回已处理",'show_num'=>$yzh,'status'=>'7'],
    	];
    	$data['show_Menu'] = $show_Menu;//顶部按钮
    	$all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
    	$export = BmmcService::getTopButton('excel','',$all_button);
    	$data['button_top'] = $export['button_top']??[];//顶部按钮
    	$data['button_search'] = $export['button_search']??[];//搜索栏按钮
    	$list = CommonService::dataToArray($paginate->items());
    	if($list){
    		$list = SendGoodsService::getButtonDatas($all_button, $list);
    		$data['list'] = $list;
    		$data['page'] = [
    				'count' => $paginate->total(),
    				'page'=>$paginate->currentPage(),
    				'page_size'=>$page_size,
    				'allPage'=>$paginate->lastPage()
    		];
    	}else{
    		$data['list'] = [];
    	}
    	return $data;
    }
    /**
     * 获取按钮和数据
     * @param array $all_button
     * @param array $list
     * @return string
     * @author du 2021年8月7日下午3:40:48
     */
    public static function getButtonDatas($all_button,$list){
    	$comName = Admin::where('admin_groupnew',2)->pluck('company_name','id');
    	$stausName = SendGoodsService::getStatusName();
    	$wstoreids = array_unique(array_column($list, 'stores'));
    	$wstoreNames = DB::table('warehouse')->whereIn('id',$wstoreids)->pluck('shck_ckmc','id');

    	$order_nums = array_unique(array_column($list, 'order_num'));
    	//print_r($order_nums);
        $pids = Orders::whereIn('order_num',$order_nums)->pluck('p_id','order_num')->toarray();
        //print_r($pids);
       // $pids = array_unique(array_column($pids, 'p_id'));
       // print_r($pids);
        $pnames = Pt::whereIn('id',$pids)->pluck('pt_name','id')->toarray();
       // print_r($pnames);
    	$arr = self::getRecoverName();
        $sendtypename = self::getSendTypeName();
    	foreach ($list as $k => $v){
            $buttonData = [];
            if($v['send_type']==2){
                $list[$k]['stores_name'] = $wstoreNames[$v['stores']]??'';
            }else{
                $list[$k]['stores_name'] = $comName[$v['stores']];
            }
            $list[$k]['pt_name'] = $pnames[$pids[$v['order_num']]];

            $list[$k]['receiving_store_name'] = $comName[$v['receiving_store']];

            $list[$k]['send_stores_info'] = DB::table('admin_infor')->where('admin_id',$v['stores'])->select('head_phone','admin_province','admin_city','admin_county','admin_dressi')->get();
            $list[$k]['sendtypename'] = $sendtypename[$v['send_type']];



    		$list[$k]['type_name'] = $stausName[$v['type']];

    		$list[$k]['goodsList'] = SendGoodsService::getSendGoodsInfo($v['id']);
    		foreach ($list[$k]['goodsList'] as $key =>$value){
                //1待追回 2已追回3追回失败
                if($value['recover']){
                    $list[$k]['goodsList'][$key]['recover_status'] = $arr[$value['recover']];
                }
    			$list[$k]['goodsList'][$key]['store_name'] = $comName[$value['store_id']];
    			$list[$k]['goodsList'][$key]['recover_name'] = $comName[$v['receiving_store']];

    			if(($value['type']==2)&&(!$value['courier_number']||!$value['courier_company'])){
                    $buttonData[] = 'editCourier';
                }
    		}
    		if($v['reject']==1){
    			$reject = ',reject';
    		}else{
    			$reject = '';
    		}
    		if($v['type']==1){
    			if($v['send_type']!=2){
                    $buttonData[] = 'sendGoodsDo,editAdress';
                }
                if($reject){
                    $buttonData[] = $reject;
                }
    		}
    		if($v['type']==4){
                $buttonData[] = 'auditSend';
            }
    		if($v['type']==2){
                if($v['send_type']!=2){
                    $buttonData[] = 'sendGoodsDo,editAdress';
                    if($v['recover']<1){
                        $buttonData[] = 'recover';
                    }
                }
    			$buttonData[] = 'seePictrue'.$reject;
    		}
    		if($v['type']==3){
    			$buttonData[] = 'seePictrue';
                if($v['send_type']!=2 && $v['recover']<1){
                    $buttonData[] = 'recover';
                }
    		}
    		if($v['reject']==5){
    			unset($buttonData['reject']);
    		}
    		if($v['recover'] == 1 && $v['reject'] == 1){
    			$buttonData[] = 'results';
    		}
    		if($v['category']==3&&$v['add_order']!=1){
                $buttonData[] = 'addOrder';
            }

    		$buttonData[] = 'note';
    		$button = BmmcService::getListButton($buttonData,$all_button);

    		$list[$k]['button_one'] = $button['button_one']??[];
    		$list[$k]['button_two'] = $button['button_two']??[];
    		$list[$k]['button_three'] = $button['button_three']??[];
    	}
    	return $list;
    }

    /**
     * 获取信息
     * @param  $send_num
     * @return
     * @author du 2021年8月18日下午2:29:36
     */

    public static function getSendGoodsInfo($pid){
    	$db = Db::table('send_goods');
    	$infoList = CommonService::getMysqlData($db, ['pid'=>$pid]);
    	return $infoList;

    }

    public static function getStatusName(){
    	//,'6'=>'待追回','7'=>'已追回','8'=>'追回失败'
    	return array('1'=>'未发货','2'=>'处理中','3'=>'已完成','4'=>'车膜未审核','5'=>'驳回');
    }

    /**|---------------------------------------------------------------------------------
     * @name 追回名称
     * @retrun /multitype:array
     * @author dou 2021/9/24 15:42
     * |---------------------------------------------------------------------------------
    */
    public static function getRecoverName ( ){
        return array('0'=>'无追回','1'=>'待追回','2'=>'已追回','3'=>'追回失败');
    }

    /**|---------------------------------------------------------------------------------
     * @name 发货类型
     * @retrun /multitype:array
     * @author dou 2021/9/24 15:44
     * |---------------------------------------------------------------------------------
    */
    public static function getSendTypeName ( ){
        return array('1'=>'自有门店发货','2'=>'库房发货');
    }

    /**|---------------------------------------------------------------------------------
     * @name 发货类型
     * @retrun /multitype:array
     * @author dou 2021/9/24 15:44
     * |---------------------------------------------------------------------------------
     */
    public static function getCollectTypeName ( ){
        return array('1'=>'门店收货','2'=>'客户收货');
    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回状态
     * @retrun /multitype:array
     * @author dou 2021/9/24 15:44
     * |---------------------------------------------------------------------------------
     */
    public static function getRejectName ( ){
        return array('1'=>'未驳回','2'=>'驳回');
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param string $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/9/24 15:07
     * |---------------------------------------------------------------------------------
    */
    public static function getDetailByOrder ( $order_num ){
        $list = self::getInfoBy('order_num',$order_num);
        if($list) {
            $sendtypename = self::getSendTypeName();
            $typename = self::getStatusName();
            $rejectname = self::getRejectName();
            $collecttypename = self::getCollectTypeName();
            $recovername = self::getRecoverName();
            $warehouse = CommonService::getWarehouse();
            $warehouse = array_column($warehouse, 'name', 'type');
            /*----------------------------------------------获取订单门店信息开始----------------------------------------------*/
            $receiving_id = array_column($list, 'stores');
            $send_id = array_column($list, 'receiving_store');
            if ($send_id && $receiving_id) {
                $send_id = array_unique($send_id);
                $receiving_id = array_merge($receiving_id, $send_id);
            } elseif ($send_id) {
                $receiving_id = $send_id;
            }
            if ($receiving_id) {
                $store = AdminsService::getAdmins(['id_searchin' => $receiving_id], ['id', 'company_name']);
                $store = array_column($store, 'company_name', 'id');
            } else {
                $store = [];
            }
            /*----------------------------------------------获取订单门店信息结束----------------------------------------------*/
            foreach ($list as $k => $v) {
                $list[$k]['sendtypename'] = $sendtypename[$v['send_type']];
                $list[$k]['typename'] = $typename[$v['type']];
                $list[$k]['rejectname'] = $rejectname[$v['reject']];
                $list[$k]['collecttypename'] = $collecttypename[$v['collect_type']];
                $list[$k]['recovername'] = $recovername[$v['recover']];
                if ($v['send_type'] == '1') {
                    $list[$k]['storesname'] = $store[$v['stores']];
                } else {
                    $list[$k]['storesname'] = $warehouse[$v['stores']];
                }
                if ($v['collect_type'] == '1') {
                    $list[$k]['receivingstorename'] = $store[$v['receiving_store']];
                } else {
                    $list[$k]['receivingstorename'] = '';
                }
                $send_goods = Db::table('send_goods')->where('pid', $v['id'])->get()->toarray();
                foreach ($send_goods as $ks => $vs) {
                    if ($vs['send_type'] == '1') {
                        if (isset($store[$v['stores']])) {
                            $send_goods[$ks]['storesname'] = $store[$v['stores']];
                        } else {
                            $send_goods[$ks]['storesname'] = AdminsService::getAdminsBy('id', $v['stores'], ['company_name']);
                        }

                    } else {
                        $send_goods[$k]['storesname'] = $warehouse[$v['stores']];
                    }
                    $send_goods[$ks]['sendtypename'] = $sendtypename[$vs['send_type']];
                    $send_goods[$ks]['typename'] = $typename[$vs['type']];
                    $send_goods[$ks]['rejectname'] = $rejectname[$vs['reject']];
                    $send_goods[$ks]['collecttypename'] = $collecttypename[$vs['collect_type']];
                    $send_goods[$ks]['recovername'] = $recovername[$vs['recover']];
                }
                $list[$k]['send_goods'] = $send_goods;
            }
        }
        return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 申请发货
     * @param array $request 请求参数
     * @retrun /multitype:array
     * @author dou 2021/11/6 13:48
     * |---------------------------------------------------------------------------------
    */
    public static function sendGoods( $request , $after = false ){
        $BaseController = new BaseController();
        $input = $request->all();
        $checkKey=CommonService::checkKey(['data','order_num','sys_num','delivery_store','send_time','collect_type','send_type'],$input,array('data' => '需发货商品信息','order_num' => '订单单号','sys_num' => '系统单号','delivery_store' => '发货门店','store_id' => '收货门店','send_time' => '期望送达时间','name' => '姓名','telephone' => '电话','collect_type' => '收货人类型','address' => '收货地址','note' => '备注信息','send_type' => '发货部门类型'));
        if($checkKey['code']!=1){
            return  ['Data' => '','ErrorMessage'=>'参数'.$checkKey['data'].'未填写,或值为空','ErrorCode'=>ErrorInc::INVALID_PARAM];
//            return $BaseController->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);
        }
        if($input['collect_type']==1){
            if(!isset($input['store_id'])){
                return  ['Data' => '','ErrorMessage'=>'参数收货门店未填写,或值为空','ErrorCode'=>ErrorInc::INVALID_PARAM];
            }
        }
        $goodsArr = $request->input('data');
        $order_num =  $request->input('order_num');
        $sys_num = $request->input('sys_num');
        $order_nums = [];
        $orders = OrderService::getOrderBy('order_num', $order_num,['accoun','category']);
        $order_nums[] = $orders['accoun'];
        $order_nums[] = $order_num;
        $sendlist = OrderService::selectSendGoods($order_nums, $sys_num,true);
        $sendlist = CommonService::jointArrayKey($sendlist, 'goods_id');
        $good_num = array_column($goodsArr, 'goods_num');
        if(!$good_num){
            return  ['Data' => '','ErrorMessage'=>'请填写发货数量','ErrorCode'=>ErrorInc::INVALID_PARAM];
//            return $BaseController->error("请填写发货数量", ErrorInc::INVALID_PARAM);
        }
        if(in_array(0, $good_num)){
            return  ['Data' => '','ErrorMessage'=>'发货商品数量不可添加0','ErrorCode'=>ErrorInc::FAILED_PARAM];
//            return $BaseController->error("发货商品数量不可添加0", ErrorInc::FAILED_PARAM);
        }
        //general_version
        foreach($goodsArr as $k => $v){
            $goods[$k]['goods_num'] = $v['goods_num'];//'goods_id'=>'wj0001','goods_num'=>1,'goods_price'=>'0','goods_remarks'=>$shr_other
            $goods[$k]['goods_id'] = PjGoods::where('pg_id',$v['goods_id'])->value('general_version');//'wj0001';
            $msg_goods_price = OrderMsg::where('id',$v['msg_id'])->value('goods_price');
            $goods[$k]['goods_price'] = $msg_goods_price??'0';//
            $goods[$k]['goods_remarks'] = 'test';

            $num = $sendlist[$v['goods_id']]['surplus_num']-$v['goods_num'];
            if(!$after) {
                if ($num < 0) {
                    return ['Data' => '', 'ErrorMessage' => '商品：' . $v['goods_name'] . "剩余可发数量不足", 'ErrorCode' => ErrorInc::FAILED_PARAM];
                    //                return $BaseController->error('商品：'.$v['goods_name']."剩余可发数量不足", ErrorInc::FAILED_PARAM);
                }
            }
        }
//        DB::beginTransaction();
        $send_num = 'F'.uniqid();
        $warehouse_nums = SendGoodsService::creactNum($order_num);
        $warehouse_num = $warehouse_nums['order_num'];
        if ($request->filled('data')) {
            $data['send_num'] = $send_num;
            $data['add_num'] = $warehouse_nums['num'];
            $data['warehouse_num'] = $warehouse_num;
            $data['send_type'] = $request->input('send_type');
            $data['sys_num']= $sys_num;
            $data['order_num']= $order_num;
            $data['stores'] = $request->input('delivery_store');
            $data['receiving_store'] =$request->input('store_id');
            $data['user']= $request->get('session_token')['admin_acc'];
            $data['telephone'] = $request->input('telephone');
            $data['collect_type'] = $request->input('collect_type');
            $data['expect_time'] = $request->input('send_time');
            $data['name'] = $request->input('name');
            $data['category'] = $orders['category'];
            $data['afid'] = $request->input('after_id');
            $data['source'] = $request->input('source');
            $address = '';
//            if($input['shr_sheng'] && $input['shr_shi'] && $input['shr_xian']){
//                $address .= $input['shr_sheng'];
//                $address .= $input['shr_shi'];
//                $address .= $input['shr_xian'];
//            }
            $data['sheng'] = $input['shr_sheng']??'';
            $data['shi'] = $input['shr_shi']??'';
            $data['xian'] = $input['shr_xian']??'';
//            $address .= $request->input('address');
            $data['address'] = $request->input('address');
            if($request->filled('note')){
                $data['send_note'] = $request->input('note');
                $rest = CommonService::accMe($sys_num, "发货备注同步" , $request->input('note'), '', '', $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
            }
            $data['create_id'] = $request->get('session_token')['id'];
            $data['create_name'] = $request->get('session_token')['admin_acc'];
            $res1 = SendGoodsService::createData($data, $goodsArr);
            $kf = 0;
            if($res1){
            /*----------------------------------------------同步智配 start---------------------------------------------*/
                //生成同步智配发货单号
                $zhipeinum = $warehouse_num;
                //同步智配 start
                if($input['send_type']==2){
                    $shr_other = $input['note']??'';
                    $orderInfo = OrderService::getOrderBy('order_num', $order_num,['p_id','new_customer_id']);
                    // 门店收货 1 客户收货2
                    if($input['collect_type']==1){
                        $adminInfo = AdminInfor::where('admin_id',$input['store_id'])->select('service_name','phone','admin_province','admin_city','admin_county','admin_dressi')->first();
                        $company_name = Admin::where('id',$input['store_id'])->value('company_name');
                        // dump($adminInfo);
                        $shr_name = $company_name??'无';
                        $shr_phone = $adminInfo['phone'];
                        if(!$adminInfo['phone']||!$adminInfo['admin_province']||!$adminInfo['admin_city']||!$adminInfo['admin_county']||!$adminInfo['admin_dressi']){
                            return  ['Data' => '','ErrorMessage'=>'门店信息不完善','ErrorCode'=>ErrorInc::FAILED_PARAM];
                        }
                        $shr_sheng = $adminInfo['admin_province'];
                        $shr_shi = $adminInfo['admin_city'];
                        $shr_xian = $adminInfo['admin_county'];
                        $shr_adress = $adminInfo['admin_dressi']??'无';
                    }elseif ($input['collect_type']==2){
                        if($input['shr_sheng'] && $input['shr_shi'] && $input['shr_xian']){
                            $usr = [];
                            $usr['shr_sheng'] = $input['shr_sheng'];
                            $usr['shr_shi'] = $input['shr_shi'];
                            $usr['shr_xian'] = $input['shr_xian'];
                        }else {
                            $usr = User::where('id', $orderInfo['new_customer_id'])->select('shr_sheng', 'shr_shi', 'shr_xian')->first();
                        }
                        $shr_name = $input['name'];
                        $shr_phone = $input['telephone'];
                        $shr_sheng = $usr['shr_sheng'];
                        $shr_shi = $usr['shr_shi'];
                        $shr_xian = $usr['shr_xian'];
                        $shr_adress = $input['address'];
                    }else{
                        return  ['Data' => '','ErrorMessage'=>'collect_type参数错误','ErrorCode'=>ErrorInc::FAILED_PARAM];
//                        return $BaseController->error('collect_type参数错误', ErrorInc::FAILED_PARAM);
                    }
                    $p_id = PlatformService::getPtBy('id', $orderInfo['p_id'],['zp_id']);
                    if(!$p_id){
                        return  ['Data' => '','ErrorMessage'=>'未匹配平台编号','ErrorCode'=>ErrorInc::TRANSFER_FAILED];
                    }
                    $recycle_id = $input['recycle_id']??0;
                    if($recycle_id>0){
                        $is_barter = 2;
                    }else{
                        $is_barter = 1;
                    }
                    $zdata = ['p_id'=>$p_id,'company_id'=>1,'is_barter'=>$is_barter,'ware_id'=>4,'shr_other'=>$shr_other,'new_money'=>'0'];
                    //$goodsData = ['goods_id'=>'wj0001','goods_num'=>1,'goods_price'=>'0','goods_remarks'=>$shr_other];
                    $userInfo = ['shr_name'=>$shr_name,'shr_phone'=>$shr_phone,'shr_sheng'=>$shr_sheng,'shr_shi'=>$shr_shi,'shr_xian'=>$shr_xian,'shr_adress'=>$shr_adress];
//                    dump($userInfo);
                    //$res['code'] ='200';
                    $res = zhiPeiOrder::orderPut($zhipeinum, $zdata, $goods, $userInfo);
                    $logdata = json_encode($zdata).'-'.json_encode($goods).'-'.json_encode($userInfo).'-'.json_encode($res);
                    CommonService::addLog('同步发货单', $logdata, $zhipeinum,'SendGoods');
                    if($res['code']!='200'){
                        //dump($res);
//                        DB::rollback();//回滚
                        return  ['Data' => '','ErrorMessage'=>'同步失败:'.$res['msg'].$res['data'],'ErrorCode'=>ErrorInc::MYSQL_FAILED];
//                        return $BaseController->error('同步失败', ErrorInc::MYSQL_FAILED);
                    }
                    $kf = 1;
                }
                //同步智配 end
            /*----------------------------------------------同步智配 end-----------------------------------------------*/
                $goodsname = implode(',',array_column($goodsArr, 'goods_name'));
                $BaseController->insertingLog('申请发货，', $sys_num, '申请发货商品：'.$goodsname, '订单管理', $request->ip(), $request->get('session_token')['admin_acc']);//日志
//                DB::commit(); //提交
                if($kf == 1){
                    $return['warehouse_num'] = $warehouse_num;
                }else {
                    $return['warehouse_num'] = '';
                }
                $return['id'] = $res1;
                return  ['Data' => $return,'ErrorMessage'=>'操作成功','ErrorCode'=>1];
//                return $BaseController->success('操作成功');
            }else{
//                DB::rollback();//回滚
                return  ['Data' => '','ErrorMessage'=>'操作失败','ErrorCode'=>ErrorInc::MYSQL_FAILED];
//                return $BaseController->error('操作失败', ErrorInc::MYSQL_FAILED);
            }
        }else{
            return  ['Data' => '','ErrorMessage'=>'缺少参数','ErrorCode'=>ErrorInc::INVALID_PARAM];
//            return $BaseController->error('缺少参数', ErrorInc::INVALID_PARAM);
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 同步库房发货状态
     * @param string  $warehouse_num 库房单号
     * @param string  $courier_number 快递单号
     * @param string  $courier_company 快递公司
     * @retrun /multitype:array
     * @author dou 2021/12/10 16:21
     * |---------------------------------------------------------------------------------
    */
    public static function sysCourierData ( $warehouse_num , $courier_number , $courier_company ){
        $db = new SendGoods();
        $pid = CommonService::getMysqlData($db, ['warehouse_num'=>$warehouse_num,'reject'=>1],['id'],[],'value');
        if($pid) {
            DB::beginTransaction();
            $db = DB::table("orders_joingoods");
            $data = CommonService::getMysqlData($db, ['skb_bh'=>$warehouse_num],['o_skbnum','sys_bh']);
            $o_skbnum = array_column($data, 'o_skbnum');
            $db = new Orders();
            $order = CommonService::getMysqlData($db, ['order_num'=>$warehouse_num,'order_status'=>3],['customer_id','sys_num'],[],'first');
            $customer_id = $order['customer_id'];
            if($order){
                $car_make = UserService::getUserBy('id', $customer_id,['car_make']);
//                if($car_make!=''){
//                    $order_status = 10;
//                }else{
//                    $notdb = new Note();
//                    $car_make = CommonService::getMysqlData($notdb, ['orders_id'=>$order['sys_num'],'note_type'=>'客户车型'],['id'],[],'first');
//                    if($car_make){
//                        $order_status = 10;
//                    }else {
//                        $order_status = 1;
//                    }
//                }
                $order_status = 10;
                if($data){
                    $reb = Orders::whereIn("order_num", $o_skbnum)->where("order_status", 3)->update(['order_status' => $order_status]);
                }else {
                    $reb = Orders::where("order_num", $warehouse_num)->where("order_status", 3)->update(['order_status' => $order_status]);
                }
            }else{
                $reb = true;
            }
            if($data){
                $res = SendGoods::whereIn("warehouse_num", $o_skbnum)->update(['type' => 3, 'send_time' => date("Y-m-d H:i:s")]);
            }else {
                $res = SendGoods::where("warehouse_num", $warehouse_num)->update(['type' => 3, 'send_time' => date("Y-m-d H:i:s")]);
            }
            $rea = DB::table('send_goods')->where('pid',$pid)->update(['type' => 2,'courier_number'=>$courier_number,'courier_company'=>$courier_company]);
            if($rea && $res && $reb){
                DB::commit(); //提交
                return  ['Data' => '','ErrorMessage'=>'操作成功','ErrorCode'=>1];
            }else{
                DB::rollback();//回滚
                return  ['Data' => '','ErrorMessage'=>'操作失败','ErrorCode'=>ErrorInc::MYSQL_FAILED];
            }
        }else{
            return  ['Data' => '','ErrorMessage'=>'无单号对应数据','ErrorCode'=>ErrorInc::DATA_EMPTY];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 驳回发货
     * @param int $id 发货商品数据id
     * @param string $send_num 发货单号
     * @param string $order_num 订单单号
     * @param string $goods_name 商品信息
     * @param int $pid 发货单id
     * @param int $send_type 发货类型
     * @param array $session 操作人信息
     * @param int $ip 操作人ip
     * @retrun /multitype:array
     * @author dou 2022/3/22 15:29
     * |---------------------------------------------------------------------------------
    */
    public static function reject ( $id , $send_num , $order_num , $goods_name , $pid , $send_type , $session , $ip ){
        if($send_type==1){
            $ret = Db::table('send_goods')->where('id',$id)->update(['reject'=>5,'type'=>5]);
            $res = Db::table('send_goods')->where('pid',$pid)->where('reject',1)->select('id')->get();
            if(count($res)==0){
                $re = SendGoods::where('id',$pid)->update(['reject'=>5,'type'=>5]);
            }
        }elseif($send_type==2){
            $res =  SendGoods::where('id',$pid)->update(['reject'=>5,'type'=>5]);
            $ret =  Db::table('send_goods')->where('pid',$pid)->update(['reject'=>5,'type'=>5]);
            //同步智配 start
            if($ret) {
                $warehouse_num = SendGoods::where('id',$pid)->value('warehouse_num');
                $zhipeinum = $warehouse_num;//库房同步单号
                $zres = zhiPeiOrder::cancelShipping($zhipeinum);//发货取消
                CommonService::addLog('同步发货取消', json_encode($res), $zhipeinum,'SendGoods');
                //dump($zres);
                if ($zres['code'] != '200') {
                    return  ['Data' => '','ErrorMessage'=>'同步失败'. $zres['msg'],'ErrorCode'=>ErrorInc::MYSQL_FAILED];
                }
            }
        }else{
            return  ['Data' => '','ErrorMessage'=>'类型错误','ErrorCode'=>ErrorInc::FAILED_PARAM];
        }
        if($ret){
            $BaseController = new BaseController();
            $BaseController->insertingLog("驳回", $order_num, "驳回" . $send_num, "发货列表".$goods_name, $ip, $session['admin_acc']);//日志
            //同步结束 end
            return  ['Data' => '','ErrorMessage'=>'操作成功','ErrorCode'=>1];
        }else{
            return  ['Data' => '','ErrorMessage'=>'操作失败','ErrorCode'=>ErrorInc::MYSQL_FAILED];
        }
    }

}
