<?php

namespace App\Http\Controllers;

use App\Events\CancelOrderEvent;
use App\Events\NewOrder;
use App\Events\TipSend;
use App\Events\FinishAccount;
use App\Handlers\Address;
use App\Handlers\ExpressHandler;
use App\Models\AgentNo;
use App\Models\GoodSku;
use App\Models\Inventory;
use App\Models\OrderCancel;
use App\Models\OrderRefund;
use App\Models\OrderDetail;
use App\Models\Scan;
use App\Models\User;
use App\Models\ShopCar;
use App\Models\VipLog;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\Goods;
use App\Models\Store;
use App\Models\Comment;
use App\Models\DwbsUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class OrderController extends Controller
{
    //我的订单首页
    public function getOrderIndex()
    {
        $user=Auth::user();
        $order_num=Order::where('user_id',$user->id)->count();

        $total=Order::where('user_id',$user->id)
            ->whereIn('apply_cancel',[0,1,3])
            ->whereIn('is_refund',[0,1,2])
            ->select('status',DB::raw('count(status) as count'))
            ->groupBy('status')->get();
        $order=Order::with(['cancel'=>function($query){$query->where('using',1);},'refund','store:id,name,img,phone'])
            ->whereIn('apply_cancel',[0,1,3])
            ->whereIn('is_refund',[0,1,2])
            ->where('user_id',$user->id)
            ->orderByDesc('created_at')
            ->select('id','order_no','store_id','is_tip_send','account','address_id','apply_cancel','is_refund','is_pay','pay_at','total','user_id','created_at','remark','signature','status')
            ->first();
        if(!empty($order)){
            $goods_ids=OrderDetail::where('order_no',$order->order_no)->groupBy('goods_id')->pluck('goods_id');
            $goods=[];
            foreach($goods_ids as $key=>$val){
                $goods[$key]=Goods::where('id',$val)->first();
                $goods[$key]->sku=OrderDetail::where('order_no',$order->order_no)->where('goods_id',$val)->get();
            }
            $order->goods=$goods;
        }
        $data['user']=User::where('id',$user->id)
            ->select('id','nickname','area_code','phone','openId','unionId','is_vip','status','sex','avatar')
            ->first();;
        $data['total']=$total;
        $data['order']=$order;
        $refund_total=OrderRefund::where('user_id',$user->id)->count();
        $cancel_total=Order::where('user_id',$user->id)
            ->whereIn('apply_cancel',[1,2,3])->count();
        $data['refund_total']=$refund_total+$cancel_total;
        $data['all_total']=Order::where('user_id',$user->id)
            ->whereIn('apply_cancel',[0,1,3])
            ->count();
        $data['order_num']=$order_num;
        return $this->success($data);
    }
    //获取订单状态数量
    public function getOrderStatusNum(){
        $where['user_id']=Auth::user()->id;
        $data=Order::where($where)->whereIn('apply_cancel',[0,1,3])->whereIn('is_refund',[0,1,2]);
        $data1=clone $data;
        $data2=clone $data;
        $data3=clone $data;
        $num['noPay']=$data->where('status',0)->count();
        $num['noSend']=$data1->where('status',1)->count();
        $num['noReceive']=$data2->where('status',2)->count();
        $num['Finish']=$data3->where('status',3)->count();
        return $this->success($num);
    }
    //获取用户订单列表
    public function getOrderList(Request $request)
    {
        $input=$request->all();
        $page_index=$input['page_index'];
        $page_size=$input['page_size'];
        $order_no=$input['order_no'];
        $num=$page_size*($page_index-1);
        $status=$input['status'];
        $where=$wheres=[];
        if($status!='all'){
            $where['status']=$status;
        }
        $where['user_id']=Auth::user()->id;
        if($order_no){
            $wheres=function($query)use($order_no){
                $query->where('order_no','like','%'.$order_no.'%');
            };
        }
        $orders=Order::with(['cancel'=>function($query){$query->where('using',1);},'refund','store:id,name,img,phone'])
            ->where($where)->where($wheres)->whereIn('apply_cancel',[0,1,3])->whereIn('is_refund',[0,1,2])
            ->select('id','order_no','store_id','is_tip_send','account','address_id','apply_cancel','is_refund','is_pay','pay_at','total','user_id','created_at','remark','signature','status')
            ->orderByDesc('id')->skip($num)->take($page_size)->get();
        $count=Order::where($where)->where($wheres)->whereIn('apply_cancel',[0,1,3])->whereIn('is_refund',[0,1,2])->count();
        foreach($orders as $key=>$val){
            $goods_ids=OrderDetail::where('order_no',$val->order_no)->groupBy('goods_id')->pluck('goods_id');
            $goods=[];
            foreach($goods_ids as $k=>$v){
                $goods[$k]=Goods::where('id',$v)->first();
                $goods[$k]->sku=OrderDetail::where('order_no',$val->order_no)->where('goods_id',$v)->get();
            }
            $orders[$key]->goods=$goods;
        }
        return $this->success_list($orders,'成功',$count);
    }
    //获取退货订单详情
    public function getRefundOrderDetail(Request $request){
        $order_no=$request->input('order_no');
        $order_refund=OrderRefund::where('order_no',$order_no)->get();
        foreach($order_refund as $key => $val){
            $goods_ids = OrderDetail::where('order_no', $val->refund_no)->groupBy('goods_id')->pluck('goods_id');
            $goods = [];
            foreach ($goods_ids as $k => $v) {
                $goods[$k] = Goods::where('id', $v)->first();
                $goods[$k]->sku = OrderDetail::where('order_no', $val->refund_no)->where('goods_id', $v)->get();
            }
            $order_refund[$key]->goods=$goods;
        }
        return $this->success($order_refund);
    }
    //判断订单价格
    protected function getOrderPrice($user_id,$store_id,$num){
        $vipLog=VipLog::where('user_id',$user_id)->where('store_id',$store_id)->first();
        if($vipLog){
            return 'vip_ed';//vip价格
        }else{
            if($num>=2){
                return 'vip_ing';//vip价格
            }else{
                return 'normal';//正常价
            }
        }
    }
    //记录下单时账号
    protected function saveAgentNoLog($user_id,$agent_id,$order_no){
        $one=$agent_id;
        $one_agent=DwbsUser::where('id',$one)->first();
        $data=[];
        $data[0]['order_no']    = $order_no;
        $data[0]['user_id']     = $user_id;
        $data[0]['nickname']    = $one_agent->nickname;
        $data[0]['phone']       = $one_agent->mobile;
        $data[0]['created_at']  = date("Y-m-d H:i:s");
        $data[0]['updated_at']  = date("Y-m-d H:i:s");
        return $data;
    }

    public function CheckOrder(Request $request){
        $input=$request->all();
        $sku=$input['sku'];
        $user=User::find(Auth::user()->id);
        $store_id=$input['store_id'];
        $time=Carbon::now()->addMonths(-2);
        $re=Order::where('user_id',$user->id)->where('is_pay',1)->where('apply_cancel',0)->where('store_id',$store_id)->where('created_at','>=',$time)->pluck('id');
        if (count($re)==0){
            return $this->success([]);
        }
        foreach ($sku as $k=>$v){
            $res=OrderDetail::whereIn('order_id',$re)->where('sku_id',$v[0])->count();
            if ($res>0){
                return $this->error(50001,'您在2个月内已经购买过相同款式尺码的商品，确定要再次购买吗？');
            }
        }
        return $this->success([]);
    }
    //提交订单
    public function submitOrderInfo(Request $request)
    {
        $user_id=Auth::user()->id;
        $user=User::where('id',$user_id)->first();
        $input=$request->all();
        $sku=$input['sku'];
        $is_car=$input['is_car'];
        if($request->has('store_id')){
            $store_id=$input['store_id'];
        }else{
            Log::info('未知的店铺信息-----user_id:'.$user_id);
            Log::info($input);
            return $this->error('450001','未知的店铺信息');
        }
        $address_id=$request->input('address_id',null);
        $store=Store::where('id',$store_id)->first();
        if(empty($store)){
            return $this->error('450001','店铺不存在或者已被删除');
        }
        if($store->status==1){
            return $this->error('450001','店铺已被禁用');
        }

        $agent_id=$store->user_id;
        $agent=DwbsUser::where('id',$agent_id)->first();

        $time=Carbon::now()->toDateTimeString();


        if(empty($agent)){
            return $this->error('450001','系统账号不存在或已被删除');
        }
        if($agent->status==1){
            return $this->error('450001','系统账号已被禁用');
        }
        $remark=$input['remark'];
        $order_no=Order::order_no('dd');
        $account=$vip_account=$num=0;
        $list=$sku_ids=$snapshot=[];
        foreach($sku as $key=>$val){
            if($val[1] > 0){
                $num += $val[1];
            }
        }
        $vip=$this->getOrderPrice($user->id,$store_id,$num);
        $arr_test=Store::getTest();
            foreach($sku as $key=>$val){
                $sku_info=[];
                if($val[1] > 0){
                    $goodSku=GoodSku::with(['goods'])->where('id',$val[0])->first();
                    if(!array_key_exists($goodSku->goods_id,$snapshot)){
                        $snapshot[$goodSku->goods_id]['name']=$goodSku->goods->name;
                        $snapshot[$goodSku->goods_id]['main_attr']=$goodSku->goods->main_attr;
                        $snapshot[$goodSku->goods_id]['img']=$goodSku->goods->img;
                        $snapshot[$goodSku->goods_id]['price']=$goodSku->goods->price;
                        $snapshot[$goodSku->goods_id]['sku']=[];
                    }
                    if(empty($goodSku)){
                        return $this->error('450001','商品规格不存在，刷新页面重新下单');
                    }
                    if(in_array($store_id,$arr_test)){
                        $storeInventory=Inventory::where(['store_id'=>$store_id,'goods_id'=>$goodSku->goods_id,'sku_id'=>$val[0]])->lockForUpdate()->first();
                        $storeInve_num=!empty($storeInventory)?$storeInventory->num:0;
                        if($val[1] > $storeInve_num){
                            return $this->error('450001','【'.$goodSku->goods->main_attr.'-'.$goodSku->type.'-'.$goodSku->size.'】库存不足');
                        }
                    }
                    if($vip=='vip_ed' || $vip=='vip_ing'){
                        $list[$key]['price']=$goodSku->goods->vip_price;
                        $sku_info['price']=$goodSku->goods->vip_price;
                        $list[$key]['account']=$goodSku->goods->vip_price * $val[1];
                        $account += $goodSku->goods->vip_price * $val[1];
                    }else{
                        $list[$key]['price']=$goodSku->goods->price;
                        $sku_info['price']=$goodSku->goods->price;
                        $list[$key]['account']=$goodSku->goods->price * $val[1];
                        $account += $goodSku->goods->price * $val[1];
                    }
                    $list[$key]['origin_price']=$goodSku->goods->price;

                    $list[$key]['order_no']=$order_no;
                    $list[$key]['goods_id']=$goodSku->goods_id;
                    $list[$key]['store_id']=$store_id;
                    $list[$key]['user_id']=$user->id;
                    $list[$key]['sku_id']=$goodSku->id;
                    $list[$key]['num']=$val[1];
                    $list[$key]['size']=$goodSku->size;
                    $list[$key]['type']=$goodSku->type;
                    $list[$key]['style']=1;
                    $list[$key]['created_at']=date("Y-m-d H:i:s");
                    $list[$key]['updated_at']=date("Y-m-d H:i:s");

                    $sku_info['origin_price']=$goodSku->goods->price;
                    $sku_info['sku_id']=$goodSku->id;
                    $sku_info['num']=$val[1];
                    $sku_info['size']=$goodSku->size;
                    $sku_info['type']=$goodSku->type;
                    array_push($snapshot[$goodSku->goods_id]['sku'],$sku_info);

                    if ($is_car==1) {
                        $sku_ids[] = $val[0];
                    }
                }
            }
            $data=[
                'order_no'=>$order_no,
                'store_id'=>$store_id,
                'user_id'=>$user->id,
                'address_id'=>$address_id,
                'remark'=>$remark,
                'is_help'=>0,
                'status'=>1,
                'is_pay'=>1,//服务商产品权限冻结后下单即支付
                'pay_money'=>$account,
                'pay_type'=>3,//免支付
                'pay_at'=>date("Y-m-d H:i:s"),
                'is_tip_send'=>0,
                'is_comment'=>0,
                'total'=>$num,
                'account'=>$account,
                'snapshot'=>json_encode($snapshot),
            ];
            $agent_id=Store::where('id',$store_id)->value('user_id');
            $agent_data=$this->saveAgentNoLog($user->id,$agent_id,$order_no);
        DB::beginTransaction();
        try{
            $result=Order::create($data);
            foreach($list as $k=>$v){
                $list[$k]['order_id']=$result->id;
            }
            OrderDetail::insert($list);
            AgentNo::insert($agent_data);
            if ($is_car==1) {
                ShopCar::where('user_id', $data['user_id'])->whereIn('sku_id', $sku_ids)->delete();
            }
            DB::commit();
            //新订单通知
            $order=$result;
            $store=Store::where('id',$order->store_id)->first();
            $user=DwbsUser::withTrashed()->where('id',$store->user_id)->first();
            if($user->openid){
                Log::info($user->openid);
                $data['openid']=$user->openid;
                $data['data']=[
                    'first' => '您有新的客户订单，请及时处理',
                    'keyword1' => User::where('id',$order->user_id)->value('nickname'),
                    'keyword2' => '请联系线下收款',
                    'keyword3' => $order->order_no,
                    'keyword4' => $order->created_at
                ];
                event(new NewOrder($data));
            }

            //用户vip变更
            $vipLog=VipLog::where('user_id',$order->user_id)
                ->where('store_id',$order->store_id)->first();
            if(empty($vipLog) && $order->total>=2){
                VipLog::create([
                    'user_id'=>$order->user_id,
                    'store_id'=>$order->store_id,
                    'order_no'=>$order->order_no,
                    'type'=>2,//购买两套，添加vip
                    'remark'=>'购买自动添加vip'
                ]);
                Order::where('order_no',$order->order_no)->update([
                    'vip'=>1
                ]);
            }
            return $this->success($order_no);
        }catch(\Exception $e){
            DB::rollBack();
            return $this->error('450001',$e->getMessage());
        }
    }
    //修改订单备注信息
    public function editOrderRemark(Request $request){
        $order_no=$request->input('order_no');
        $remark=$request->input('remark');
        $res=Order::where('order_no',$order_no)->update([
            'remark'=>$remark
        ]);
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //根据订单号查询订单
    public function getOrderNoInfo(Request $request)
    {
        $input=$request->all();
        $order_no=$input['order_no'];
        $data=Order::withTrashed()->with(['user:id,nickname,phone,avatar','address:id,name,phone,province,city,area,address,area_code,type,user_id','cancel'=>function($query){$query->where('using',1);},'store:id,name,img,phone','refund']);
        $data->select('id','order_no','store_id','is_tip_send','account','address_id','apply_cancel','is_refund','is_pay','pay_at','total','user_id','created_at','remark','signature','status');
        $order=$data->where('order_no',$order_no)->first();
        $user_id=Auth::user()->id;
        if(empty($order)){
            return $this->error('450018','订单不存在');
        }
        if($user_id != $order->user_id){
            $user=User::where('id',$user_id)->first();
            $order_user=User::where('id',$order->user_id)->first();
            if(empty($user->phone) && empty($order_user->openId)){
                return $this->error('450005','是否与该订单所绑定手机账号：'.$order_user->phone.'进行合并');
            }
            return $this->error('450019','这是其他人的订单，你无法进入');
        }
        $goods_ids=OrderDetail::where('order_no',$order->order_no)->groupBy('goods_id')->pluck('goods_id');
        $goods=[];
        foreach($goods_ids as $key=>$val){
            $goods[$key]=Goods::where('id',$val)->first();
            $goods[$key]->sku=OrderDetail::where('order_no',$order->order_no)->where('goods_id',$val)->get();
        }
        $order->goods=$goods;
        return $this->success($order);
    }
    //扫码获取订单，并合并用户
    public function getScanOrder(Request $request){
        $order_no=$request->input('order_no');
        $data=Order::withTrashed()->with(['user:id,nickname,phone,avatar','address','cancel'=>function($query){$query->where('using',1);},'store:id,name,img,phone','refund']);
        $order=$data->where('order_no',$order_no)->first();
        $user_id=Auth::user()->id;
        if(empty($order)){
            return $this->error('450018','扫码订单不存在');
        }
        $goods_ids=OrderDetail::where('order_no',$order->order_no)->groupBy('goods_id')->pluck('goods_id');
        $goods=[];
        foreach($goods_ids as $key=>$val){
            $goods[$key]=Goods::where('id',$val)->first();
            $goods[$key]->sku=OrderDetail::where('order_no',$order->order_no)->where('goods_id',$val)->get();
        }
        if($order_no){
            $scan=Scan::where('user_id',$user_id)->where('store_id',$order->store_id)->first();
            if(!$scan){
                Scan::create([
                    'user_id'=>$user_id,
                    'store_id'=>$order->store_id,
                    'goods_id'=>null,
                    'order_no'=>$order_no,
                    'is_store'=>3
                ]);
            }
        }
        $order->goods=$goods;
        $result['order']=$order;
        return $this->success($result);
    }
    //提醒发货
    public function tipSend(Request $request)
    {
        $input=$request->all();
        $order_id=$input['order_id'];
        $order=Order::with('store')->where('id',$order_id)->first();
        if($order->status != 1){
            return $this->error('450001','订单状态不符，请核对后再操作');
        }
        if($order->is_tip_send == 1 && time() < strtotime($order->tip_send_at."+1 day")){
            return $this->error('450001','近期已提醒，请稍后重试（24小时内不再提醒）');
        }
        $order->is_tip_send=1;
        $order->tip_send_at=date("Y-m-d H:i:s");
        $res=$order->save();
        if($res){
            $user=DwbsUser::where('id',$order->store->user_id)->first();
            if($user->openid){
                $data['openid']=$user->openid;
                $data['data']=[
                    'first' => '您有新的客户订单等待发货，请及时处理',
                    'keyword1' => $order->order_no,
                    'keyword2' => '以线下实际收款为准',
                    'keyword3' => Auth::user()->nickname,
                    'keyword4' => '待发货'
                ];
                event(new TipSend($data));
            }
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //确认已自提
    public function sureOneSelfTake(Request $request){
        $order_no=$request->input('order_no');
        $order=Order::where('order_no',$order_no)->first();
        $order->status = 3;
        $order->order_status = 0;
        $res=$order->save();
        if($res){
            if($order->pay_type != 3){
                event(new FinishAccount($order->order_no));
            }else{
                Order::where('order_no',$order->order_no)->update(['is_finish'=>1,'finish_no'=>$order->order_no]);
            }
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //确认收货
    public function surePickUp(Request $request)
    {
        $input=$request->all();
        $order_id=$input['order_id'];
        $order=Order::with('address')->where('id',$order_id)->first();
        if(empty($order)){
            return $this->error('450001','该订单不存在');
        }
        if($order->status==3){
            return $this->error('450001','该订单已确认收货');
        }
        $order->status=3;
        $order->order_status=0;//用户收货
        $res=$order->save();
        if($res){
            if($order->pay_type != 3){
                event(new FinishAccount($order->order_no));
            }else{
                Order::where('order_no',$order->order_no)->update(['is_finish'=>1,'finish_no'=>$order->order_no]);
            }
            return $this->success([]);
        }else{
            return $this->error();
        }
    }
    //我的评价
    public function getComment(Request $request){
        $input=$request->all();
        $page_index=$input['page_index'];
        $page_size=$input['page_size'];
        $num=$page_size*($page_index-1);
        $user=Auth::user();
        $count= Comment::where('user_id',$user->id)->where('comment_id',0)->count();
        $list= Comment::with(['comment','store:id,name,img','user:id,avatar,nickname,phone'])
            ->where('user_id',$user->id)->where('comment_id',0)
            ->orderByDesc('id')->skip($num)->take($page_size)->get();

        return $this->success_list($list,'成功',$count);
    }
    //查询订单物流信息
    public function getOrderExpress(Request $request){
        $order_no=$request->input('order_no');
        $order=Order::with('address')->where('order_no',$order_no)->first();
        if(empty($order)){
            return $this->error('450001','订单信息有误');
        }
        if($order->express_state==3){  //已签收
            $express=json_decode($order->express_info,true);
        }else{ //未签收
            $express=new ExpressHandler();
            $CustomerName = null;
            if($order->express_code=='SF'){
                $CustomerName = substr($order->express_phone,-4);
            }
            $express=$express->getExpress($order->express_no, $order->express_code, $order->order_no, $CustomerName);
        }
        $data['express']=$express;
        $data['express_state']=$order->express_state;
        $data['express_company']=$order->express_company;
        $data['express_no']=$order->express_no;
        $data['express_time']=$order->express_time;
        return $this->success($data);
    }
    //取消订单
    public function cancelOrder(Request $request){
        $id=$request->input('id');
        if($request->has('reason')){
            $reason=$request->input('reason');
        }else{
            $reason=null;
        }
        $order=Order::where('id',$id)->first();
        if($order->apply_cancel==1){
            return $this->error('450001','该订单正在取消审核中，不能再次取消');
        }
        if($order->apply_cancel==2){
            return $this->error('450001','该订单已取消，不能再次取消');
        }
        DB::beginTransaction();
        if($order->status==0){
            $order->apply_cancel=2;
            $order->cancel_at=date("Y-m-d H:i:s");
            try {
                $order->save();
                OrderCancel::create([
                    'user_id' => $order->user_id,
                    'store_id' => $order->store_id,
                    'order_id' => $order->id,
                    'status' => 2,
                    'using' => 1,
                    'type' => 1,   //客户自己取消
                    'reason' => $reason.'/用户取消'
                ]);
                DB::commit();
                return $this->success([]);
            }catch(\Exception $e){
                DB::rollBack();
                return $this->error($e->getMessage());
            }
        }elseif($order->status==1){
            try{
                $order->apply_cancel=1;
                $order->cancel_at=date("Y-m-d H:i:s");
                $order->save();
                OrderCancel::where('user_id',$order->user_id)
                    ->where('store_id',$order->store_id)
                    ->where('order_id',$order->id)->update(['using'=>0]);
                OrderCancel::create([
                    'user_id' =>$order->user_id,
                    'store_id'=>$order->store_id,
                    'order_id'=>$order->id,
                    'status'  =>1,
                    'using'   =>1,
                    'type' => 1,   //客户自己取消
                    'reason'  =>$reason.'/用户取消'
                ]);
                //取消订单通知
                $user=User::where('id',$order->user_id)->first();
                $store=Store::where('id',$order->store_id)->first();
                $agent=DwbsUser::withTrashed()->where('id',$store->user_id)->first();
                if($agent->openid){
                    $data['openid']=$agent->openid;
                    $data['data']=[
                        'first' => '您的客户【'.$user->nickname.'】提交了新的取消订单申请，请及时处理',
                        'keyword1' => $user->nickname,
                        'keyword2' => $order->order_no,
                        'keyword3' => '已下单',
                        'keyword4' => $order->cancel_at
                    ];
                    event(new CancelOrderEvent($data));
                }
                DB::commit();
                return $this->success([]);
            }catch(\Exception $e){
                DB::rollBack();
                return $this->error($e->getMessage());
            }
        }else{
            return $this->error('450001','该订单不能取消');
        }
    }

    public function DealAddress(Request $request){
        $data=[];
        $details=$request->input('details');
        $r = Address::smart($details);
        return $this->success([
            'phone'=>array_key_exists('mobile',$r)?$r['mobile']:'',
            'name'=>array_key_exists('name',$r)?$r['name']:'',
            'province'=>$r['province'],
            'city'=>$r['city'],
            'area'=>$r['region'],
            'street'=>$r['street'],
        ]);
        preg_match_all("/1((34[0-8]\d{7})|((3[0-3|5-9])|(4[5-7|9])|(5[0-3|5-9])|(66)|(7[2-3|5-8])|(8[0-9])|(9[1|8|9]))\d{8})/", $details,$phones);
        if($phones){
            if($phones[0]){
                $data['phone']=$phones[0][0];
            }
        }
        $name=trim(mb_substr($details,'0',mb_strpos($details,$phones[0][0])));
        $regex = "/\ |\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\，|\。|\。|\“|\‘|\？|\！|\【|\】|\；|\：|\￥|\（|\）|\'|\`|\-|\=|\\\|\|/";
        $data['name'] = preg_replace($regex,"",$name);

        $client = new Client();
        $url = 'https://restapi.amap.com/v5/place/text?parameters';
        $array = [
            'query' => [
                'keywords' => $details,
                'output' => 'json',
                'key' => '4e0ce153265426f2d2ceef069e5eb552',
            ]
        ];
        $response = $client->request('GET', $url, $array);
        $ad = json_decode($response->getBody()->getContents());
        if ($ad->pois){
            $data['province']=$ad->pois[0]->pname;
            $data['city']=$ad->pois[0]->cityname;
            $data['area']=$ad->pois[0]->adname;
        }
        return $this->success($data);
    }
    //获取微信位置授权
    public function getSignPackage(){
        $config = config('wechat.official_account.daweiboshi');
        $app = Factory::officialAccount($config);
        $url='https://weidian.jiuweiyun.cn/web/user';
        $app->jssdk->setUrl($url);
        $data=$app->jssdk->buildConfig(array('onMenuShareAppMessage','onMenuShareTimeline',
            'openLocation','getLocation','chooseImage',
            'uploadImage', 'downloadImage','scanQRCode',
            'updateAppMessageShareData', 'updateTimelineShareData'), true);
        return $this->success($data);
    }
    //根据经纬度获取地理位置信息
    public function getAddressInfo(Request $request){
        $location=$request->input('location');
        $key='b019688375d389c1e55150985e90f816';
        $client=new Client();
        $url='https://restapi.amap.com/v3/geocode/regeo?key='.$key.'&location='.$location;
        $result=$client->request('GET',$url);
        $res = json_decode($result->getBody()->getContents());
        return $this->success($res);
    }

}
