<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Admin\Pushxm;
use App\Models\GhPrice;
use App\Models\GhXPrice;
use App\Models\SyncStores;
use App\Services\CommonService;
use App\Services\CompanyService;
use App\Services\PlatformService;
use App\Services\SysStoresService;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\PushLidao;
use App\Http\Controllers\Admin\Push;
use App\Models\Temporary;
use App\Models\Disareanew;
use App\Models\Bserviss;
use DB;

class AotuorderController extends BaseController
{
    public function Distrib ($sys_nums,$ip,$admin_acc="系统录入",$admin_id='1133')
    {
	    //$sys_nums='L20191120071726725';
	    //$sys_nums='L20191120071931088';
	    //$ip="192.168.1.1";
	    if(date("Y-m-d H:i:s")>"2019-11-10 16:00:00" && date("Y-m-d H:i:s")<"2019-11-11 00:31:00"){
			$this->manual($sys_nums);
			$this->inserting_log("系统派单，",$sys_nums,'11.10|16:00-00:31停止自动派单',"订单管理",$ip,$admin_acc);//日志、
			exit;
		}
        if($sys_nums!=''){
            $sys_num= $sys_nums;
            $now=date("H:i:s");
            $times = DB::table("time_type")->where('t_type',1)->first();
            if(!$times || $now<$times['tstart_time'] || $now>$times['tend_time']){
                //$_POST['sys_num']=$_GET['sys_num'];
                $this->manual($sys_num);
				//$this->inserting_log("系统派单，",$_POST['sys_num'],'非自动派单时段',"订单管理");//日志、
				$this->inserting_log("系统派单，",$sys_num,'非自动派单时段',"订单管理",$ip,$admin_acc);//日志
				exit;
                $goods_brand = DB::table("order_msg")->where('sys_num',$sys_num)->select('goods_brand','goods_id')->groupBy("goods_brand")->get()->toArray();
                if(count($goods_brand)>1){
                    $this->manual($sys_num);
                    $this->inserting_log("系统派单，",$sys_num,'包含品牌大于一个',"订单管理",$ip,$admin_acc);//日志
                }else{
                    $good_id=['307','429','241','242','243','275','286','440','482','481','480','241','242','275'];
                    //$good_id=$goods_brand[0]['goods_id'];
                    if(in_array($goods_brand[0]['goods_id'],$good_id)){
                        $this->manual($sys_num);
                        $this->inserting_log("系统派单，",$sys_num,'综合售后,agm,ffs商品',"订单管理",$ip,$admin_acc);//日志
                    }else{
                        $order = DB::table("orders")->where('sys_num',$sys_num)->first();
                        $user = DB::table("user")->where('id',$order['new_customer_id'])->first();
                        $user_phone = DB::table("user")->where('shr_phone',$user['shr_phone'])->count();
                        if($user_phone>1){
                            $this->manual($sys_num);
                            $this->inserting_log("系统派单，",$sys_num,'非首次下单',"订单管理",$ip,$admin_acc);//日志
                        }else{
                            //dump($user);
                            $goodid=DB::table("goods_brand")->where('brand_name',$goods_brand[0]['goods_brand'])->value("id");
                            //echo $goodid;
                            if($order['p_id']=='133'){
                                $data=$this->addWorkOrder($order,$sys_num,'488',$order['new_customer_id'],'0',$goodid,$admin_acc,$admin_id);
                                $this->inserting_log("系统派单，",$sys_num,"订单，指定服务商".$data['msg'],"订单管理",$ip,$admin_acc);//日志
                            }else{
                                //$region=M("sdo2o_bluezp.region");
                                //$arcover=M("sdo2o_bluezp.arcover");
                                if(strstr($user['shr_sheng'],"市")){
                                    //$sheng=rtrim($user['shr_sheng'],'市');
                                    $sheng = str_replace("市","",$user['shr_sheng']);
                                }else{
                                    if(strstr($user['shr_sheng'],"东省")){
                                        $sheng=str_replace('东省','东',$user['shr_sheng']);
                                    }elseif(strstr($user['shr_sheng'],"东")){
                                        $sheng=$user['shr_sheng'];
                                    }else{
                                        //$sheng=rtrim($user['shr_sheng'],'省');
                                        $sheng = str_replace("省","",$user['shr_sheng']);
                                    }
                                }
                                $shr_sheng=DB::table('region')->whereRaw("reg_level=1 and (reg_name like '%".$user['shr_sheng']."%' or reg_alias like '%".$user['shr_sheng']."%' or reg_name like '%".$sheng."%')")->first();
                                if(isset($shr_sheng)){
                                    //$shi=rtrim($_POST['shi'],'市');
                                    if(strstr($user['shr_shi'],"东市")){
                                        $shi=str_replace('东市','东',$user['shr_shi']);
                                    }elseif(strstr($user['shr_shi'],"东")){
                                        $shi=$user['shr_shi'];
                                    }else{
                                        //$shi=rtrim($user['shr_shi'],'市');
                                        $shi = str_replace("市","",$user['shr_shi']);
                                    }
                                    $shengs = ['北京','上海','天津','重庆'];
                                    if(in_array($sheng,$shengs)){
                                        $shr_shi=DB::table('region')->whereRaw("reg_level=2 and (reg_name like '%".$user['shr_sheng']."%' or reg_alias like '%".$user['shr_sheng']."%' or reg_name like '%".$sheng."%') and reg_blnum='".$shr_sheng['reg_num']."'")->first();
                                    }else{
                                        $shr_shi=DB::table('region')->whereRaw("reg_level=2 and (reg_name like '%".$user['shr_shi']."%' or reg_alias like '%".$user['shr_shi']."%' or reg_name like '%".$shi."%') and reg_blnum='".$shr_sheng['reg_num']."'")->first();
                                    }
                                    if(isset($shr_shi)){
                                        //if(in_array($sheng,$shengs)){
                                            $shr_xian=DB::table('region')->whereRaw("reg_level=3 and (reg_name like '%".$user['shr_xian']."%' or reg_alias like '%".$user['shr_xian']."%') and reg_blnum='".$shr_shi['reg_num']."'")->first();
                                            if(!empty($shr_xian)){
                                                $dress = Disareanew::whereRaw("are_shid='".$shr_sheng['reg_id']."' and are_xid='".$shr_xian['reg_id']."'")->first();
                                                $xian=1;
                                            }else{
	                                            $dress = Disareanew::where(['are_shid'=>$shr_sheng['reg_id'], 'are_sid'=>$shr_shi['reg_id']])->first();
                                            	$xian=2;
                                            }
                                        //}else{
                                        //    $dress = Disareanew::whereRaw("are_shid='".$shr_sheng['reg_id']."' and are_sid='".$shr_shi['reg_id']."'")->first();
                                        //    $xian=2;
                                        //}
                                        //$dress=M("disarea")->where("are_shid='".$shr_sheng['reg_id']."' and are_sid='".$shr_shi['reg_id']."'")->find();
                                        if(isset($dress)){
                                            if($goodid=='2' && $user['shr_shi']!='成都' && $user['shr_shi']!='成都市' && $user['shr_shi']!='南京' && $user['shr_shi']!='南京市'){
                                                $serPro=DB::table('arcover')->where('arc_shid',$shr_shi['reg_id'])->select('arc_serid')->groupBy('arc_serid')->get()->toArray();
                                                if (empty($serPro)){
                                                    $data['code']='2';
                                                }else{
	                                                $admin_id="";
	                                                foreach($serPro as $k=>$v){
	                                                    $admin_id.=$v['arc_serid'].",";
	                                                }
	                                                $admin_id=trim($admin_id,",");
	                                                $admin_id=$admin_id;

	                                                $list=DB::table("admin")->whereRaw("is_lidao=2 and enable=1 and id in (".$admin_id.")")->select('id','company_name','owner','children_id')->get()->toArray();// and owner=2
	                                                //$list=M("admin")->where("enable=1 and id in (".$admin_id.")")->field("id,company_name,owner,children_id")->select();
	                                                $end = $this->jingwei($user['shr_sheng'],$user['shr_sheng'].$user['shr_shi'].$user['shr_xian'].$user['shr_adress']);
	                                                //echo $end;
	                                                if(!empty($list) && !empty($end)){
	                                                    foreach( $list as $k2 => $v2 ){
	                                                        $admin_ids[]=$v2['id'];
	                                                        if($v2['owner']=='1' && $v2['children_id']!=''){
	                                                            $children_id[]=$v2['children_id'];
	                                                        }
	                                                    }
	                                                    $admin_ids=implode(',',$admin_ids);
	                                                    if(isset($children_id)){
	                                                        $children_id=implode(',',$children_id);
	                                                        $children=DB::table("admin_infor")->whereRaw("admin_id in(".$children_id.") and admin_province like '".$sheng."%' and admin_city like '".$shi."%'")->select("admin_id")->get()->toArray();
	                                                        if(!empty($children)){
	                                                            foreach( $children as $kc => $vc ){
	                                                                $cadmin_id[]=$vc['admin_id'];
	                                                            }
	                                                            $cadmin_id=implode(',',$cadmin_id);
	                                                            $admin_ids=$admin_ids.','.$cadmin_id;
	                                                            $lists=DB::table("admin")->whereRaw("`id` in (".$cadmin_id.") and enable='1'")->orderBy('is_lidao' ,'DESC')->orderBy('is_sord','DESC')->select('id','company_name','is_lidao','owner','children_id')->get()->toArray();
	                                                        }
	                                                        if(isset($lists)){
	                                                            $list = array_merge($list,$lists);
	                                                        }
	                                                    }
	                                                    //dump($list);
	                                                    $admin_infor = DB::table('admin_infor')->whereRaw('admin_id in ('.$admin_ids.')')->select('admin_id','admin_longitude','admin_latitude','admin_province','admin_city','admin_county','admin_dressi')->get()->toArray();
	                                                    foreach($admin_infor as $key=>$val){
	                                                        $admin_list[$val['admin_id']] = $val;
	                                                    }
	                                                    $pcdp=array('499','865','866','867','878','879','880','921');
														foreach( $list as $ka => $va ){
															if(!in_array($va['id'],$pcdp)){
																$ypc[]=$va;
															}
														}
														$list=$ypc;
														if(!empty($list)){
		                                                    foreach ($list as $key => $value) {
		                                                        $adminInfo = $admin_list[$value['id']];
		                                                        //dump($adminInfo);
		                                                        if(empty($adminInfo['admin_longitude']) || empty($adminInfo['admin_latitude'])){
		                                                            $jingwei = $this->jingwei($adminInfo['admin_province'],$adminInfo['admin_dressi']);
		                                                            if(isset($jingwei)){
		                                                                $start []= $jingwei;
		                                                            }else{
		                                                                $start []="0,0";
		                                                            }
		                                                        }else{
		                                                            $start[]= $adminInfo['admin_longitude'].",".$adminInfo['admin_latitude'];
		                                                        }
		                                                    }
		                                                    //$start[1]="116.528581,39.806117";
		                                                    //exit;
		                                                    if(!empty($start) && !empty($end)){
		                                                        $start=implode('|',$start);
		                                                        $res = $this->juli($start,$end);
		                                                    }
		                                                    if(!isset($res)){
			                                                    $data['code']='2';
		                                                    }else{
			                                                    foreach( $list as $ki => $vi ){
			                                                       if(isset($res[$ki]['distance'])){
			                                                            $num[]=round($res[$ki]['distance']/1000,2);
			                                                            $list[$ki]['juli'] = round($res[$ki]['distance']/1000,2);
			                                                        }else{
				                                                        $num[]=10000;
			                                                            $list[$ki]['juli'] = '10000';
			                                                        }
			                                                    }
			                                                    array_multisort($num, SORT_NUMERIC ,SORT_ASC, $list);
			                                                    if($list[0]['juli']<8){
			                                                         if($xian==1){
						                                            	$ser=Bserviss::whereRaw("find_in_set('".$dress['are_id']."',bs_areid) and bs_branid='".$goodid."' and bs_status='1' and bs_serid='".$list[0]['id']."'")->first();
					                                            	}else{
						                                            	$ser=Bserviss::whereRaw("bs_sid='".$dress['are_sid']."' and bs_branid='".$goodid."' and bs_status='1' and bs_serid='".$list[0]['id']."'")->first();
					                                            	}
					                                            	if(isset($ser)){
						                                            	$data=$this->addWorkOrder($order,$sys_num,$list[0]['id'],$order['new_customer_id'],$ser['bs_id'],$goodid,$admin_acc,$admin_id);
					                                            	}else{
			                                                        	$data=$this->addWorkOrder($order,$sys_num,$list[0]['id'],$order['new_customer_id'],0,$goodid,$admin_acc,$admin_id);
		                                                        	}
			                                                        $this->inserting_log("系统派单，",$sys_num,"订单l".$data['msg'],"订单管理",$ip,$admin_acc);//日志
			                                                        //echo 41;
			                                                        $data['code']='1';
			                                                    }else{
				                                                  	$data['code']='2';
			                                                    }
		                                                    }
	                                                    }else{
		                                                    $data['code']='2';
	                                                    }
	                                                }else{
	                                                    $data['code']='2';
	                                                }
                                                }
                                            }else{
                                                $data['code']='2';
                                            }
                                            if($data['code']=='1'){
                                            }else{
                                            	if($xian==1){
	                                            	$ser=Bserviss::whereRaw("find_in_set('".$dress['are_id']."',bs_areid) and bs_branid='".$goodid."' and bs_status='1'")->get()->toArray();
                                            	}else{
	                                            	$ser=Bserviss::whereRaw("bs_sid='".$dress['are_sid']."' and bs_branid='".$goodid."' and bs_status='1'")->get()->toArray();
                                            	}
                                                //$ser=Bserviss::whereRaw("find_in_set('".$dress['are_id']."',bs_areid) and bs_branid='".$goodid."' and bs_status='1' and bs_allday='2'")->get()->toArray();
                                                if(!empty($ser)){
                                                    foreach( $ser as $ks => $vs ){
                                                        //最小派单量
                                                        $bs=$vs['bs_num']/$vs['bs_min'];
                                                        $vs['bs']=$bs;
                                                        if($bs<1){
                                                            $min[]=$vs;
                                                            $lasttime[]=strtotime($vs['bs_lastime']);
                                                            $minnum[]=$vs['bs_min'];
                                                            $minbl[]=$bs;
                                                        }
                                                    }
                                                    if(isset($min)){
                                                        array_multisort($minbl, SORT_NUMERIC ,SORT_ASC,$lasttime, SORT_NUMERIC ,SORT_ASC,$minnum, SORT_NUMERIC ,SORT_DESC, $min);
                                                        $datas=$this->addWorkOrder($order,$sys_num,$min[0]['bs_serid'],$order['new_customer_id'],$min[0]['bs_id'],$goodid,$admin_acc,$admin_id);
                                                        $this->inserting_log("系统派单，",$sys_num,"订单in".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                                                        //dump($min);
                                                        //echo 1;
                                                    }else{
                                                        foreach( $ser as $ks1 => $vs1 ){
                                                            $bs1=$vs1['bs_max']*$vs1['bs_satisfa']/100;
                                                            $vs1['satisfa']=$bs1;
                                                            if($bs1>$vs1['bs_num']){
                                                                $vs1['bl']=$vs1['bs_num']/$bs1;
                                                                $sati[]=$vs1;
                                                                $satisfa[]=$bs1;
                                                                $satibl[]=$vs1['bs_num']/$bs1;
                                                            }
                                                        }
                                                        if(isset($sati)){
                                                            array_multisort($satibl, SORT_NUMERIC ,SORT_ASC,$satisfa, SORT_NUMERIC ,SORT_DESC, $sati);
                                                            $datas=$this->addWorkOrder($order,$sys_num,$sati[0]['bs_serid'],$order['new_customer_id'],$sati[0]['bs_id'],$goodid,$admin_acc,$admin_id);
                                                            $this->inserting_log("系统派单，",$sys_num,"订单sa".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                                                            //dump($sati);
                                                            //echo 2;
                                                        }else{
                                                            foreach( $ser as $ks2 => $vs2 ){
                                                                $bs2=$vs2['bs_num']/$vs2['bs_max'];
                                                                $vs2['bs2']=$bs2;
                                                                if($bs2<1){
                                                                    $max[]=$vs2;
                                                                    $maxnum[]=$vs2['bs_max'];
                                                                    $maxbl[]=$bs2;
                                                                }
                                                            }
                                                            if(isset($max)){
                                                                array_multisort($maxbl, SORT_NUMERIC ,SORT_ASC,$maxnum, SORT_NUMERIC ,SORT_DESC, $max);
                                                                $datas=$this->addWorkOrder($order,$sys_num,$max[0]['bs_serid'],$order['new_customer_id'],$max[0]['bs_id'],$goodid,$admin_acc,$admin_id);
                                                                $this->inserting_log("系统派单，",$sys_num,"订单ax".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                                                                //dump($max);
                                                                //echo 3;
                                                            }else{
                                                                foreach( $ser as $ks3 => $vs3 ){
                                                                    $bs3=$vs3['bs_num']-$vs3['bs_max'];
                                                                    $vs3['bs3']=$bs3;
                                                                    $maxs[]=$vs3;
                                                                    $maxsnum[]=$bs3;
                                                                    $maxsmax[]=$vs3['bs_max'];
                                                                }
                                                                array_multisort($maxsnum, SORT_NUMERIC ,SORT_ASC,$maxsmax, SORT_NUMERIC ,SORT_DESC, $maxs);
                                                                $datas=$this->addWorkOrder($order,$sys_num,$maxs[0]['bs_serid'],$order['new_customer_id'],$maxs[0]['bs_id'],$goodid,$admin_acc,$admin_id);
                                                                $this->inserting_log("系统派单，",$sys_num,"订单p".$datas['msg'],"订单管理",$ip,$admin_acc);//日志

                                                            }
                                                        }
                                                    }
                                                    if($datas['code']!='1'){
                                                        $this->manual($sys_num);
                                                        //echo "手动派单";
                                                    }
                                                }else{
                                                    $this->manual($sys_num);
                                                    $this->inserting_log("系统派单，",$sys_num,'未匹配到服务商',"订单管理",$ip,$admin_acc);//日志
                                                }
                                            }
                                        }else{
                                            $this->manual($sys_num);
                                            $this->inserting_log("系统派单，",$sys_num,'未匹配到地址',"订单管理",$ip,$admin_acc);//日志
                                            //echo "手动派单";
                                        }
                                    }else{
                                        $this->manual($sys_num);
                                        $this->inserting_log("系统派单，",$sys_num,'未匹配到城市信息',"订单管理",$ip,$admin_acc);//日志
                                        //echo "手动派单";
                                    }
                                }else{
                                    $this->manual($sys_num);
                                    $this->inserting_log("系统派单，",$sys_num,'未匹配到省份信息',"订单管理",$ip,$admin_acc);//日志
                                    //echo "手动派单";
                                }
                            }
                        }
                    }
                }
            }else{
                //$_POST['sys_num']=$_GET['sys_num'];
                $goods_brand = DB::table("order_msg")->where('sys_num',$sys_num)->select('goods_brand','goods_id')->groupBy("goods_brand")->get()->toArray();
                if(count($goods_brand)>1){
                    //echo "手动派单";
                    $this->manual($sys_num);
                    $this->inserting_log("系统派单，",$sys_num,'包含品牌大于一个',"订单管理",$ip,$admin_acc);//日志
                    //$flag='4';
                }else{
                    $good_id = ['307','429','241','242','243','275','286','440','482','481','480','241','242','275'];
                    //$good_id=$goods_brand[0]['goods_id'];
                    if(in_array($goods_brand[0]['goods_id'],$good_id)){
                        $this->manual($sys_num);
                        $this->inserting_log("系统派单，",$sys_num,'综合售后,AGM,FFS商品',"订单管理",$ip,$admin_acc);//日志
                    }else{
                        $order = DB::table("orders")->where('sys_num',$sys_num)->first();
                        if($order['p_id']=='149' || $order['p_id']=='151'){
	                        $this->manual($sys_num);
                        	$this->inserting_log("系统派单，",$sys_num,'平安保险服务',"订单管理",$ip,$admin_acc);//日志
                        }else if($order['p_id']=='81'){
							$this->manual($sys_num);
                        	$this->inserting_log("系统派单，",$sys_num,'演示订单',"订单管理",$ip,$admin_acc);//日志

	                    }else{
	                        //return $order;exit;
	                        $user = DB::table("user")->where('id',$order['new_customer_id'])->first();
	                        $user_phone = DB::table("user")->where('shr_phone',$user['shr_phone'])->count();
	                        if($user_phone>1){
	                            $this->manual($sys_num);
	                            $this->inserting_log("系统派单，",$sys_num,'非首次下单',"订单管理",$ip,$admin_acc);//日志
	                        }else{
	                            $goodid=DB::table("goods_brand")->where('brand_name',$goods_brand[0]['goods_brand'])->value("id");
	                            if(($order['p_id']=='44' || $order['p_id']=='122') && $goodid==4){
									$data=$this->addWorkOrder($order,$sys_num,'1695',$order['new_customer_id'],'0',$goodid,$admin_acc,$admin_id);
									if($data['code']=='1'){
										$this->inserting_log("系统派单，",$sys_num,'风帆自动派单成功',"订单管理",$ip,$admin_acc);//日志
										return;
									}else{
										$this->inserting_log("系统派单，",$sys_num,"风帆自动派单，".$data['msg'],"订单管理",$ip,$admin_acc);//日志
										return;
									}
								}else{
		       //                     if(($user['shr_shi']=='南京' || $user['shr_shi']=='南京市') && $goodid==2){
									//	$ends = $this->jingwei($user['shr_sheng'],$user['shr_sheng'].$user['shr_shi'].$user['shr_xian'].$user['shr_adress']);
									//	if(!empty($ends)){
									//		$ends=explode(',',$ends);
									//		$bd_encrypt=$this->bd_encrypt($ends[0], $ends[1]);
									//		$point=[
									//			'lng'=>$bd_encrypt['bd_lon'],
									//			'lat'=>$bd_encrypt['bd_lat']
									//		];
									//		$conser=DB::select("SELECT cc_coordinate,sc_serid FROM gone_cover_ser as a LEFT JOIN gone_cover_coordinate as b on a.sc_num=b.cc_num WHERE FIND_IN_SET('江苏省',sc_sheng) and  sc_state=1 and sc_serid!=0");
									//		$con_ser='';
									//		if(!empty($conser)){
									//			foreach( $conser as $k => $v ){
									//				$a= $this->is_point_in_polygon($point, json_decode($v['cc_coordinate'],true));
									//				if(!empty($a)){
									//					$con_ser=$v['sc_serid'];
									//					break;
									//				}
									//			}
									//		}
									//		if($con_ser!=''){
									//			//$con_ser="585";
									//			$install=DB::table("install_person")->whereRaw("(admin_id='".$con_ser."' or company_id='".$con_ser."') and delet_y=1 and install_state=1 and install_is_type=1 and is_shman=2")->select('id','check_code','install_name','install_phone','bind')->first();
									//			if(!empty($install)){
									//				$data=$this->addWorkOrder($order,$sys_num,$con_ser,$order['new_customer_id'],'0',$goodid,$admin_acc,$admin_id,$install);
									//				if($data['code']=='1'){
									//					$this->inserting_log("系统派单，",$sys_num,'电子围栏寻单成功',"订单管理",$ip,$admin_acc);//日志
									//					return;
									//				}else{
									//					$this->inserting_log("系统派单，",$sys_num,"电子围栏，".$data['msg'],"订单管理",$ip,$admin_acc);//日志
									//				}
									//			}else{
									//				$this->inserting_log("系统派单，",$sys_num,"电子围栏，未匹配到指定技师","订单管理",$ip,$admin_acc);//日志
									//			}
									//		}else{
									//			$this->inserting_log("系统派单，",$sys_num,"电子围栏，未匹配到对应服务商","订单管理",$ip,$admin_acc);//日志
									//		}
									//	}else{
									//		$this->inserting_log("系统派单，",$sys_num,"电子围栏，未匹配到对应客户坐标","订单管理",$ip,$admin_acc);//日志
									//	}
									//}
		                            if($order['p_id']=='133'){
		                                $data=$this->addWorkOrder($order,$sys_num,'488',$order['new_customer_id'],'0',$goodid,$admin_acc,$admin_id);
		                                $this->inserting_log("系统派单，",$sys_num,"订单，指定服务商".$data['msg'],"订单管理",$ip,$admin_acc);//日志
		                            }else{
		                                if(strstr($user['shr_sheng'],"市")){
		                                    //$sheng=rtrim($user['shr_sheng'],'市');
		                                    $sheng = str_replace("市","",$user['shr_sheng']);
		                                }else{
		                                    if(strstr($user['shr_sheng'],"东省")){
		                                        $sheng=str_replace('东省','东',$user['shr_sheng']);
		                                    }elseif(strstr($user['shr_sheng'],"东")){
		                                        $sheng=$user['shr_sheng'];
		                                    }else{
		                                        //$sheng=rtrim($user['shr_sheng'],'省');
		                                        $sheng = str_replace("省","",$user['shr_sheng']);
		                                    }
		                                }
		                                //DB::connection()->enableQueryLog();
		                                $shr_sheng = DB::table('region')->whereRaw("reg_level=1 and (reg_name like '%".$user['shr_sheng']."%' or reg_alias like '%".$user['shr_sheng']."%' or reg_name like '%".$sheng."%')")->first();
		                                //return $shr_sheng;exit;
		                                if(isset($shr_sheng)){
		                                    //$shi=rtrim($_POST['shi'],'市');
		                                    if(strstr($user['shr_shi'],"东市")){
		                                        $shi=str_replace('东市','东',$user['shr_shi']);
		                                    }elseif(strstr($user['shr_shi'],"东")){
		                                        $shi=$user['shr_shi'];
		                                    }else{
		                                        //$shi=rtrim($user['shr_shi'],'市');
		                                        $shi = str_replace("市","",$user['shr_shi']);
		                                    }
		                                    $shengs = ['北京','上海','天津','重庆'];
		                                    if(in_array($sheng,$shengs)){
		                                        $shr_shi=DB::table('region')->whereRaw("reg_level=2 and (reg_name like '%".$user['shr_sheng']."%' or reg_alias like '%".$user['shr_sheng']."%' or reg_name like '%".$sheng."%') and reg_blnum='".$shr_sheng['reg_num']."'")->first();
		                                    }else{
		                                        $shr_shi=DB::table('region')->whereRaw("reg_level=2 and (reg_name like '%".$user['shr_shi']."%' or reg_alias like '%".$user['shr_shi']."%' or reg_name like '%".$shi."%') and reg_blnum='".$shr_sheng['reg_num']."'")->first();
		                                        //return $shr_shi;exit;
		                                    }
		                                    if(isset($shr_shi)){
		                                        //if(in_array($sheng,$shengs)){
		                                            $shr_xian = DB::table('region')->whereRaw("reg_level=3 and (reg_name like '%".$user['shr_xian']."%' or reg_alias like '%".$user['shr_xian']."%') and reg_blnum='".$shr_shi['reg_num']."'")->first();
		                                            if(!empty($shr_xian)){
		                                                $dress = Disareanew::where(['are_shid'=>$shr_sheng['reg_id'], 'are_xid'=>$shr_xian['reg_id']])->first();
		                                                $xian=1;
		                                            }else{
			                                            $dress = Disareanew::where(['are_shid'=>$shr_sheng['reg_id'], 'are_sid'=>$shr_shi['reg_id']])->first();
		                                            	$xian=2;
		                                            }
		                                        //}else{
		                                        //    $dress = Disareanew::where(['are_shid'=>$shr_sheng['reg_id'], 'are_sid'=>$shr_shi['reg_id']])->first();
		                                        //    $xian=2;
		                                        //    //return $dress;exit;
		                                        //}
		                                        //$dress=M("disarea")->where("are_shid='".$shr_sheng['reg_id']."' and are_sid='".$shr_shi['reg_id']."'")->find();
		                                        if(isset($dress)){
		                                            //if($goodid=='2' && $user['shr_shi']!='成都' && $user['shr_shi']!='成都市' && $user['shr_shi']!='南京' && $user['shr_shi']!='南京市'){
		              //                              if($goodid=='2'){
		              //                                  $serPro = DB::table('arcover')->where('arc_shid',$shr_shi['reg_id'])->select('arc_serid')->groupBy('arc_serid')->get()->toArray();
		              //                                  if (empty($serPro)){
		              //                                      $data['code']='2';
		              //                                  }else{
			             //                                   $admin_id="";
			             //                                   foreach($serPro as $k=>$v){
			             //                                       $admin_id.=$v['arc_serid'].",";
			             //                                   }
			             //                                   $admin_id = trim($admin_id,",");
			             //                                   if (isset($admin_id)){
			             //                                       $admin_id = $admin_id.","."585";
			             //                                   }else{
			             //                                       $admin_id = "585";
			             //                                   }

			             //                                   //echo $admin_id;
			             //                                   $list = DB::table("admin")->whereRaw("is_lidao=2 and enable=1 and id in (".$admin_id.")")->select('id','company_name','owner','children_id')->get()->toArray();

			             //                                   $end = $this->jingwei($user['shr_sheng'],$user['shr_sheng'].$user['shr_shi'].$user['shr_xian'].$user['shr_adress']);
			             //                                   //echo $end;
			             //                                   if(!empty($list) && !empty($end)){
			             //                                       foreach( $list as $k2 => $v2 ){
			             //                                           $admin_ids[]=$v2['id'];
			             //                                           if($v2['owner']=='1' && $v2['children_id']!=''){
			             //                                               $children_id[]=$v2['children_id'];
			             //                                           }
			             //                                       }
			             //                                       $admin_ids = implode(',',$admin_ids);
			             //                                       if(isset($children_id)){
			             //                                           $children_id = implode(',',$children_id);
			             //                                           $children = DB::table("admin_infor")->whereRaw("admin_id in(".$children_id.") and admin_province like '".$sheng."%' and admin_city like '".$shi."%'")->select("admin_id")->get()->toArray();
			             //                                           if(!empty($children)){
			             //                                               foreach( $children as $kc => $vc ){
			             //                                                   $cadmin_id[]=$vc['admin_id'];
			             //                                               }
			             //                                               $cadmin_id=implode(',',$cadmin_id);
			             //                                               $admin_ids=$admin_ids.','.$cadmin_id;
			             //                                               $lists=DB::table("admin")->whereRaw("`id` in (".$cadmin_id.") and enable='1' and is_lidao=2")->orderBy('is_lidao','DESC')->orderBy('is_sord','DESC')->select('id','company_name','is_lidao','owner','children_id')->get()->toArray();
			             //                                           }
			             //                                           if(isset($lists)){
			             //                                               $list = array_merge($list,$lists);
			             //                                           }else{

			             //                                           }
			             //                                       }
			             //                                       //dump($list);
			             //                                       $admin_infor = DB::table('admin_infor')->whereRaw('admin_id in ('.$admin_ids.')')->select('admin_id','admin_longitude','admin_latitude','admin_province','admin_city','admin_county','admin_dressi')->get()->toArray();
			             //                                       foreach($admin_infor as $key=>$val){
			             //                                           $admin_list[$val['admin_id']] = $val;
			             //                                       }
		              //                                       	$pcdp=array('499','865','866','867','878','879','880','921','820','684','843','844','849','853','892','1437','1439','1452');
																//foreach( $list as $ka => $va ){
																//	if(!in_array($va['id'],$pcdp)){
																//		$ypc[]=$va;
																//	}
																//}
																//$list=$ypc;
																//if(!empty($list)){
				            //                                        foreach ($list as $key => $value) {
				            //                                            $adminInfo = $admin_list[$value['id']];
				            //                                            //dump($adminInfo);
				            //                                            if(empty($adminInfo['admin_longitude']) || empty($adminInfo['admin_latitude'])){
				            //                                                $jingwei = $this->jingwei($adminInfo['admin_province'],$adminInfo['admin_dressi']);
				            //                                                if(isset($jingwei)){
				            //                                                    $start []= $jingwei;
				            //                                                }else{
				            //                                                    $start []="0,0";
				            //                                                }
				            //                                            }else{
				            //                                                $start[ ]= $adminInfo['admin_longitude'].",".$adminInfo['admin_latitude'];
				            //                                            }
				            //                                        }
				            //                                        //$start[1]="116.528581,39.806117";
				            //                                        //exit;
				            //                                        if(!empty($start) && !empty($end)){
				            //                                            $start=implode('|',$start);
				            //                                            $res = $this->juli($start,$end);
				            //                                        }
				            //                                        if (!isset($res)){
				            //                                             $data['code']='2';
				            //                                        }else{
					           //                                         foreach( $list as $ki => $vi ){
						          //                                         if(isset($res[$ki]['distance'])){
					           //                                                 $num[]=round($res[$ki]['distance']/1000,2);
					           //                                                 $list[$ki]['juli'] = round($res[$ki]['distance']/1000,2);
					           //                                             }else{
						          //                                              $num[]=10000;
					           //                                                 $list[$ki]['juli'] = '10000';
					           //                                             }
					           //                                         }
					           //                                         array_multisort($num, SORT_NUMERIC ,SORT_ASC, $list);
					           //                                         if($list[0]['juli']<8){
						          //                                           if($xian==1){
								        //                                    	$ser=Bserviss::whereRaw("find_in_set('".$dress['are_id']."',bs_areid) and bs_branid='".$goodid."' and bs_status='1' and bs_serid='".$list[0]['id']."'")->first();
							         //                                   	}else{
								        //                                    	$ser=Bserviss::whereRaw("bs_sid='".$dress['are_sid']."' and bs_branid='".$goodid."' and bs_status='1' and bs_serid='".$list[0]['id']."'")->first();
							         //                                   	}
							         //                                   	if(isset($ser)){
								        //                                    	$data=$this->addWorkOrder($order,$sys_num,$list[0]['id'],$order['new_customer_id'],$ser['bs_id'],$goodid,$admin_acc,$admin_id);
							         //                                   	}else{
					           //                                             	$data=$this->addWorkOrder($order,$sys_num,$list[0]['id'],$order['new_customer_id'],0,$goodid,$admin_acc,$admin_id);
				            //                                            	}
					           //                                             $this->inserting_log("系统派单，",$sys_num,"订单l".$data['msg'],"订单管理",$ip,$admin_acc);//日志
					           //                                             //echo 41;
					           //                                              $data['code']='1';
					           //                                         }else{
						          //                                          $data['code']='2';
					           //                                         }
				            //                                        }
			             //                                       }else{
				            //                                        $data['code']='2';
				            //                                    }
			             //                                   }else{
			             //                                       $data['code']='2';
			             //                                   }
		              //                                  }
		              //                              }else{
		                                            //    $data['code']='2';
		                                            //}
		                                            $data['code']='2';
		                                            if($data['code']=='1'){
		                                                //$sql="update gone_bservis set bs_num=bs_num+1 where bs_serid='".$list[0]['id']."' and bs_areid='".$dress['are_id']."' and bs_branid='".$goodid."'";
		                                                //M()->query($sql);
		                                            }else{
			                                            if($xian==1){
			                                            	$ser=Bserviss::whereRaw("find_in_set('".$dress['are_id']."',bs_areid) and bs_branid='".$goodid."' and bs_status='1'")->get()->toArray();
		                                            	}else{
			                                            	$ser=Bserviss::whereRaw("bs_sid='".$dress['are_sid']."' and bs_branid='".$goodid."' and bs_status='1'")->get()->toArray();
		                                            	}
		                                                //$ser=Bserviss::where(['bs_areid'=>$dress['are_id'], 'bs_branid'=>$goodid,'bs_status'=>'1'])->get()->toArray();
		                                                if(!empty($ser)){
			                                                $time=date("Y-m-d H:i:s");
															if($time>'2021-02-08' && $time<'2020-02-17'){
																$activity=['1206','1388','1756','721','1706','744','1593','1177','869','1514','688','614','1180','1228','658','1669','1373','454','1253','603','947','526','774','1570','1026','1665','1655','1660','1019','1355','1661','638','661','1341','969','645','1365','873','449','1298','1357','265','1738','197','1377','1699','455','657','368','1654','639','633','1653','1216','1730','1656','753','1761','458','673','1201','1611','538','1360','1727','423','1156','1482','646','536','1340','1366','1324','703','1663','1501','1008','1016','282','1673','608','410','1629','582','1568','691','635','624','777','1334','1004','1006','966','1237','1637','543','529','560','1178','712','697','1776','564','1716','581','214','1660','578','1680','747','501','1132','428','436','651','905','778','926','697','656','479','1190','601','710','485','1486','1229','925','1675','713','428','269'];
																$sers=$ser;
																$sers1=[];
																$sers2=[];
																foreach( $sers as $k => $v ){
																	if(in_array($v['bs_serid'],$activity)){
																		$sers1[]=$v;
																	}else{
																		$sers2[]=$v;
																	}
																}
																if(!empty($sers1)){
																	$ser=$sers1;
				                                                    foreach( $ser as $ks => $vs ){
				                                                        //最小派单量
				                                                        $bs=$vs['bs_num']/$vs['bs_min'];
				                                                        $vs['bs']=$bs;
				                                                        if($bs<1){
				                                                            $min[]=$vs;
				                                                            //$lasttime[]=strtotime($vs['bs_lastime']);

				                                                            $minnum[]=$vs['bs_min'];
				                                                            $minbl[]=$bs;
				                                                        }
				                                                    }
				                                                    if(isset($min)){//SORT_NUMERIC ,SORT_ASC,$lasttime,
				                                                        array_multisort($minbl,  SORT_NUMERIC ,SORT_ASC,$minnum, SORT_NUMERIC ,SORT_DESC, $min);
				                                                        $datas=$this->addWorkOrder($order,$sys_num,$min[0]['bs_serid'],$order['new_customer_id'],$min[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                        $this->inserting_log("系统派单，",$sys_num,"订单in".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
				                                                        //dump($min);
				                                                        //echo 1;
				                                                    }else{
				                                                        foreach( $ser as $ks1 => $vs1 ){
				                                                            $bs1=$vs1['bs_max']*$vs1['bs_satisfa']/100;
				                                                            $vs1['satisfa']=$bs1;
				                                                            if($bs1>$vs1['bs_num']){
				                                                                $vs1['bl']=$vs1['bs_num']/$bs1;
				                                                                $sati[]=$vs1;
				                                                                $satisfa[]=$bs1;
				                                                                $satibl[]=$vs1['bs_num']/$bs1;
				                                                            }
				                                                        }
				                                                        if(isset($sati)){
				                                                            array_multisort($satibl, SORT_NUMERIC ,SORT_ASC,$satisfa, SORT_NUMERIC ,SORT_DESC, $sati);
				                                                            $datas=$this->addWorkOrder($order,$sys_num,$sati[0]['bs_serid'],$order['new_customer_id'],$sati[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                            $this->inserting_log("系统派单，",$sys_num,"订单sa".$datas['msg'],"订单管理",$admin_acc);//日志
				                                                            //dump($sati);
				                                                            //echo 2;
				                                                        }else{
				                                                            foreach( $ser as $ks2 => $vs2 ){
				                                                                $bs2=$vs2['bs_num']/$vs2['bs_max'];
				                                                                $vs2['bs2']=$bs2;
				                                                                if($bs2<1){
				                                                                    $max[]=$vs2;
				                                                                    $maxnum[]=$vs2['bs_max'];
				                                                                    $maxbl[]=$bs2;
				                                                                }
				                                                            }
				                                                            if(isset($max)){
				                                                                array_multisort($maxbl, SORT_NUMERIC ,SORT_ASC,$maxnum, SORT_NUMERIC ,SORT_DESC, $max);
				                                                                $datas=$this->addWorkOrder($order,$sys_num,$max[0]['bs_serid'],$order['new_customer_id'],$max[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                                $this->inserting_log("系统派单，",$sys_num,"订单ax".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
				                                                                //dump($max);
				                                                                //echo 3;
				                                                            }else{
				                                                                foreach( $ser as $ks3 => $vs3 ){
				                                                                    $bs3=$vs3['bs_num']-$vs3['bs_max'];
				                                                                    $vs3['bs3']=$bs3;
				                                                                    $maxs[]=$vs3;
				                                                                    $maxsnum[]=$bs3;
				                                                                    $maxsmax[]=$vs3['bs_max'];
				                                                                }
				                                                                array_multisort($maxsnum, SORT_NUMERIC ,SORT_ASC,$maxsmax, SORT_NUMERIC ,SORT_DESC, $maxs);
				                                                                $datas=$this->addWorkOrder($order,$sys_num,$maxs[0]['bs_serid'],$order['new_customer_id'],$maxs[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                                $this->inserting_log("系统派单，",$sys_num,"订单p".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
				                                                                //dump($maxs);
				                                                                //echo 4;
				                                                            }
				                                                        }
				                                                    }
			                                                    }else{
				                                                    $ser=$sers2;
				                                                    foreach( $ser as $ks => $vs ){
				                                                        //最小派单量
				                                                        $bs=$vs['bs_num']/$vs['bs_min'];
				                                                        $vs['bs']=$bs;
				                                                        if($bs<1){
				                                                            $min[]=$vs;
				                                                            //$lasttime[]=strtotime($vs['bs_lastime']);

				                                                            $minnum[]=$vs['bs_min'];
				                                                            $minbl[]=$bs;
				                                                        }
				                                                    }
				                                                    if(isset($min)){//SORT_NUMERIC ,SORT_ASC,$lasttime,
				                                                        array_multisort($minbl,  SORT_NUMERIC ,SORT_ASC,$minnum, SORT_NUMERIC ,SORT_DESC, $min);
				                                                        $datas=$this->addWorkOrder($order,$sys_num,$min[0]['bs_serid'],$order['new_customer_id'],$min[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                        $this->inserting_log("系统派单，",$sys_num,"订单in".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
				                                                        //dump($min);
				                                                        //echo 1;
				                                                    }else{
				                                                        foreach( $ser as $ks1 => $vs1 ){
				                                                            $bs1=$vs1['bs_max']*$vs1['bs_satisfa']/100;
				                                                            $vs1['satisfa']=$bs1;
				                                                            if($bs1>$vs1['bs_num']){
				                                                                $vs1['bl']=$vs1['bs_num']/$bs1;
				                                                                $sati[]=$vs1;
				                                                                $satisfa[]=$bs1;
				                                                                $satibl[]=$vs1['bs_num']/$bs1;
				                                                            }
				                                                        }
				                                                        if(isset($sati)){
				                                                            array_multisort($satibl, SORT_NUMERIC ,SORT_ASC,$satisfa, SORT_NUMERIC ,SORT_DESC, $sati);
				                                                            $datas=$this->addWorkOrder($order,$sys_num,$sati[0]['bs_serid'],$order['new_customer_id'],$sati[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                            $this->inserting_log("系统派单，",$sys_num,"订单sa".$datas['msg'],"订单管理",$admin_acc);//日志
				                                                            //dump($sati);
				                                                            //echo 2;
				                                                        }else{
				                                                            foreach( $ser as $ks2 => $vs2 ){
				                                                                $bs2=$vs2['bs_num']/$vs2['bs_max'];
				                                                                $vs2['bs2']=$bs2;
				                                                                if($bs2<1){
				                                                                    $max[]=$vs2;
				                                                                    $maxnum[]=$vs2['bs_max'];
				                                                                    $maxbl[]=$bs2;
				                                                                }
				                                                            }
				                                                            if(isset($max)){
				                                                                array_multisort($maxbl, SORT_NUMERIC ,SORT_ASC,$maxnum, SORT_NUMERIC ,SORT_DESC, $max);
				                                                                $datas=$this->addWorkOrder($order,$sys_num,$max[0]['bs_serid'],$order['new_customer_id'],$max[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                                $this->inserting_log("系统派单，",$sys_num,"订单ax".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
				                                                                //dump($max);
				                                                                //echo 3;
				                                                            }else{
				                                                                foreach( $ser as $ks3 => $vs3 ){
				                                                                    $bs3=$vs3['bs_num']-$vs3['bs_max'];
				                                                                    $vs3['bs3']=$bs3;
				                                                                    $maxs[]=$vs3;
				                                                                    $maxsnum[]=$bs3;
				                                                                    $maxsmax[]=$vs3['bs_max'];
				                                                                }
				                                                                array_multisort($maxsnum, SORT_NUMERIC ,SORT_ASC,$maxsmax, SORT_NUMERIC ,SORT_DESC, $maxs);
				                                                                $datas=$this->addWorkOrder($order,$sys_num,$maxs[0]['bs_serid'],$order['new_customer_id'],$maxs[0]['bs_id'],$goodid,$admin_acc,$admin_id);
				                                                                $this->inserting_log("系统派单，",$sys_num,"订单p".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
				                                                                //dump($maxs);
				                                                                //echo 4;
				                                                            }
				                                                        }
				                                                    }
			                                                    }
			                                                    if($datas['code']!='1'){
			                                                        $this->manual($sys_num);
			                                                        //echo "手动派单";
			                                                    }
															}else{
			                                                    foreach( $ser as $ks => $vs ){
			                                                        //最小派单量
			                                                        $bs=$vs['bs_num']/$vs['bs_min'];
			                                                        $vs['bs']=$bs;
			                                                        if($bs<1){
			                                                            $min[]=$vs;
			                                                            //$lasttime[]=strtotime($vs['bs_lastime']);

			                                                            $minnum[]=$vs['bs_min'];
			                                                            $minbl[]=$bs;
			                                                        }
			                                                    }
			                                                    if(isset($min)){//SORT_NUMERIC ,SORT_ASC,$lasttime,
			                                                        array_multisort($minbl,  SORT_NUMERIC ,SORT_ASC,$minnum, SORT_NUMERIC ,SORT_DESC, $min);
			                                                        $datas=$this->addWorkOrder($order,$sys_num,$min[0]['bs_serid'],$order['new_customer_id'],$min[0]['bs_id'],$goodid,$admin_acc,$admin_id);
			                                                        $this->inserting_log("系统派单，",$sys_num,"订单in".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
			                                                        //dump($min);
			                                                        //echo 1;
			                                                    }else{
			                                                        foreach( $ser as $ks1 => $vs1 ){
			                                                            $bs1=$vs1['bs_max']*$vs1['bs_satisfa']/100;
			                                                            $vs1['satisfa']=$bs1;
			                                                            if($bs1>$vs1['bs_num']){
			                                                                $vs1['bl']=$vs1['bs_num']/$bs1;
			                                                                $sati[]=$vs1;
			                                                                $satisfa[]=$bs1;
			                                                                $satibl[]=$vs1['bs_num']/$bs1;
			                                                            }
			                                                        }
			                                                        if(isset($sati)){
			                                                            array_multisort($satibl, SORT_NUMERIC ,SORT_ASC,$satisfa, SORT_NUMERIC ,SORT_DESC, $sati);
			                                                            $datas=$this->addWorkOrder($order,$sys_num,$sati[0]['bs_serid'],$order['new_customer_id'],$sati[0]['bs_id'],$goodid,$admin_acc,$admin_id);
			                                                            $this->inserting_log("系统派单，",$sys_num,"订单sa".$datas['msg'],"订单管理",$admin_acc);//日志
			                                                            //dump($sati);
			                                                            //echo 2;
			                                                        }else{
			                                                            foreach( $ser as $ks2 => $vs2 ){
			                                                                $bs2=$vs2['bs_num']/$vs2['bs_max'];
			                                                                $vs2['bs2']=$bs2;
			                                                                if($bs2<1){
			                                                                    $max[]=$vs2;
			                                                                    $maxnum[]=$vs2['bs_max'];
			                                                                    $maxbl[]=$bs2;
			                                                                }
			                                                            }
			                                                            if(isset($max)){
			                                                                array_multisort($maxbl, SORT_NUMERIC ,SORT_ASC,$maxnum, SORT_NUMERIC ,SORT_DESC, $max);
			                                                                $datas=$this->addWorkOrder($order,$sys_num,$max[0]['bs_serid'],$order['new_customer_id'],$max[0]['bs_id'],$goodid,$admin_acc,$admin_id);
			                                                                $this->inserting_log("系统派单，",$sys_num,"订单ax".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
			                                                                //dump($max);
			                                                                //echo 3;
			                                                            }else{
			                                                                foreach( $ser as $ks3 => $vs3 ){
			                                                                    $bs3=$vs3['bs_num']-$vs3['bs_max'];
			                                                                    $vs3['bs3']=$bs3;
			                                                                    $maxs[]=$vs3;
			                                                                    $maxsnum[]=$bs3;
			                                                                    $maxsmax[]=$vs3['bs_max'];
			                                                                }
			                                                                array_multisort($maxsnum, SORT_NUMERIC ,SORT_ASC,$maxsmax, SORT_NUMERIC ,SORT_DESC, $maxs);
			                                                                $datas=$this->addWorkOrder($order,$sys_num,$maxs[0]['bs_serid'],$order['new_customer_id'],$maxs[0]['bs_id'],$goodid,$admin_acc,$admin_id);
			                                                                $this->inserting_log("系统派单，",$sys_num,"订单p".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
			                                                                //dump($maxs);
			                                                                //echo 4;
			                                                            }
			                                                        }
			                                                    }
			                                                    if($datas['code']!='1'){
			                                                        $this->manual($sys_num);
			                                                        //echo "手动派单";
			                                                    }
		                                                    }
		                                                    //自动派单结束
		                                                }else{
		                                                    $this->manual($sys_num);
		                                                    $this->inserting_log("系统派单，",$sys_num,'未匹配到服务商',"订单管理",$ip,$admin_acc);//日志
		                                                }
		                                            }
		                                        }else{
		                                            $this->manual($sys_num);
		                                            $this->inserting_log("系统派单，",$sys_num,'未匹配到地址',"订单管理",$ip,$admin_acc);//日志
		                                            //echo "手动派单";
		                                        }
		                                    }else{
		                                        $this->manual($sys_num);
		                                        $this->inserting_log("系统派单，",$sys_num,'未匹配到城市信息',"订单管理",$ip,$admin_acc);//日志
		                                    }
		                                }else{
		                                    $this->manual($sys_num);
		                                    $this->inserting_log("系统派单，",$sys_num,'未匹配到省份信息',"订单管理",$ip,$admin_acc);//日志
		                                }
		                            }
	                            }
	                        }
	                    }
                    }
                }
            }
        }
    }


    //手动派单
    public function manual ($sys_num)
    {
        $poss['distype']='3';
        DB::table('orders')->where('sys_num',$sys_num)->update($poss);
    }

    public function addWorkOrder ($orderinfo,$sys_num,$ser_id,$user_id,$are_id,$goodid,$admin_acc,$admin_id,$install=0)
    {
        if($orderinfo['order_status']==10){
        }else{
            //$this->error("派单失败，该订单状态不正确，请刷新核实！");exit;
            $data['code']=2;
            $data['msg']="派单失败，该订单状态不正确，请刷新核实！";
            return $data;
            exit;
        }
        //if($are_id!='0'){
        //    $sql="update gone_bservisnew set bs_num=bs_num+1,bs_lastime='".date('Y-m-d H:i:s')."' where bs_serid='".$ser_id."' and bs_id='".$are_id."' and bs_branid='".$goodid."'";
        //    //M()->query($sql);
        //    DB::update($sql);
        //}
        //$data['code']=1;
        //$data['msg']="派单成功";
        //return $data;
        /*$user=M('user');
        $order_msg=M("order_msg");
        $order_list=M("order_list");
        $management=M("management");
        $order_time=M("order_time");
        $ser_time=M("ser_time");
        $admin_infor=M("admin_infor");*/
        // 绑定状态1.否2.是
        $binds=DB::table('admin_infor')->where('admin_id',$ser_id)->value("bind");

        $ordermsginfo=DB::table('order_msg')->where('sys_num',$sys_num)->whereNotIn('goods_service',[2,3])->select('id','goods_brand','goods_id','goods_name','goods_num')->get()->toArray();
        if(isset($orderinfo) && isset($ordermsginfo)){
            //养车宝
            if($orderinfo['p_id']==67){
                $date=date("Y-m-d H:i:s");
                $sign=md5("sudian".$orderinfo['order_num']);
                // $url='http://218.247.224.50/yangchebao-app-ws/ws/0.1/battery/deal/notify';//测试环境
                $url='http://app.yangchebao.com.cn/yangchebao-app-ws/ws/0.1/battery/deal/notify';//生产环境
                $ParArray = array("orderNumber" => $orderinfo['order_num'],"orderStatus" => "2","serviceTime" => $date,"remarks" => "","sign" => $sign);
                $ParArray = json_encode($ParArray);
                $resp = $this->request_posts($url,$ParArray);
                $obj=json_decode($resp,true);
                if($obj['result']=='success'){
                }else{
                    //$this->error("通知养车宝失败！请刷新核实！");exit;
                    $data['code']=2;
                    $data['msg']="通知养车宝失败！请刷新核实！";
                    return $data;
                    exit;
                }
                //汽车超人
            }else if($orderinfo['p_id']==70){
                // $url='http://testcs.qichechaoren.com/sdkb/fforder.jhtml';//测试环境
                $url='http://www.qccr.com/sdkb/fforder.jhtml';//生产环境
                $ParArray = array("sign" => "955e3c9f7c9d250e97dd55b329a1e223","no" => $orderinfo['order_num'],"status" => "1");
                $ParArray = json_encode($ParArray);
                $Post_Data['param']=$ParArray;
                $resp = $this->curl($url, $Post_Data);
            }else if ($orderinfo['p_id']==86){
                //乐车邦
                //$url='https://m3.lechebang.cn/gateway/open_api';//测试环境
                $url='https://m.lechebang.com/gateway/open_api';//生产环境
                $time=time();
                $sign="apiName=lcb.renewalBatteryOrder.status.change&appCode=9001&orderNum=".$orderinfo['order_num']."&processStatus=3&timestamp=".$time."Hc3hznL9DKbxzTtW7nrpVlam3CCAnpN0";
                $sign=md5($sign);
                $sign=strtoupper($sign);
                $ParArray = array("appCode" => "9001","timestamp" =>$time ,"signMethod" => "md5","apiName" => "lcb.renewalBatteryOrder.status.change","sign" => $sign,"processStatus" => "3","orderNum" => $orderinfo['order_num']);
                $ParArray = json_encode($ParArray);
                $resp = $this->https_post($url,$ParArray);
                $obj=json_decode($resp,true);
                //$lcb_erro=M("lcb_erro");
                $possl['le_data']=$ParArray."-".$resp;
                $possl['le_num']=$orderinfo['order_num'];
                DB::table('lcb_erro')->insert($possl);
                if($obj['statusCode']=='200'|| $obj['statusCode']=='14022'){
                }else{

                    //$this->error("通知乐车邦失败！请刷新核实！");exit;
                    $data['code']=2;
                    $data['msg']="通知乐车邦失败！请刷新核实！";
                    return $data;
                    exit;
                }
            }else if($orderinfo['p_id']==102){
                //$url='http://dev.liyingtong.com/battery/statusCallBack';//测试环境
                //$url='http://mo2o.sudianwang.com/index.php/Ceshi/post';//测试环境
                $url='http://biz.liyingtong.com/battery/statusCallBack';//生产环境
                $ParArray = array("orderId" => $orderinfo['order_num'],"status" => "14");
                $ParArrays = json_encode($ParArray);
                $resp = $this->post_form($url, $ParArray);
                $obj=json_decode($resp,true);

                //$lcb_erro=M("lcb_erro");
                $possl['le_data']=$ParArrays."-".$resp;
                $possl['le_num']=$orderinfo['order_num'];
                DB::table('lcb_erro')->insert($possl);
                if($obj['responseCode']=='2000' || $obj['responseCode']=='4000'){
                }else{

                    //$this->error("通知畅通车友失败！请刷新核实！");exit;
                    $data['code']=2;
                    $data['msg']="通知畅通车友失败！请刷新核实！";
                    return $data;
                    exit;

                }
            }
            $shr_phone=DB::table('user')->where('id',$user_id)->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();//手机号
            if($ser_id=="617"){
                //$pj_brand=M("pj_brand");
                //$settlement_list=M("settlement_list");
               // $settlement_money=M("settlement_money");
                $luot[0]['orderid']=$orderinfo['order_num'];//系统单号
                $luot[0]['orderstatus']="20";//订单状态
                $luot[0]['ordername']="";//订单名称
                $luot[0]['addtime']=$orderinfo['create_time'];//下单时间
                $luot[0]['paytime']=$orderinfo['create_time'];//支付时间

                $luot[0]['deliveraddr']=$shr_phone['shr_sheng'].$shr_phone['shr_shi'].$shr_phone['shr_xian'].$shr_phone['shr_adress'];//收货地址
                $luot[0]['delivermobile']=$shr_phone['shr_phone'];//收货人手机号

                //$note=M("note");
                $luot[0]['delivername']=$shr_phone['shr_name'];//收货人姓名
                $note_content = DB::table('note')->where(['orders_id'=>$sys_num,'note_type'=>"客户留言"])->value('note_content');//收货人备注
                if($orderinfo['order_type']==1){
                    $luot[0]['ordermsg']="";
                }else{
                    $luot[0]['ordermsg']="一小时加急；";
                }
                if(isset($note_content)){
                    $luot[0]['ordermsg']=$luot[0]['ordermsg'].$note_content;//收货人备注
                }else{
                    $luot[0]['ordermsg']=$luot[0]['ordermsg'];
                }

                //$gh_price=M("gh_price");
                $new_money=0;
                //$luot_data=M("luot_data");
                $l_data = DB::table('luot_data')->select('lud_goodid','lud_sku','lud_cpgg')->first();
                if(isset($l_data)){

                }else{
                    //$this->error("骆驼对接无该条数据！");exit;
                    $data['code']=2;
                    $data['msg']="骆驼对接无该条数据";
                    return $data;
                    exit;
                }
                foreach( $ordermsginfo as $kg => $vg ){
                    $price[$vg['id']]=DB::table('gh_price')->where(['goods_id'=>$vg['goods_id'],'ser_id'=>617])->value('supply_price');
                    if($price[$vg['id']]){

                    }else{
                        $price[$vg['id']]=0;
                    }
                    $good_list[$kg]['goodsid']=$l_data[$vg['goods_id']]['lud_sku']."_".$l_data[$vg['goods_id']]['lud_cpgg'];
                    $good_list[$kg]['goodsname']=$vg['goods_name'];
                    $good_list[$kg]['count']='1';//$vg['count(1)'];
                    $good_list[$kg]['price']=$price[$vg['id']];
                    $new_money=$price[$vg['id']]+$new_money;
                }
                $luot[0]['totalprice']=$new_money;//订单金额
                $luot[0]['shipprice']="0";//配送费用
                $luot[0]['goodsprice']=$new_money;//商品费用
                $luot[0]['payprice']=$new_money;//实付金额
                $luot[0]['couponsprice']="0";//优惠金额
                $luot[0]['goods']=$good_list;//收货人姓名
                $url='http://order.autocamel.com/api/order.htm';//正式
                //$url='http://www.kaiyitech.com/baseweb/api/order.htm';//生产环境测试
                //$url='http://zhanlijuan.imwork.net:54912/baseweb/api/order.htm';//测试环境
                $ParArray=array("cid" => "123.56.102.226","uid" => "LANCHENG","sid"=>"orderpush","stat"=>"0","rmk"=>"","ver"=>"1","biz"=>$luot);
                $ParArray = json_encode($ParArray);
                $resp = $this->request_posts($url,$ParArray);
                $obj=json_decode($resp,true);
                //dump($obj);
                //exit;
                if($obj['biz']['data'][0]['status']=='0'){
                    //$luotuo_error=M('luotuo_error');
                    $poss['le_error']=$ParArray;
                    $poss['le_ltero']=$resp;
                    $poss['le_number']=$orderinfo['order_num'];
                    DB::table('luotuo_error')->insert($poss);
                }else{
                    //$luotuo_error=M('luotuo_error');
                    $poss['le_error']=$ParArray;
                    $poss['le_ltero']=$resp;
                    $poss['le_number']=$orderinfo['order_num'];
                    DB::table('luotuo_error')->insert($poss);
                    //$this->error("通知骆驼安装失败！");exit;
                    $data['code']=2;
                    $data['msg']="通知骆驼安装失败";
                    return $data;
                    exit;
                }
                $post['ser_id']=$ser_id;//服务中心id
                $post['order_status']=30;//订单状态
                $post['intall_person']="骆驼客服";//安装人姓名
                $post['intall_phone']="4001899507";//安装人电话
            }else{
	            if($install=='0'){
	                $post['ser_id']=$ser_id;//服务中心id
	                $post['order_status']=20;//已派单
	                $relation['order_state']=20;
                }else{
	                $pj_brand=DB::table("goods_brand");
					$gh_price=DB::table("gh_price");
					$settlement_list=DB::table("settlement_list");
					$settlement_money=DB::table("settlement_money");
					$post['ser_id']=$ser_id;//服务中心id
					$post['order_status']=30;//订单状态
					$post['intall_person']=$install['install_name'];//安装人姓名
					$post['intall_phone']=$install['install_phone'];//安装人电话
					$relation['order_state']=30;
					$relation['install_id']=$install['id'];
					$relation['acceptance_time']=date("Y-m-d H:i:s");
                }
            }
            //$inventory=M("inventory");
            //$order_visit=M("order_visit");
            $push_type=1;
            $serid = DB::table('admin')->whereRaw("FIND_IN_SET(" .$ser_id. ",children_id)")->value('id');
            foreach($ordermsginfo as $k=>$v){
                //order_goods_id-关联msg_id
                $orderlistIds=DB::table('order_list')->where('sys_num',$sys_num)->where('order_goods_id',$v['id'])->value("category");
                if(isset($orderlistIds)){
                    //$this->inserting_log("系统派单，",$_POST['sys_num'],"订单重复派单","订单管理");//日志
                    //$this->error("派单失败，该订单已被派单，请刷新核实！");exit;
                    $data['code']=2;
                    $data['msg']="派单失败，该订单已被派发";
                    return $data;
                    exit;
                }
                $number='P'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                /***追溯****/
                $arr['trace_code'] =$number;//追溯码
                $arr['code']="http://weixin.sudianwang.com/index.php/Management/index?trace_code_select=".$number."&";//二维码

                /***派工单***/
                $get['stauas']=10;
                $get['serial_number']=$number;//派工单号
                $get['p_id']=$orderinfo['p_id'];//平台id
                $get['ser_id']=$ser_id;//服务中心id
                $get['sys_num']=$sys_num;//系统单号
                $get['order_num']=$orderinfo['order_num'];//平台编号
                $get['order_goods_id']=$v['id'];//关联msg_id
                $get['admin_id']=$admin_id??'1133';//创建人id
                $get['creater']=$admin_acc??'系统录入';//创建人
                $get['customer_id']=$user_id;//用户id
                $get['customer_phone']=$shr_phone['shr_phone'];//客户手机号
                $get['orli_type']=$orderinfo['order_type'];//订单类型
                $get['pay_typel']=$orderinfo['pay_type'];//支付方式
                //$timed=$ser_time->where("ser_id='".$_POST['ser_id']."'")->find();
                //if($timed){
                //}else{
                $timed=DB::table('ser_time')->where('ser_id',0)->first();
                //}
                $date_n=date("Y-m-d",strtotime("+1 day"));
                $date_s=date("H:i:s");
                //$date_s="16:35:00";
                if($date_s>$timed['start_time'] && $date_s<$timed['end_time']){
                    $payout_time=date("Y-m-d H:i:s");//接单奖罚起始计时时间
                }else{
                    if($date_s<$timed['start_time']){
                        $payout_time=date("Y-m-d")." ".$timed['start_time'];//接单奖罚起始计时时间
                    }else{
                        $payout_time=$date_n." ".$timed['start_time'];//接单奖罚起始计时时间
                    }
                }
                /***订单操作时间***/
                $this->operating_time($number,'下单时间',$orderinfo['create_time'],$orderinfo['order_num'],$admin_acc);//订单操作时间
                $this->operating_time($number,'派单时间',date("Y-m-d H:i:s"),$orderinfo['order_num'],$admin_acc);//订单操作时间
//                $this->operating_time($number,'起始时间',$payout_time,$orderinfo['order_num'],$admin_acc);//订单操作时间
                $this->add_thistory($number,'tih_crecttime',$payout_time,$ser_id,1);//添加历史时间
                if($install!='0'){
					$this->operating_time($number,'接单时间',date("Y-m-d H:i:s"),$orderinfo['order_num'],$admin_acc);//订单操作时间
					$set['sys_num']=$sys_num;//系统单号
					$set['order_num']=$orderinfo['order_num'];//平台编号
					$set['msg_id']=$v['id'];//关联msg_id
					$set['p_id']=$orderinfo['p_id'];//平台id
					$set['serial_number']='0';//派工单号
					$set['list_id']=$number;//派工单号
					$set['ser_id']=$ser_id;//服务中心id
					$set['type']="2";//服务中心id
					$set['installperson']=$install['id'];//安装人id
					$set['intall_person']=$install['install_name'];//安装人名称
					$set['intall_phone']=$install['install_phone'];//骆驼服务电话
					$price=$gh_price->whereRaw("goods_id='".$v['goods_id']."' and ser_id='0'")->value('supply_price');
					$set['order_price']=$price?$price:'0';//供货价
					$set['all_price']=$price?$price:'0';//总金额
					$set['sett_status']="1";//供货价
					$set['list_service_type']=30;
					$set['customer_id']=$user_id;//用户id
					$set['sel_type']=$orderinfo['order_type'];//订单类型
					$sem_slid=$settlement_list->insertGetid($set);//骆驼派单即等于接单
					//$sem_slid=1;
					if(!empty($sem_slid)){
						$money['sem_slid']=$sem_slid;
						$money['sem_synum']=$sys_num;
						$money['sem_price']=$price?$price:'0';
						$money['sem_creacter']="系统派单";
						$money['sem_type']=1;
						$settlement_money->insert($money);
						$support=DB::table("support");
						$tim=date("Y-m-d H:i:s");
						$sup_prices=$support->whereRaw("sup_serid like '%,".$user_id.",%' and sup_brname='".$v['goods_brand']."' and sup_startime<'".$tim."' and sup_endtime>'".$tim."'")->select('sup_price','sup_type','sup_goodids')->first();
						if(!empty($sup_price)){
							$sup_price=$sup_prices['sup_price'];
							$sup_type=$sup_prices['sup_type'];
							$sup_goodids=explode(',',$sup_prices['sup_goodids']);
							if(!empty($sup_price)){
								if($sup_price>0){
									if($sup_type=='1'){
										$moneys['sem_slid']=$sem_slid;
										$moneys['sem_synum']=$sys_num;
										$moneys['sem_price']="-".$sup_price;
										$moneys['sem_creacter']="系统派单";
										$moneys['sem_type']=12;
										$settlement_money->insert($moneys);
									}else{
										if(in_array($v['goods_id'],$sup_goodids)){
											$moneys['sem_slid']=$sem_slid;
											$moneys['sem_synum']=$sys_num;
											$moneys['sem_price']="-".$sup_price;
											$moneys['sem_creacter']="系统派单";
											$moneys['sem_type']=12;
											$settlement_money->insert($moneys);
										}
									}
									//$testa=M("`sdceshi_bluezp`.testa");
									//$posa['sqlss']=$settlement_money->getlastsql();
									//$testa->add($posa);
								}
							}
						}
					}
					//派工单状态
					$get['stauas']=30;//派工单状态
					$get['install_id']=$install['id'];//安装人id
					$get['intall_person']=$install['install_name'];//安装人姓名
					$get['intall_phone']=$install['install_phone'];//安装人电话
					//溯源状态
					$times=date('Y-m-d H:i:s');
					$sometime=substr(date('Y-m-d H:i:s',strtotime("$times-2 month")),0,10);//入仓时间
					$arr['goods_name']=$v['goods_name'];//产品名称
					//$info['manufacturer']=$goods_brand->where("`brand_name`='".$MsgArr['goods_brand']."'")->getField("brand_remark");//生产厂家
					$arr['manufacturer']=$pj_brand->whereRaw("`brand_name`='".$v['goods_brand']."'")->value("brand_remark");//生产厂家
					$arr['transport']=$sometime;//入仓时间
					$arr['order_time']=substr($times,0,10);//下单时间
					$arr['install_one']=$install['install_name'];//安装人
					$arr['replacing_time']=substr(date('Y-m-d H:i:s',strtotime('+2 year')),0,10);//建议更换时间
					$arr['installation']=2;//安装分类(上门安装)
				}
                /***************半径推送******************************/
                $store = CommonService::getSyncStores($ser_id, $orderlistIds);
//                $store=SyncStores::where("ser_id",$ser_id)->where("type",2)->value('id');
                if(!empty($store)){
                    $pt_id_arr = PlatformService::getPtIdByPtType();
//	                $supply_price = DB::table('gh_price')->where(['goods_id'=>$v['goods_id'],'ser_id'=>'0'])->orderBy('id',"DESC")->value('supply_price');
                    if(in_array($orderinfo['p_id'], $pt_id_arr)){
                        $supply_price = GhXPrice::whereRaw("`goods_id`='" . $v['goods_id'] . "' and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                    }else {
                        $supply_price = GhPrice::whereRaw("`goods_id`='" . $v['goods_id'] . "' and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                    }
                    if(!$supply_price){
                        $supply_price='0.00';
                    }
                    $goo_code = DB::table('pj_goodcode')->where(['pgc_pgid'=>$v['goods_id'],'pgc_type'=>'1'])->first();
                    if(empty($goo_code)){
                        $goo_code['pgc_code']='暂无';
                        $goo_code['new']='暂无';
                    }
                    $pop['platform_number'] = $orderinfo['order_num'];
                    $pop['ord_order_number'] = $number;
                    $pop['ord_clent_id'] = $user_id;
                    $pop['order_num'] = $orderinfo['order_num'];
                    $pop['orcl_name'] = $shr_phone['shr_name'];
                    $pop['orcl_phone'] = $shr_phone['shr_phone'];
                    $pop['orcl_province'] = $shr_phone['shr_sheng'];
                    $pop['orcl_city'] = $shr_phone['shr_shi'];
                    $pop['orcl_county'] = $shr_phone['shr_xian'];
                    $pop['orcl_address'] = $shr_phone['shr_adress'];
                    $pop['ord_service_shop_id'] = $ser_id;
                    $pop['goo_id'] = $v['goods_id'];
                    $pop['goo_code'] = $goo_code['pgc_code'];
                    $pop['goo_codenew'] = $goo_code['new'];
                    $pop['goo_name'] = $v['goods_name'];
                    $pop['goo_quantity'] = $v['goods_num'];
                    $pop['ord_service_adm_id'] = $install['id']??0;
                    $pop['ord_service_type'] = 1;
                    $pop['ord_client_id'] = $orderinfo['new_customer_id'];
                    $pop['goo_is_recycle'] = 1;
                    $pop['goo_price'] = $supply_price;
                    $pop['company_name'] = CompanyService::getCompanyById($orderinfo['company_id'],['com_name'],'value');
                    $store = SysStoresService::sysStore($pop, 'orderUrl',$store);
                    if($store['ErrorCode']!=1){
                        return $store;
                    }
                    $push_type=2;
                    $get['store_type'] = 5;//派工单状态
                    $post['store_type'] = 5;
                }else{
                    $get['store_type'] = 1;//派工单状态
                    $post['store_type'] = 1;
                }
                /***************半径推送******************************/

                $returnOrderList=DB::table('order_list')->insert($get);
                $returnMan=DB::table('management')->insert($arr);
                if(isset($returnOrderList)){
	                if(!empty($serid)){
						$weixin['ser_id']=$serid;
					}else{
	                	$weixin['ser_id']=$ser_id;
					}
	                $weixin['order_num']=$orderinfo['order_num'];
	                //$weixin['ser_id']=$ser_id;
	                $weixin['goods_name']=$v['goods_name'];
	                $weixin['serial_number']=$number;
	                $this->post_form('http://weixin.sudianwang.com/index.php/BindingAccount/push_order', $weixin);
                    //$ordestatu=M()->execute("update gone_order_status set st_one=st_one+1 where st_serid='".$_POST['ser_id']."'");

                    $relation['sys_num'] = $sys_num;//系统单号
                    $relation['order_num'] = $orderinfo['order_num'];//平台单号
                    $relation['serial_number'] = $number;//派工单号
                    $relation['single_payer'] = $admin_acc;//派单人
                    $relation['order_time'] = $orderinfo['create_time'];//下单时间
                    $relation['payment_time'] = date("Y-m-d H:i:s");//派单时间
                    $relation['ser_id'] = $ser_id;//服务商id
                    $relation['order_goods_id'] = $v['id'];//商品id
                    $relation['p_id'] = $orderinfo['p_id'];//平台id
                    $relation['customer_id'] = $orderinfo['new_customer_id'];//用户id
                    //$relation['order_state'] = 20;//订单状态（已派单）
                    $relation['update_time'] = date("Y-m-d H:i:s");//更新时间
                    $relation['orli_type'] = $orderinfo['order_type'];//订单类型
                    $relation['category'] = 1;//已派单
                    $relation['company_id'] = $orderinfo['company_id'];
                    Temporary::insert($relation);


                    DB::table('order_status')->where('st_serid',$ser_id)->increment('st_one',1);
                    //服务中心扣库存
                    $gsql = "UPDATE `gone_inventory` SET `inv_num`=`inv_num`-1 WHERE `inv_serid`='".$ser_id."' and `inv_goodid`='".$v['goods_id']."' and `inv_num`>0;";
                    $sql = "INSERT INTO sdo2o_bluezp.`gone_invenrecor`( `iv_serid`, `iv_goodid`, `iv_num`,`iv_serial`,`iv_ordernum`) VALUES ('".$ser_id."','".$v['goods_id']."','-1','".$number."','".$orderinfo['order_num']."')";
                    //$inventory->query($sql);
                    //$inventory->query($gsql);
                    DB::update($gsql);
                    DB::update($sql);
                }
                //$order_visit->startTrans();
                $visit_sys = DB::table('order_visit')->where('ov_sys',$sys_num)->value("ov_id");
                $visit_data['ov_serial'] = $number;
                $visit_data['ov_sys'] = $sys_num;
                $visit_data['ov_order'] = $orderinfo['order_num'];
                $visit_data['ov_creatime'] = date('Y-m-d H:i:s');
                $visit_data['ov_statue'] = 1;
                $visit_data['ov_show'] = 1;
                $visit_data['ov_lasttime'] = date("Y-m-d H:i:s",intval(time()));
                $visit_data['company_id'] = $orderinfo['company_id'];
                // if($visit_sys){
                // 	$order_visit->where("ov_id=".$visit_sys)->save($visit_data);
                // }else{
                // 	$order_visit->add($visit_data);
                // }
                DB::table('order_visit')->insert($visit_data);
            }
            //$post['ser_id']=$_POST['ser_id'];//服务中心id
            //$post['order_status']=20;//已派单
            $post['distype'] = '2';
            $returnOrder = DB::table('orders')->where('sys_num',$sys_num)->update($post);
            if($returnOrder && $returnOrderList && $returnMan){
	            $file_path = "./url.txt";
		    	$myfile = fopen($file_path, "a");
		    	$txt = date("Y-m-d H:i:s")."--".$sys_num."--".$ser_id."--".$install['check_code']."\r";
		    	fwrite($myfile, $txt);
		    	fclose($myfile);
                //$order_sendflow=M("order_sendflow");
                $senl['os_serial']=$number;
                $senl['os_serid']=$ser_id;
                $senl['os_installid']=$ser_id;
                $senl['os_parenid']='0';
                $senl['os_ordernum']=$orderinfo['order_num'];
                $senl['os_sysnum']=$sys_num;
                DB::table('order_sendflow')->insert($senl);
				if($install!='0' && $install['bind']=='2'){
					$Pushs= new PushLidaoController();
                    $err = $Pushs->res_push($sys_num,$install['check_code'],'新订单',2,'');
				}
                ////绑定状态
                //if($binds==2){
                //    //include_once('PushAction.class.php');
                //    $Push= new PushController();
                //    //$Push->push($_POST['sys_num'],'新订单',1);
                //    if($orderinfo['order_type']==1){
                //        $Push->push($sys_num,'新订单',1);
                //    }elseif ( $orderinfo['order_type']==10 ){
                //        $Push->push($sys_num,'夜间订单',1);
                //    }elseif ( $orderinfo['order_type']==20 ){
                //        $Push->push($sys_num,'加急订单',1);
                //    }
                //}
                //$parent =DB::table('admin')->whereRaw("FIND_IN_SET(" . $ser_id . ",children_id)")->value('admin_acc');
                //if ($parent) {
                //    //include_once('PushAction.class.php');
                //    $Push = new PushController();
                //    if ($orderinfo['order_type'] == 1) {
                //        $Push->push($parent, '新订单', 2);
                //    } elseif ($orderinfo['order_type'] == 10) {
                //        $Push->push($parent, '夜间订单', 2);
                //    } elseif ($orderinfo['order_type'] == 20 || $orderinfo['order_type'] == 15 || $orderinfo['order_type'] == 25 || $orderinfo['order_type'] == 30) {
                //        $Push->push($parent, '加急订单', 2);
                //    }
                //}
                if($push_type==1){
	                $admin = DB::table('admin')->whereRaw("FIND_IN_SET(" .$ser_id. ",children_id) or id='".$ser_id."'")->get(['admin_acc','token','phone_type'])->toArray();
	                if(!empty($admin)){
		                foreach( $admin as $k => $v ){
			                if($v['phone_type']=='xiaomi'){
				                $Push = new PushxmController();
				                if ($orderinfo['order_type'] == 1) {
			                        $Push->push($v['token'], '新订单');
			                    } elseif ($orderinfo['order_type'] == 10) {
			                        $Push->push($v['token'], '夜间订单');
			                    } elseif ($orderinfo['order_type'] == 20 || $orderinfo['order_type'] == 15 || $orderinfo['order_type'] == 25 || $orderinfo['order_type'] == 30) {
			                        $Push->push($v['token'], '加急订单');
			                    }
			                }else{
			                	$Push = new PushController();
			                    if ($orderinfo['order_type'] == 1) {
			                        $Push->push($v['admin_acc'], '新订单', 2);
			                    } elseif ($orderinfo['order_type'] == 10) {
			                        $Push->push($v['admin_acc'], '夜间订单', 2);
			                    } elseif ($orderinfo['order_type'] == 20 || $orderinfo['order_type'] == 15 || $orderinfo['order_type'] == 25 || $orderinfo['order_type'] == 30) {
			                        $Push->push($v['admin_acc'], '加急订单', 2);
			                    }
		                    }
		                }
	                }
                }
                //$this->inserting_log("系统派单，",$_POST['sys_num'],"订单".$resp,"订单管理");//日志
                //$this->success("派单成功！");
                if($are_id!='0'){
                    $sql="update gone_bservisnew set bs_num=bs_num+1,bs_lastime='".date('Y-m-d H:i:s')."' where bs_serid='".$ser_id."' and bs_id='".$are_id."' and bs_branid='".$goodid."'";
                    //echo $sql;
                    //M()->query($sql);
                    DB::update($sql);
                }
                $data['code']=1;
                $data['msg']="派单成功";
                return $data;
                exit;
            }else{
                //$this->error("派单失败！");
                $data['code']=2;
                $data['msg']="派单失败";
                return $data;
                exit;
            }
        }else{
            //$this->error("派单失败！");
            $data['code']=2;
            $data['msg']="派单失败";
            return $data;
            exit;
        }
    }


    //获取地址经纬度
    function jingwei($city,$address)
    {
        $url = "http://restapi.amap.com/v3/geocode/geo?key=6e8883ff32af2f2b81beaacdd22a9b36&address='".$address."'&city='".$city."'&output='json'";
        //$result = file_get_contents($url);
        $result = $this->http_get($url);
        $arr = json_decode($result,true);
        if($arr['status'] == '1' && $arr['geocodes'] && isset($arr['geocodes'])){
            return $arr['geocodes'][0]['location'];
        }else{
            return '';
        }
    }


    //计算行车距离
    function juli($start,$end)
    {
        $url = "http://restapi.amap.com/v3/distance?key=6e8883ff32af2f2b81beaacdd22a9b36&origins=".$start."&destination=".$end."&type=1&output=json";
        //$result = file_get_contents($url);
        $result = $this->http_get($url);
        $arr = json_decode($result,true);
        if($arr['status'] == '1' && isset($arr['results'])){
            //return round($arr['route']['paths']['0']['distance'] / 1000,2);
            return $arr['results'];
        }else{
            return '';
        }
    }



    //get提交
    function http_get($url, $ssl = FALSE)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if($ssl)
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
            curl_setopt($curl, CURLOPT_SSLVERSION, 3);
        }
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            var_dump(curl_error($curl));
            return FALSE;
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }
	public function post_form($url, $data)
    {
        $postdata = http_build_query($data);
        $options = array('http' => array('method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 15 * 60));
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    //接口访问
    function request_posts($url,$param)
    {
        $header = array(
            'Content-Type: application/json',
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $response = curl_exec($ch);
        curl_close($ch);
        return trim($response);
    }

	function bd_encrypt($gg_lon,$gg_lat){
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $gg_lon;
        $y = $gg_lat;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $bd_lon = $z * cos($theta) + 0.0065;
        $bd_lat = $z * sin($theta) + 0.006;
        // 保留小数点后六位
        $data['bd_lon'] = round($bd_lon, 6);
        $data['bd_lat'] = round($bd_lat, 6);
        return $data;
    }
     function is_point_in_polygon($point, $pts) {
	    $N = count($pts);
	    $boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
	    $intersectCount = 0;//cross points count of x
	    $precision = 2e-10; //浮点类型计算时候与0比较时候的容差
	    $p1 = 0;//neighbour bound vertices
	    $p2 = 0;
	    $p = $point; //测试点

	    $p1 = $pts[0];//left vertex
	    for ($i = 1; $i <= $N; ++$i) {//check all rays
	        // dump($p1);
	        if ($p['lng'] == $p1['lng'] && $p['lat'] == $p1['lat']) {
	            return $boundOrVertex;//p is an vertex
	        }

	        $p2 = $pts[$i % $N];//right vertex
	        if ($p['lat'] < min($p1['lat'], $p2['lat']) || $p['lat'] > max($p1['lat'], $p2['lat'])) {//ray is outside of our interests
	            $p1 = $p2;
	            continue;//next ray left point
	        }

	        if ($p['lat'] > min($p1['lat'], $p2['lat']) && $p['lat'] < max($p1['lat'], $p2['lat'])) {//ray is crossing over by the algorithm (common part of)
	            if($p['lng'] <= max($p1['lng'], $p2['lng'])){//x is before of ray
	                if ($p1['lat'] == $p2['lat'] && $p['lng'] >= min($p1['lng'], $p2['lng'])) {//overlies on a horizontal ray
	                    return $boundOrVertex;
	                }

	                if ($p1['lng'] == $p2['lng']) {//ray is vertical
	                    if ($p1['lng'] == $p['lng']) {//overlies on a vertical ray
	                        return $boundOrVertex;
	                    } else {//before ray
	                        ++$intersectCount;
	                    }
	                } else {//cross point on the left side
	                    $xinters = ($p['lat'] - $p1['lat']) * ($p2['lng'] - $p1['lng']) / ($p2['lat'] - $p1['lat']) + $p1['lng'];//cross point of lng
	                    if (abs($p['lng'] - $xinters) < $precision) {//overlies on a ray
	                        return $boundOrVertex;
	                    }

	                    if ($p['lng'] < $xinters) {//before ray
	                        ++$intersectCount;
	                    }
	                }
	            }
	        } else {//special case when ray is crossing through the vertex
	            if ($p['lat'] == $p2['lat'] && $p['lng'] <= $p2['lng']) {//p crossing over p2
	                $p3 = $pts[($i+1) % $N]; //next vertex
	                if ($p['lat'] >= min($p1['lat'], $p3['lat']) && $p['lat'] <= max($p1['lat'], $p3['lat'])) { //p.lat lies between p1.lat & p3.lat
	                    ++$intersectCount;
	                } else {
	                    $intersectCount += 2;
	                }
	            }
	        }
	        $p1 = $p2;//next ray left point
	    }
	    if ($intersectCount % 2 == 0) {//偶数在多边形外
	        return false;
	    } else { //奇数在多边形内
	        return true;
	    }
	}
   /* public function inserting_log ($type,$order_number,$content,$model,$ip,$admin_acc)
    {
        $data['czrz_name'] = $admin_acc;//登录者
        $data['czrz_ip'] = $ip;//操作ip
        $data['czrz_czsj'] = date("Y-m-d H:i:s");//创建时间
        $data['test_data'] = $model;//操作模块名称
        $data['czrz_czlx'] = $type;//创建类型
        $data['czrz_czxq'] = $content;//操作内容
        $data['czrz_number']= $order_number;//操作单号
        //var_dump($data);
        $res=DB::table('czrz_obj')->insert($data);
        if($res){
            return 1;
        }else{
            return 2;
        }
    }*/



    // 订单操作时间
    /*public function operating_time($num,$type,$time,$admin_acc)
    {
        //$order_time=M("order_time");
        $data['serial_number']=$num;
        $data['create_name']=$admin_acc;
        $data['is_type']=$type;
        $data['create_time']=$time;
        $result=DB::table('order_time')->insert($data);
        if($result){
            return 1;exit;
        }else{
            return 2;exit;
        }
    }*/


    //添加时间戳
   /* public function add_thistory ($number,$timetype,$time,$ser_id,$type)
    {
        //$time_history=M("time_history");
        if($type==1){
            $poss[$timetype]=strtotime($time);
            $poss['tih_serid']=$ser_id;
            $poss['tih_number']=$number;
            DB::table('time_history')->insert($poss);
        }else{
            $poss[$timetype]=strtotime($time);
            DB::table('time_history')->where('tih_number',$number)->update($poss);
        }
    }*/
}
