<?php

namespace App\Http\Controllers\Orders;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Admin\Pushxm;
use App\Services\CommonService;
use App\Services\CompanyService;
use App\Services\SysStoresService;
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 App\Services\OrderDeductionFeeService;
use DB;

class AotuorderController extends BaseController
{
    public function Distrib ($sys_nums,$ip,$admin_acc="系统录入",$admin_id='1133')
    {
        if($sys_nums!=''){
            $sys_num = $sys_nums;
            //判定是否为多品牌订单
            $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){
                $content = '包含品牌大于一个('.count($goods_brand).');';
                $this->manual($sys_num);
                $this->insertingLog("系统派单，",$sys_num,$content,"订单管理",$ip,$admin_acc);//日志
                return true;
            }
            $order = DB::table("orders")->where('sys_num',$sys_num)->first();
            if(empty($order)){
                $this->insertingLog("系统派单，",$sys_num,'单号异常获取失败',"订单管理",$ip,$admin_acc);//日志
                return true;
            }
            //判定是否为锁定订单
            if($order['lock_type']=='2'){
                $this->manual($sys_num);
                $this->insertingLog("系统派单，",$sys_num,'锁定订单禁止下派',"订单管理",$ip,$admin_acc);//日志
                return true;
            }
            $order_rejected = DB::table("order_rejected")->where('or_order_num',$order['order_num'])->select('or_ser_id')->get();
            $order_rejected = CommonService::dataToArray($order_rejected);
            if(empty($order_rejected)){
                $or_ser_id = '';
            }else{
                $or_ser_id = array_column($order_rejected, 'or_ser_id');
            }
            //判定用户信息是否重复
            $user = DB::table("user")->where('id',$order['new_customer_id'])->first();
            $user_phone = DB::table("user")->where('shr_name',$user['shr_name'])->where('shr_sheng',$user['shr_sheng'])->where('shr_shi',$user['shr_shi'])->where('shr_xian',$user['shr_xian'])->select('id')->first();
            $phone = array_column($user_phone,'id');
            $order_num = DB::table("orders")->where('new_customer_id','in', implode(',',$phone))->count();
            if($order_num>1){
                $this->manual($sys_num);
                $this->insertingLog("系统派单，",$sys_num,'重复手机号暂停派单',"订单管理",$ip,$admin_acc);//日志
                return true;
                foreach( $user_phone as $k => $v )
                {
                    $phone[]=$v['id'];
                }
                $ser_id = DB::table('orders as a')->leftJoin('order_msg as b', 'a.sys_num', '=', 'b.sys_num')
                    ->where('new_customer_id','in',implode(',',$phone))->where('ser_id','<>',0)
                    ->where('goods_brand',$goods_brand[0]['goods_brand'])
                    ->value('ser_id');
                if($ser_id){
                    $enable =DB::table("admin")->where('id',$ser_id)->value('enable');
                    if($enable!=1){
                        $this->insertingLog("系统派单，",$sys_num,"重复手机号派单，门店已停用","订单管理",$ip,$admin_acc);//日志
                    }else{
                        $data=$this->addWorkOrder($order,$sys_num,$ser_id,$order['new_customer_id'],$areid,$goodid,$admin_acc,$admin_id);
                        if($data['code']=='1'){
                            $this->insertingLog("系统派单，",$sys_num,'重复手机号派单成功',"订单管理",$ip,$admin_acc);//日志
                            return true;
                        }else{
                            $this->insertingLog("系统派单，",$sys_num,"重复手机号派单，".$data['msg'],"订单管理",$ip,$admin_acc);//日志
                            return true;
                        }
                    }
                }else{
                    $this->manual($sys_num);
                    $this->insertingLog("系统派单，",$sys_num,'重复手机号派单未匹配门店',"订单管理",$ip,$admin_acc);//日志
                    return true;
                }
            }
            $goodid=DB::table("goods_brand")->where('brand_name',$goods_brand[0]['goods_brand'])->where('company_id',$order['company_id'])->value("id");
            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(empty($shr_sheng)){
                $this->manual($sys_num);
                $this->insertingLog("系统派单，",$sys_num,'未匹配到省份信息',"订单管理",$ip,$admin_acc);//日志
                return true;
            }
            //验证城市信息
            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(empty($shr_shi)){
                $this->manual($sys_num);
                $this->insertingLog("系统派单，",$sys_num,'未匹配到城市信息',"订单管理",$ip,$admin_acc);//日志
                return true;
            }
            //通过区县获取地址
            $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;
            }
            if(empty($dress)){
                $this->manual($sys_num);
                $this->insertingLog("系统派单，",$sys_num,'未匹配到地址',"订单管理",$ip,$admin_acc);//日志
                return true;
            }
            $data['code']='2';
            if($data['code']=='1'){
            }else{
                if(empty($or_ser_id)) {
                    if ($xian == 1) {
                        $ser = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("find_in_set('" . $dress['are_id'] . "',bs_areid) and bs_branid='" . $goodid . "' and bs_status='1' and enable=1")->where('company_id',$order['company_id'])->select('bservisnew.*')->get()->toArray();
                        if (!$ser) {
                            $ser = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("bs_sid='" . $dress['are_sid'] . "' and bs_branid='" . $goodid . "' and bs_status='1' and enable=1")->where('company_id',$order['company_id'])->select('bservisnew.*')->get()->toArray();
                            $xian = 2;
                        }
                    } else {
                        $ser = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("bs_sid='" . $dress['are_sid'] . "' and bs_branid='" . $goodid . "' and bs_status='1' and enable=1")->where('company_id',$order['company_id'])->select('bservisnew.*')->get()->toArray();
                    }
                }else{
                    if ($xian == 1) {
//                        CommonService::startmysql();
                        $ser = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("find_in_set('" . $dress['are_id'] . "',bs_areid) and bs_branid='" . $goodid . "' and bs_status='1' and enable=1 and bs_serid not in (".implode(',', $or_ser_id).")")->where('company_id',$order['company_id'])->select('bservisnew.*')->get()->toArray();
//                        CommonService::addLog('自动拒单', CommonService::showmysql(), '','AotuorderController');
                        if (!$ser) {
                            $ser = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("bs_sid='" . $dress['are_sid'] . "' and bs_branid='" . $goodid . "' and bs_status='1' and enable=1 and bs_serid not in (".implode(',', $or_ser_id).")")->where('company_id',$order['company_id'])->select('bservisnew.*')->get()->toArray();
                            $xian = 2;
                        }
                    } else {
                        $ser = Bserviss::leftJoin('admin','admin.id','=','bservisnew.bs_serid')->whereRaw("bs_sid='" . $dress['are_sid'] . "' and bs_branid='" . $goodid . "' and bs_status='1' and enable=1 and bs_serid not in (".implode(',', $or_ser_id).")")->where('company_id',$order['company_id'])->select('bservisnew.*')->get()->toArray();
                    }
                }
                if($ser){
                    $juli = 1;
                    $end = $this->jingwei($user['shr_sheng'],$user['shr_sheng'].$user['shr_shi'].$user['shr_xian'].$user['shr_adress']);
                    if($end){
                        $admin_id = array_column($ser,'bs_serid');
                        $list= DB::table("admin")->where('enable',1)
                            ->whereIn('id',$admin_id)
                            ->select("id","company_name","owner","children_id")->get()->toArray();
                        if($list){
                            $admin_ids = array_column($list,'id');
                            $admin_ids=implode(',',$admin_ids);
                            $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();
                            $admin_list = CommonService::jointArrayKey($admin_infor, 'admin_id');
                            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($jingwei){
                                        $start []= $jingwei;
                                    }else{
                                        $start []="0,0";
                                    }
                                }else{
                                    $start[]= $adminInfo['admin_longitude'].",".$adminInfo['admin_latitude'];
                                }
                            }
                            if(!empty($start) && !empty($end)){
                                $start=implode('|',$start);
                                $res = $this->juli($start,$end);
                            }
                            foreach( $list as $ki => $vi ){
                                if($res[$ki]['code']=='3'){
                                    $num[]=10000;
                                    $list[$ki]['juli'] = '10000';
                                }else{
                                    $num[]=round($res[$ki]['distance']/1000,2);
                                    $list[$ki]['juli'] = round($res[$ki]['distance']/1000,2);
                                }
                            }
                            array_multisort($num, SORT_NUMERIC ,SORT_ASC, $list);
                            if($list[0]['juli']<8){
                                if($xian==1){
                                    $ser=DB::table("bservisnew")->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=DB::table("bservisnew")->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->insertingLog("系统派单，",$sys_num,"订单l".$data['msg']."；距离(".$list[0]['id'].")：".$list[0]['juli'],"订单管理",$ip,$admin_acc);//日志
                                return true;
                            }
                        }
                    }
                    if($juli == 1){
                        $time=date("Y-m-d H:i:s");
                        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($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->insertingLog("系统派单，",$sys_num,"订单in".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                        }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($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->insertingLog("系统派单，",$sys_num,"订单sa".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                            }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($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->insertingLog("系统派单，",$sys_num,"订单ax".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                                }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->insertingLog("系统派单，",$sys_num,"订单p".$datas['msg'],"订单管理",$ip,$admin_acc);//日志
                                }
                            }
                        }
                        if(!isset($datas) || $datas['code']!='1'){
                            $this->manual($sys_num);
                            return true;
                        }
                        //派单结束
                    }
                    return true;
                    //自动派单结束
                }else{
                    $this->manual($sys_num);
                    $this->insertingLog("系统派单，",$sys_num,'未匹配到服务商',"订单管理",$ip,$admin_acc);//日志
                    return true;
                }
            }
        }
        return true;
    }


    //手动派单
    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{
            $data['code']=2;
            $data['msg']="派单失败，该订单状态不正确，请刷新核实！";
            return $data;
        }
        // 派单扣除 订单所属公司金额
        // 扣费
        $post_data['adm_id'] = $orderinfo['admin_id'];
        $post_data['company_id'] = $orderinfo['company_id'];
        $post_data['order_number'] = $sys_num;
        $post_data['reo_price'] = -0.5;
        $reduce_price = OrderDeductionFeeService::deductFee($post_data);
        if ($reduce_price['code'] != 200) {
            $data['code']=2;
            $data['msg']="余额不足";
            return $data;
        }
        // 绑定状态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)){
            $shr_phone=DB::table('user')->where('id',$user_id)->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();//手机号
            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){
                $orderlistIds=DB::table('order_list')->where('sys_num',$sys_num)->where('order_goods_id',$v['id'])->value("id");
                if(isset($orderlistIds)){
                    $data['code']=2;
                    $data['msg']="派单失败，该订单已被派发";
                    return $data;
                }
                $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']=20;
                $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
                $agency_id = DB::table('admin')
                    ->where('id',$ser_id)
                    ->value('company_id');
                $get['agency_id'] = $agency_id;//代理商id(运营商）
                $get['customer_phone']=$shr_phone['shr_phone'];//客户手机号
                $get['orli_type']=$orderinfo['order_type'];//订单类型
                $get['pay_typel']=$orderinfo['pay_type'];//支付方式
                $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->operatingTime($number,'下单时间',$orderinfo['create_time'],$orderinfo['order_num'],$admin_acc);//订单操作时间
                $this->operatingTime($number,'派单时间',date("Y-m-d H:i:s"),$orderinfo['order_num'],$admin_acc);//订单操作时间
                $this->operatingTime($number,'起始时间',$payout_time,$orderinfo['order_num'],$admin_acc);//订单操作时间
                $this->add_thistory($number,'tih_crecttime',$payout_time,$ser_id,1);//添加历史时间
                if($install!='0'){
                    $this->operatingTime($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);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //派工单状态
                    $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 = DB::table('sync_stores')->whereRaw("ser_id='".$ser_id."' and type='2'")->value('id');
                if(!empty($store)){
                    $goo_code = DB::table('pj_goodcode')->whereRaw("pgc_pgid='".$v['goods_id']."' and pgc_type=1")->first();
                    if(empty($goo_code)){
                        $goo_code['pgc_code']='暂无';
                        $goo_code['new']='暂无';
                    }
                    $supply_price = DB::table('gh_price')->whereRaw("goods_id='".$v['goods_id']."' and ser_id=0")->orderBy('id',"DESC")->value('supply_price');
                    //$supply_price = DB::table('gh_price')->where(['goods_id'=>$v['goods_id'],'ser_id'=>'0'])->orderBy('id',"DESC")->value('supply_price');
                    if(!$supply_price){
                        $supply_price='0.00';
                    }
                    $pop['platform_number'] = $orderinfo['order_num'];
                    $pop['ord_order_number'] = $number;
                    $pop['ord_clent_id'] = $_POST['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']?$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;
                    $time = date("Y-m-d H:i:s");
//                    $pop['time'] = $time;
//                    $pop['token'] = md5(md5($time.'4a392d38f53a162699bda15b6f97e4f9'));
//                    $resp = $this->do_post('http://mk.bluearp.com/index.php/api/v3/OtherSystemOrders/importOrders',$pop);
                    $pop['company_name'] = CompanyService::getCompanyById($orderinfo['company_id'],['com_name'],'value');
                    $store = SysStoresService::sysStore($pop, 'orderUrl',$store);
                    if($store['ErrorCode']!=1){
                        $data['code']=$store['ErrorCode'];
                        $data['msg']=$store['ErrorMessage'];
                        return $data;
                    }
                    $push_type=2;
                    $get['store_type'] = 5;//派工单状态
                    $post['store_type'] = 5;
                }else{
                    $get['store_type'] = 1;//派工单状态
                    $post['store_type'] = 1;
                }
                /***************半径推送******************************/

                $get['company_id'] = $orderinfo['company_id'];//支付方式
                $get['ol_distype'] = 2;//系统派单类型
                $returnOrderList=DB::table('order_list')->insert($get);
                $arr['company_id'] = $orderinfo['company_id'];
                $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['goods_name']=$v['goods_name'];
//                    $weixin['serial_number']=$number;
                    $weixin['order_num'] = $orderinfo['order_num'];
                    $weixin['goods_name'] = '安装服务';//$v['goods_name'];
                    $weixin['serial_number'] = $number;
                    $weixin['dress'] = $shr_phone['shr_sheng'].$shr_phone['shr_shi'].$shr_phone['shr_xian'].$shr_phone['shr_adress'];
                    CommonService::requestPost('http://zptzchat.bluearp.com/m/index.php/BindingAccount/push_order', $weixin);
                    //$ordestatu=M()->execute("update gone_order_status set st_one=st_one+1 where st_serid='".$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);
                }
                //$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'];
                DB::table('order_visit')->insert($visit_data);
            }
            $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($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)){
                    }
                }
                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;
            }else{
                //$this->error("派单失败！");
                $data['code']=2;
                $data['msg']="派单失败";
                return $data;
            }
        }else{
            //$this->error("派单失败！");
            $data['code']=2;
            $data['msg']="派单失败";
            return $data;
        }
    }


    //获取地址经纬度
    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 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);
         }
     }


    function do_post($url,$param)
    { // 模拟提交数据函数
        //$post_data = http_build_query($param, '', '&');

        $post_data = $this->ToUrlencode($param);
        $post_data=urldecode(json_encode($post_data));
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        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)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    public function ToUrlencode($arr)
    {

        $temp = array();
        if (is_array($arr))
        {
            foreach ($arr AS $key => $row)
            {
                $temp[$key] = $row;
                if (is_array($temp[$key]))
                {
                    $temp[$key] = $this->ToUrlencode($temp[$key]);
                }
                else
                {
                    $temp[$key] = urlencode($row);
                }
            }
        }
        else
        {
            $temp = $arr;
        }
        return $temp;
    }
}
