<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\model\wallet;
use Redis;

/**
 * 会员中心，不是个人中心
 */
class Usercenter extends Api
{
    protected $noNeedLogin = ['test','testredis'];
    protected $noNeedRight = '*';

    protected $allowFields = [
        'id',
        'username',
        'nickname',
        //'truename',//

        'email',
        'mobile',
        'avatar',
        'real_status',
        'gender',
        'height',
        'weight',
        'birthday',
        'bio',
        'audio_bio',

        //'alipay_account',//
        'idcard_status',

        'longitude',
        'latitude',
        'cityname',
        'photo_images',

        'education_id',
        'hobby_ids',
        'job_id',
        'marital_id',
        'tag_ids',
        'wages_id',

        'hometown_cityid',
    ];

    public function testredis(){
        //redis_matching_set(1,125);
        dump(redis_matching_get(1));
        $a = cache('?mt_matching_uid_1','',['type'=>'Redis']);
        dump($a);
    }

    public function test(){
        $a = [1,4,10,22,66,36,102,45,23,52,35,76,7];
        $b = [1,10,7,102];
        $c = [10,102];

        //dump(array_intersect($a,$b));
        $data = array_merge($c,$b);
        dump($data);
        dump(array_flip(array_flip($data)));
        dump(array_flip([]));
    }

    //获取他人用户信息，留下足迹
    public function getuserinfo(){
        $uid = input_post('uid',0);
        $userinfo = Db::name('user')->field($this->allowFields)->where('id',$uid)->find();

        if(!$userinfo){
            $this->error('不存在的用户');
        }

        //
        $userinfo = info_domain_image($userinfo,['avatar','photo_images']);
        $idcard_confirm = Db::name('user_idconfirm')->where('user_id',$uid)->find();
        $new_data = [
            'age'            => birthtime_to_age($userinfo['birthday']),
            'truename'       => ($userinfo['idcard_status'] == 1 && isset($idcard_confirm['truename'])) ? $idcard_confirm['truename'] : '',
            'alipay_account' => ($userinfo['idcard_status'] == 1 && isset($idcard_confirm['alipay_account'])) ? $idcard_confirm['alipay_account'] : '',

        ];

        $userinfo = array_merge($userinfo,$new_data);
        //枚举
        $userinfo['education'] = Db::name('enum_education')->where('id',$userinfo['education_id'])->value('name');
        $userinfo['hobby'] = Db::name('enum_hobby')->where('id','IN',$userinfo['hobby_ids'])->field(['id','name'])->select();
        $userinfo['job'] = Db::name('enum_job')->where('id',$userinfo['job_id'])->value('name');
        $userinfo['marital'] = Db::name('enum_marital')->where('id',$userinfo['marital_id'])->value('name');
        $userinfo['tag'] = Db::name('enum_tag')->where('id','IN',$userinfo['tag_ids'])->field(['id','name'])->select();
        $userinfo['wages'] = Db::name('enum_wages')->where('id',$userinfo['wages_id'])->value('name');

        //家乡
        $userinfo['hometown_city'] = Db::name('area')->where('id',$userinfo['hometown_cityid'])->value('name');

        //vip
        $userinfo['vip_endtime'] = Db::name('user_wallet')->where('user_id',$uid)->value('vip_endtime');
        $userinfo['is_vip'] = $userinfo['vip_endtime'] > time() ? 1 : 0;

        //是否喜欢和关注
        $is_follow = Db::name('user_follow')->where(['uid'=>$this->auth->id,'follow_uid'=>$uid])->find();
        $userinfo['is_follow'] = $is_follow ? 1 : 0;

        $is_like   = Db::name('user_like')->where(['uid'=>$this->auth->id,'like_uid'=>$uid])->find();
        $userinfo['is_like'] = $is_like ? 1 : 0;

        //是否拉黑
        $is_black = Db::name('user_black')->where(['uid'=>$this->auth->id,'black_uid'=>$uid])->find();
        $userinfo['is_black'] = $is_black ? 1 : 0;

        //关注人数,粉丝人数
        $follow_num = Db::name('user_follow')->where(['uid'=>$this->auth->id])->count('id');
        $fans_num   = Db::name('user_follow')->where(['follow_uid'=>$this->auth->id])->count('id');
        $userinfo['follow_num'] = $follow_num;
        $userinfo['fans_num'] = $fans_num;


        //查看别人信息，就要留下痕迹
        $data = [
            'uid' => $this->auth->id,
            'to_uid' => $uid,
        ];
        $check = Db::name('user_visit')->where($data)->find();
        if($check){
            Db::name('user_visit')->where($data)->update(['number'=>$check['number']+1,'updatetime'=>time()]);
        }else{
            $data['number'] = 1;
            $data['updatetime'] = time();
            Db::name('user_visit')->insertGetId($data);
        }


        $this->success('success',$userinfo);

    }

    //同城
    public function samecity(){
        $gender = input_post('gender','all');
        $agemin = input_post('agemin',0);
        $agemax = input_post('agemax',100);

        if(empty($this->auth->cityname) || empty($this->auth->longitude) || empty($this->auth->latitude)){
           // $this->success('success',[]);
        }

        $map = [
            'user.status' => 1,
           // 'user.cityname' => $this->auth->cityname,
            'user.id' => ['neq',$this->auth->id],
           // 'user.longitude' => ['neq',''],
           // 'user.latitude' => ['neq',''],
            'user.is_online|user.is_livebc' => 1,
        ];
        if($gender != 'all'){
            $map['user.gender'] = $gender;
        }

        $map['user.birthday'] = ['between',[time() - $agemax * 31536000,time() - $agemin * 31536000]];

        //dump($map);
        $field = [
            'user.id','user.username','user.nickname','user.birthday','user.height','user.longitude','user.latitude','user.avatar','user.audio_bio','user.bio','user.gender'
        ];
        $list = Db::name('user')->alias('user')->field($field)->where($map)->orderRaw('rand()')->autopage()->select();
        //dump($list);

        $list = list_domain_image($list,['avatar']);

        foreach($list as $key => $one){
            $one['age'] = birthtime_to_age($one['birthday']);
           // $one['distance'] = $this->calc_map_distance([$this->auth->longitude,$this->auth->latitude],[$one['longitude'],$one['latitude']]);
            $one['distance'] = rand(0,10).'公里';

            $list[$key] = $one;
        }

        $this->success('success',$list);

    }

    //附近
    public function nearuser(){
        $gender = input_post('gender','all');
        $agemin = input_post('agemin',0);
        $agemax = input_post('agemax',100);

        if(empty($this->auth->cityname) || empty($this->auth->longitude) || empty($this->auth->latitude)){
           // $this->success('success',[]);
        }

        //经过地图测算和公式推算，经度纬度 0.1即为11公里
        $map = [
            'user.status' => 1,
            ////'user.cityname' => $this->auth->cityname,
            'user.id' => ['neq',$this->auth->id],
           // 'user.longitude' => ['between',[$this->auth->longitude - 0.1,$this->auth->longitude + 0.1]],
           // 'user.latitude' => ['between',[$this->auth->latitude - 0.1,$this->auth->latitude + 0.1]],
            'user.is_online|user.is_livebc' => 1,
        ];
        if($gender != 'all'){
            $map['user.gender'] = $gender;
        }

        $map['user.birthday'] = ['between',[time() - $agemax * 31536000,time() - $agemin * 31536000]];

        //dump($map);
        $field = [
            'user.id','user.username','user.nickname','user.birthday','user.height','user.longitude','user.latitude','user.avatar','user.audio_bio','user.bio','user.gender'
        ];

        $list = Db::name('user')->alias('user')->field($field)->where($map)->orderRaw('rand()')->autopage()->select();
        //dump($list);exit;

        $list = list_domain_image($list,['avatar']);

        foreach($list as $key => $one){
            $one['age'] = birthtime_to_age($one['birthday']);
            //$one['distance'] = $this->calc_map_distance([$this->auth->longitude,$this->auth->latitude],[$one['longitude'],$one['latitude']]);
            $one['distance'] = rand(0,10).'公里';
            $list[$key] = $one;
        }

        $this->success('success',$list);

    }

    //视频通话每分钟调用一次
    //女性不收费，互关不收费，设置不收费的也不收费
    public function video_onemin(){
        $to_user_id = input_post('to_user_id');
        $to_user_info = Db::name('user')->field('id,gender,free_video,free_audio,free_typing')->where('id',$to_user_id)->find();
        if(!$to_user_info){
            $this->error('不存在的用户');
        }

        //先检查今天免费的一分钟
        $start = strtotime(date('Y-m-d'));
        $end   = $start + 86399;

        $map = [
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
            'price' => 0,
        ];

        $check = Db::name('user_match_video_log')->where($map)->find();

        //设置价格
        $price = config('site.video_min_price');
        $price = empty($check) ? 0 : $price;
        $bili  = config('site.money_to_gold');
        $money = bcdiv($price,$bili,2);

        Db::startTrans();

        //记录日志
        $data = [
            'user_id' => $this->auth->id,
            'price'   => $price,
            'createtime' => time(),
            'to_user_id' => $to_user_id,
        ];

        $log_id = Db::name('user_match_video_log')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('扣费失败');
        }

        //扣费
        //男的，或 未实名认证的女的 都要扣费
        if($price > 0 && (($this->auth->gender == 1) || ($this->auth->gender == 0 && $this->auth->idcard_status != 1))){
            $rs = model('wallet')->lockChangeAccountRemain($this->auth->id,'gold',-$price,11,'','user_match_video_log',$log_id);
            if($rs['status'] === false){
                Db::rollback();
                $this->error($rs['msg']);
            }
        }
        //另一方加钱,0收费
        if($money > 0 && $to_user_info['gender'] == 0 && $to_user_info['free_video'] == 0){
            $rs = model('wallet')->lockChangeAccountRemain($to_user_id,'money',$money,21,'','user_match_video_log',$log_id);
            if($rs['status'] === false){
                Db::rollback();
                $this->error($rs['msg']);
            }
        }

        Db::commit();
        $this->success('success');
    }
    //语音通话每分钟调用一次
    public function audio_onemin(){
        $to_user_id = input_post('to_user_id');
        $to_user_info = Db::name('user')->field('id,gender,free_video,free_audio,free_typing')->where('id',$to_user_id)->find();
        if(!$to_user_info){
            $this->error('不存在的用户');
        }

        //先检查今天免费的一分钟
        $start = strtotime(date('Y-m-d'));
        $end   = $start + 86399;

        $map = [
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
            'price' => 0,
        ];

        $check = Db::name('user_match_audio_log')->where($map)->find();

        //设置价格
        $price = config('site.audio_min_price');
        $price = empty($check) ? 0 : $price;
        $bili  = config('site.money_to_gold');
        $money = bcdiv($price,$bili,2);

        Db::startTrans();

        //记录日志
        $data = [
            'user_id' => $this->auth->id,
            'price'   => $price,
            'createtime' => time(),
            'to_user_id' => $to_user_id,
        ];

        $log_id = Db::name('user_match_audio_log')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('扣费失败');
        }

        //扣费
        //男的，或 未实名认证的女的 都要扣费
        if($price > 0 && (($this->auth->gender == 1) || ($this->auth->gender == 0 && $this->auth->idcard_status != 1))){
            $rs = model('wallet')->lockChangeAccountRemain($this->auth->id,'gold',-$price,12,'','user_match_audio_log',$log_id);
            if($rs['status'] === false){
                Db::rollback();
                $this->error($rs['msg']);
            }
        }
        //另一方加钱,0收费
        if($money > 0 && $to_user_info['gender'] == 0 && $to_user_info['free_audio'] == 0){
            $rs = model('wallet')->lockChangeAccountRemain($to_user_id,'money',$money,22,'','user_match_audio_log',$log_id);
            if($rs['status'] === false){
                Db::rollback();
                $this->error($rs['msg']);
            }
        }

        Db::commit();
        $this->success('success');
    }
    //打字聊天每句话调用一次
    public function typing_once(){
        $to_user_id = input_post('to_user_id');
        $to_user_info = Db::name('user')->field('id,gender,free_video,free_audio,free_typing')->where('id',$to_user_id)->find();
        if(!$to_user_info){
            $this->error('不存在的用户');
        }


        //设置价格
        $price = config('site.typing_min_price');
        $bili  = config('site.money_to_gold');
        $money = bcdiv($price,$bili,2);


        Db::startTrans();

        //记录日志
        $data = [
            'user_id' => $this->auth->id,
            'price'   => $price,
            'createtime' => time(),
            'to_user_id' => $to_user_id,
        ];

        $log_id = Db::name('user_match_typing_log')->insertGetId($data);
        if(!$log_id){
            Db::rollback();
            $this->error('扣费失败');
        }

        //扣费
        //男的，或 未实名认证的女的 都要扣费
        if($price > 0 && (($this->auth->gender == 1) || ($this->auth->gender == 0 && $this->auth->idcard_status != 1))){
            $rs = model('wallet')->lockChangeAccountRemain($this->auth->id,'gold',-$price,13,'','user_match_typing_log',$log_id);
            if($rs['status'] === false){
                Db::rollback();
                $this->error($rs['msg']);
            }
        }
        //另一方加钱,设置0收费
        if($money > 0 && $to_user_info['gender'] == 0 && $to_user_info['free_typing'] == 0){
            $rs = model('wallet')->lockChangeAccountRemain($to_user_id,'money',$money,23,'','user_match_typing_log',$log_id);
            if($rs['status'] === false){
                Db::rollback();
                $this->error($rs['msg']);
            }
        }


        //tag任务赠送金币
        //搭讪奖励
        $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,15);
        if($task_rs === false){
            Db::rollback();
            $this->error('完成任务赠送奖励失败');
        }

        Db::commit();
        $this->success('success');
    }

    //语音匹配
    public function getaudiouser(){

        //判断资格
        $start = strtotime(date('Y-m-d'));
        $end   = $start + 86399;

        $map = [
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
            'price' => 0,
        ];

        $check = Db::name('user_match_audio_log')->where($map)->find();
        //$check = true;

        //已经用掉免费的了，判断金额
        if($check){
            $price = config('site.audio_min_price');
            $gold = model('wallet')->getWallet($this->auth->id,'gold');

            if($gold < $price){
                $this->error('您的金币已经不足,请充值');
            }
        }

        //找到互关的人，排除
        $follow_me = Db::name('user_follow')->where('follow_uid',$this->auth->id)->column('uid');
        //dump($follow_me);
        $my_follow = Db::name('user_follow')->where(['uid'=>$this->auth->id,'follow_uid'=>['IN',$follow_me]])->column('follow_uid');
        //dump($my_follow);exit;


        //给出备选用户
        $map = [
            'status' =>1,                                       //未封禁用户
            'gender' => $this->auth->gender == 1 ? 0 : 1,       //异性
            'is_online' => 0,                                   //不在语聊间的
            'is_livebc' => 0,                                   //不在直播的
            'real_status' => 1,                                 //真人认证
            'idcard_status' => 1,                               //实名认证
            'open_match_audio' => 1,                            //打开语聊开关
            'id' => ['NOT IN',$my_follow]                     //不是好友的
        ];

        $lists = Db::name('user')->field('id,cityname,status,gender,real_status,tag_ids')->where($map)->order('logintime desc')->page($this->page,100)->select();
        $lists = $this->fliter_user($lists,10);

        $result = [];
        if(!empty($lists)){
            foreach($lists as $key => $val){
                $result[] = ['id'=>$val];
            }
        }

        //tag任务赠送金币
        //语音匹配奖励  +5金币
        if(!empty($result)){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,11);
            if($task_rs === false){
                $this->error('完成任务赠送奖励失败');
            }
        }

        $this->success('success',$result);
    }

    //视频匹配
    public function getvideouser(){

        //判断资格
        $start = strtotime(date('Y-m-d'));
        $end   = $start + 86399;

        $map = [
            'user_id' => $this->auth->id,
            'createtime' => ['between',[$start,$end]],
            'price' => 0,
        ];

        $check = Db::name('user_match_video_log')->where($map)->find();
        //$check = true;

        //已经用掉免费的了，判断金额
        if($check){
            $price = config('site.video_min_price');
            $gold = model('wallet')->getWallet($this->auth->id,'gold');

            if($gold < $price){
                $this->error('您的金币已经不足,请充值');
            }
        }

        //找到互关的人，排除
        $follow_me = Db::name('user_follow')->where('follow_uid',$this->auth->id)->column('uid');
        //dump($follow_me);
        $my_follow = Db::name('user_follow')->where(['uid'=>$this->auth->id,'follow_uid'=>['IN',$follow_me]])->column('follow_uid');
        //dump($my_follow);exit;


        //给出备选用户
        $map = [
            'status' =>1,                                       //未封禁用户
            'gender' => $this->auth->gender == 1 ? 0 : 1,       //异性
            'is_online' => 0,                                   //不在语聊间的
            'is_livebc' => 0,                                   //不在直播的
            'real_status' => 1,                                 //真人认证
            'idcard_status' => 1,                               //实名认证
            'open_match_video' => 1,                            //打开视频开关的
            'id' => ['NOT IN',$my_follow]                     //不是好友的
        ];

        $lists = Db::name('user')->field('id,cityname,status,gender,real_status,tag_ids')->where($map)->order('logintime desc')->page($this->page,100)->select();
        $lists = $this->fliter_user($lists,10);

        $result = [];
        if(!empty($lists)){
            foreach($lists as $key => $val){
                $result[] = ['id'=>$val];
            }
        }

        //tag任务赠送金币
        //视频匹配奖励  +5金币
        if(!empty($result)){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,12);
            if($task_rs === false){
                $this->error('完成任务赠送奖励失败');
            }
        }
        $this->success('success',$result);
    }

    //聊天匹配
    public function gettypinguser(){

        //找到互关的人，排除
        $follow_me = Db::name('user_follow')->where('follow_uid',$this->auth->id)->column('uid');
        //dump($follow_me);
        $my_follow = Db::name('user_follow')->where(['uid'=>$this->auth->id,'follow_uid'=>['IN',$follow_me]])->column('follow_uid');
        //dump($my_follow);exit;

        //给出备选用户
        $map = [
            'status' =>1,                                        //未封禁用户
            'gender' => $this->auth->gender == 1 ? 0 : 1,        //异性
            //'real_status' => 1,                                 //真人认证
            //'idcard_status' => 1,                               //实名认证
            //打开聊天开关的
            'open_match_typing' => 1,                            //打开文字聊天开关的
            'id' => ['NOT IN',$my_follow]                      //不是好友的
        ];

        $lists = Db::name('user')->field('id,cityname,status,gender,real_status,tag_ids')->where($map)->order('logintime desc')->page($this->page,100)->select();
        //$lists = $this->fliter_user($lists,100);
        $lists = array_column($lists,'id');

        $result = [];
        if(!empty($lists)){
            /*foreach($lists as $key => $val){
                $result[] = ['id'=>$val];
            }*/
            $result = Db::name('user')->field('id,nickname,username,avatar,audio_bio')->where(['id'=>['IN',$lists]])->select();
            $result = list_domain_image($result,['avatar,audio_bio']);
        }

        //tag任务赠送金币
        //缘分匹配奖励  +5金币
        if(!empty($result)){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,10);
            if($task_rs === false){
                $this->error('完成任务赠送奖励失败');
            }
        }
        $this->success('success',$result);
    }

    //过滤规则
    private function fliter_user($lists,$number = 1){

        if(empty($lists)){
            return $lists;
        }
        //dump($lists);

        //过滤掉通话中的
        foreach($lists as $key => $val){
            if(redis_matching_get($val['id']) == 1){
                unset($lists[$key]);
            }
        }

        //预留全部
        $all_result = array_column($lists,'id');
        //dump($all_result);

        //提取同城的
        $citydata = [];
        foreach($lists as $key => $val){
            if( !empty($this->auth->cityname) && $this->auth->cityname == $val['cityname'] ){
                $citydata[] = $val['id'];
            }
        }
        //dump($citydata);

        //有标签交集的
        $tagdata = [];
        foreach($lists as $key => $val){
            if( !empty($this->auth->tag_ids) && !empty($val['tag_ids']) ){

                $auth_tag_ids = explode(',',$this->auth->tag_ids);
                $val_tag_ids  = explode(',',$val['tag_ids']);
                if(count(array_intersect($auth_tag_ids,$val_tag_ids)) > 0){
                    $tagdata[] = $val['id'];
                }
            }
        }
        //dump($tagdata);

        //双条件都满足
        $double_data = [];
        if(!empty($citydata) && !empty($tagdata)){
            $double_data = array_intersect($citydata,$tagdata);
        }
        //dump($double_data);
        if(count($double_data) >= $number){
            return $double_data;
        }

        //两种条件合并，去重。空数组合并没影响
        $merge_data = array_merge($citydata,$tagdata);
        $merge_data = array_flip(array_flip($merge_data));
        //dump($merge_data);
        if(count($merge_data) >= $number){
            return $merge_data;
        }

        return $all_result;
    }

    /**
     * 是否关注
     */
    public function isFollows() {
        $user_id = $this->request->request("user_id",0,"intval");

        if (!$user_id || $user_id<=0) {
            $this->error(__('Invalid parameters'));
        }

        $map = [
            'uid' => $this->auth->id,
            'follow_uid' => $user_id,
        ];
        $check = Db::name('user_follow')->where($map)->find();

        $data = [];
        if($check){
            $data["is_show_follow"] = 0;
        }else{
            $data["is_show_follow"] = 1;
        }

        $this->success("获取成功！",$data);
    }

    /**
     * 获取主播技能分类
     */
    public function getAnchorType() {
        $this->success("获取成功！",\app\common\model\UserAnchorType::select());
    }

    /**
     * 主播申请
     */
    public function anchorApply() {
        $this->error('不需要申请');
        /*$type_id = $this->request->request('type_id'); // 技能分类ID
        $desc = $this->request->request('desc'); // 申请备注
        if (!$type_id && !$desc) {
            $this->error(__('Invalid parameters'));
        }
        $useranchorModel = new \app\common\model\UserAnchor();
        $data = [];
        $data["user_id"] = $this->auth->id;
        $data["type_id"] = $type_id;
        if($useranchorModel->where($data)->find()) $this->error(__('您已申请过该类型的主播，请勿重复申请！'));
        $data["desc"] = $desc;
        $data["createtime"] = time();
        $res = $useranchorModel->insertGetId($data);
        if($res) {
            \app\common\model\User::update(["is_anchor"=>1],["id"=>$this->auth->id]);
            $this->success("申请发送成功！");
        } else {
            $this->error("网络错误，请稍后重试");
        }*/
    }

    /**
     * 获取当前用户信息
     */
    public function getMyUserInfo() {
        $userInfo = $this->auth->getUserinfo();
        //当月消费金额
        $redis = new Redis();
        $redisconfig = config("redis");
        $redis->connect($redisconfig["host"], $redisconfig["port"]);
        $user_renew2 = $redis->get('user_renew2_'.$this->auth->id);
        $userInfo['user_renew2'] = empty($user_renew2)?0:intval($user_renew2);

        $this->success("获取成功！",$userInfo);
    }


    /**
     * calc_map_distance() , 根据地图上的两个点各自的x,y坐标，计算出2点之间的直线距离
     * @param array $point_1 第1个点的x,y坐标    array( 101 , 202 )
     * @param array $point_2 第2个点的x,y坐标    array( 101 , 202 )
     * @param bool $calc_as_string 是否计算为字符串公里距离 , 如果未否返回数字
     * @return float | false | string
     */
    private function calc_map_distance( $point_1=array(  ) , $point_2=array(  ) , $calc_as_string=false ) {
        if( empty( $point_1 ) || empty( $point_2 ) ){
            return false;
        }
        // 经纬度不存在，或者经纬度超过最大范围 +-180 , +-90 ，返回false
        $p1_x = $point_1[0];
        $p1_y = $point_1[1];

        $p2_x = $point_2[0];
        $p2_y = $point_2[1];
        if(
            $p1_x < -180 || $p1_x > 180
            || $p2_x < -180 || $p2_x > 180
            || $p1_y < -90 || $p1_y > 90
            || $p2_y < -90 || $p2_y > 90
        ){
            return '0公里';
        }

        // 根据2点各自的坐标，计算2点之间直线距离的公式
        $distance = round(6378.138*2*asin(sqrt(pow(sin(( $p1_x *pi()/180-$p2_x*pi()/180)/2),2)+cos( $p1_x *pi()/180)*cos($p2_x*pi()/180)* pow(sin(( $p1_y *pi()/180-$p2_y*pi()/180)/2),2)))*1000);

        // 是否计算为字符串公里距离
        if( !$calc_as_string ){
            return (string)round( $distance / 1000 , 1 ) . '公里';
        }

        // 如果计算为字符串公里距离
        if( $distance / 1000 > 1 ){
            $k = (string)round( $distance / 1000 , 1 );
            $m = (string)$distance % 1000 ;
            $distance = "{$k}公里{$m}米";
        }
        else{
            $distance = "{$distance}米";
        }
        return $distance;
    }

    //地图api,根据两地坐标，获得两地距离，打卡用的
    //type=0直线，type=1开车
    private function getmapjuli($start_lon,$start_lat,$end_lon,$end_lat,$type = 0){
        $result = 0;

        $apiurl = 'https://restapi.amap.com/v3/distance?';

        $param = [
            'key' => '398c424811d1a59beac2f915323d334e',
            'origins' => $start_lon.','.$start_lat,
            'destination' => $end_lon.','.$end_lat,
            'type' => $type,
            'output' => 'json',
        ];

        $apiurl .= http_build_query($param);

        $request_rs = json_decode(curl_get($apiurl),true);
        if(isset($request_rs['status']) && $request_rs['status'] == 1){
            if(isset($request_rs['results'][0]['distance']))
            {
                $result = $request_rs['results'][0]['distance'];
            }
        }

        //dump($result);

        return $result;
    }

    public function distance()
    {
        $a = $this->calc_map_distance([118.339282,35.028445],[118.437399,35.017438]);
        dump($a);
        $a = $this->calc_map_distance([118.339282,35.028445],[118.437399,35.017438],true);
        dump($a);
        $b = $this->getmapjuli(118.339282,35.028445,118.437399,35.017438,1);
        dump($b);
        $b = $this->getmapjuli(118.339282,35.028445,118.437399,35.017438,0);
        dump($b);
    }

}
