<?php

/** ==============================================================
 * Created for lbs api.
 * Author: Allen zhang
 * Date: 2016-05-04
 */

#用户登录验证
if( empty($_G['uid']) ){
        odz_error('no_login');
}
needParams(array('type'));
isset($_GET['type']) && $_GET['type'] == 'getDistance' ? getList() : updateLocal();

/* 
 * 获取客户端附近的人列表页数据
 * ==============================================================
 * @param auth              | 用户必须登录
 * @param page_size         | 暂无分页，默认取前200条数据
 * @param gender            | 筛选的用户性别 0 保密 1 男 2 女 空字符 全部
 * ==============================================================
 */
function getList(){
    
        global $_G;
        $condition          = '';
        $result             = array();
        if( isset($_GET['gender']) && in_array($_GET['gender'],array('1','2')) ){
                $condition  = " and p.gender = {$_GET['gender']} ";
            
        }
        #获取用户经纬度
        $location       = DB::fetch_first('SELECT uid,latitude,longitude,datetime  FROM '.DB::table('mocuz_member_coordinate')." WHERE uid = {$_G['uid']}");
        #此经纬度为原点的一定半径内的坐标范围
        $locationRang   = getAround($location['latitude'],$location['longitude']);
        #默认取 前200条数据
        $lbsSql         = 'SELECT m.uid,m.latitude,m.longitude,m.datetime,p.gender,p.birthyear,p.affectivestatus,p.birthmonth,p.birthday  FROM '.DB::table('mocuz_member_coordinate').' as m inner join '.DB::table('common_member_profile').' as p '.
            " on m.uid=p.uid WHERE m.uid != {$_G['uid']} and m.latitude > {$locationRang['minLat']} and m.latitude< {$locationRang['maxLat']} and m.longitude > {$locationRang['minLng']} and m.longitude < {$locationRang['maxLng']} {$condition} order by datetime desc limit 0 , 200" ;
        #根据uid 获取用户资料
            
        $lbsQuery       = DB::query($lbsSql);
        while(  $v = DB::fetch($lbsQuery)   ){
                $userInfo          = getUserInfo($v['uid']);
                $result[]      = array(
                        'uid'           => (string)$v['uid'],
                        'username'      => $userInfo['username'],
                        'gender'        => (string)$v['gender'],
                        'sightml'       => !empty($userInfo['sightml'])?(strip_tags($userInfo['sightml'])?strip_tags($userInfo['sightml']):odz_lang('no_message_left')):odz_lang('no_message_left'),
                        'avatar'        => avatar($v['uid'], 'small', true),
                        'gender'        => (string)$v['gender'],
                        'distance'      => (string)round(getDistance($location['latitude'],$location['latitude'],$v['latitude'],$v['latitude']),2),
                        'datetime'      => my_date_format($v['datetime'],'Y-m-d'),
                        'inblack'       => DB::fetch_first('SELECT * FROM '.DB::table('mocuz_blackfriend')." WHERE uid = {$v['uid']} AND bid = {$_G['uid']}") ? '1' : '0',
                        'isblack'       => DB::fetch_first('SELECT * FROM '.DB::table('mocuz_blackfriend')." WHERE uid = {$_G['uid']} AND bid = {$v['uid']}") ? '1' : '0',
                );
            
        }
        #二维数组 排序 按距离大小
        if(!empty($result)){
                odz_array_sort($result, 'distance');
        }
        
        odz_result(array('list'=>$result));
        
}

/* 
 * 更新用户坐标(注意 IOS Android 经纬度统一)
 * ==============================================================
 * @param auth              | 用户必须登录
 * @param page_size         | 暂无分页，默认取前200条数据
 * @param gender            | 筛选的用户性别
 * ==============================================================
 */

function updateLocal(){
    
        global $_G;
        needParams(array('latitude','longitude','platform'));
        $location       = DB::fetch_first('SELECT * FROM '.DB::table('mocuz_member_coordinate')." WHERE uid = {$_G['uid']}");
        $data           = $_GET['platform'] == 'ios' ? bd_encrypt($_GET['longitude'],$_GET['latitude']) : array('latitude'=>$_GET['latitude'],'longitude'=>$_GET['longitude'],'datetime'=>time(),'uid'=>$_G['uid']);
       
        DB::delete('mocuz_member_coordinate', array('uid'=>$_G['uid']));
        DB::insert('mocuz_member_coordinate',$data) ? odz_success() : odz_error('mysql_error');

}



# 获得半径内的经纬度坐标范围
function  getAround( $lat, $lng ,$raidus=18000) {

        $data           = array();
        $PI             = 3.14159265;
        $EARTH_RADIUS   = 6378137;
        $RAD            = $PI / 180.0;
        $latitude       = $lat;
        $longitude      = $lng;
        $degree         = (24901*1609)/360.0;
        $raidusMile     = $raidus;
        $dpmLat         = 1/$degree;
        $radiusLat      = $dpmLat*$raidusMile;
        $minLat         = $latitude - $radiusLat;
        $maxLat         = $latitude + $radiusLat;
        $data["maxLat"] = $maxLat;
        $data["minLat"] = $minLat;
        $mpdLng         = $degree*cos($latitude * ($PI/180));
        $dpmLng         = 1 / $mpdLng;
        $radiusLng      = $dpmLng*$raidusMile;
        $minLng         = $longitude - $radiusLng;
        $maxLng         = $longitude + $radiusLng;
        $data["maxLng"] = $maxLng;
        $data["minLng"] = $minLng;

        return $data;
}


# 根据两点间的经纬度计算距离
function getDistance($lat1, $lng1, $lat2, $lng2){
    
        #approximate radius of earth in meters
        $earthRadius = 6378137; 
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        if(round($calculatedDistance)>=0 && round($calculatedDistance)<=100){
            return 100;
        }else if(round($calculatedDistance)>100 && round($calculatedDistance)<=200){
            return 200;
        }else if(round($calculatedDistance)>200 && round($calculatedDistance)<=300){
            return 300;
        }else if(round($calculatedDistance)>300 && round($calculatedDistance)<=400){
            return 400;
        }else{
            return round($calculatedDistance);
        }
}

#获取基础参数
function needParams($params = array()) {
    
        if(!is_array($params)){
                $params = array($params);
        }
        foreach($params as $param) {
                if(!in_array($param, array_keys($_GET)) ) {
                        odz_error('param '.$param.' is need');
                }
        }
}

#组装用户信息
function getUserInfo($uid){
            
            $userSql            = "SELECT m.username , f.sightml FROM ".DB::table('common_member')." as m LEFT JOIN ".DB::table('common_member_field_forum')." as f ON  m.uid = f.uid WHERE m.uid = {$uid}";
            return  DB::fetch_first($userSql);
}

#统一 安卓 ios 坐标
function bd_encrypt($gg_lon,$gg_lat){
    global $_G;
    $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);
    $data['longitude']  = $z * cos($theta) + 0.0065;
    $data['latitude']   = $z * sin($theta) + 0.006;
    $data['datetime']   = time();
    $data['uid']        = $_G['uid'];
    return $data;
}

odz_error('param_error');