<?php

include_once (DISCUZ_ROOT.'source/discuz_version.php');

require_once 'includes/gotye.php';

$ctl_obj = new GoTye_ctl();

//获取附近的人列表

$coordinate_list =array();

if($_GET['type']=='getDistance'){



    if(empty($_GET['uid'])){

		odz_error('param error');

	}

    $result = array();

    $page       = isset($_GET['page'])?trim($_GET['page']):1;

    $offset     = ($page-1)*20;

    $order      = '';

    $gender     = isset($_GET['gender'])?$_GET['gender']:'';

    $uid        = $_GET['uid'];

    

    if($gender ==1){

            $order = ' and p.gender = 1 ';

    }

    if($gender == 2){

            $order = ' and p.gender = 2 ';

    }

    

    $coordinate = DB::fetch_first('SELECT uid,latitude,longitude,datetime  FROM '.DB::table('mocuz_member_coordinate')." WHERE uid = '$_GET[uid]'");

    $coords  = $ctl_obj->getAround($coordinate['latitude'],$coordinate['longitude']);

    $coordinate_list = DB::fetch_all('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 != {$_GET['uid']} and m.latitude > {$coords['minLat']} and m.latitude< {$coords['maxLat']} and m.longitude > {$coords['minLng']} and m.longitude < {$coords['maxLng']} {$order} order by datetime desc limit ".$offset.", 200" );



   //附近的人坐标数据

    foreach ($coordinate_list as $k =>$v ){

            $uids[] = $v['uid'];

    }

    //去除重复的uid 造成原因 未知

    if(!empty($uids)){

            foreach ($coordinate_list as $v){

                    $temp[]=$v['uid'];

            }

            $temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组

            $uids = array_unique($uids);

            foreach ($temp as $k => $v){

                    $temp[$k]=$coordinate_list[$k];   //再将拆开的数组重新组装

            }

            $coordinate_list = array_values($temp);

            $uids = array_values($uids);

    }

    if(!empty($coordinate_list)){

            $query = DB::query('SELECT c.uid,c.gender,c.birthyear,c.birthmonth,c.birthday ,c.affectivestatus,f.sightml  FROM '.DB::table('common_member_profile').' as c inner join '.DB::table('common_member_field_forum').' as f '.

                    " on c.uid=f.uid WHERE c.uid in (".implode(',', $uids).")");

                while($row = DB::fetch($query)){

                        foreach($coordinate_list as $k => $v ){

                                if( $v['uid'] == $row['uid']){

                                        $coordinate_list[$k] = array_merge($v,$row);

                                        $coordinate_list[$k]['space_data'] = DB::fetch_first('SELECT * FROM '.DB::table('common_member')." where uid = {$v['uid']}");

                                        $coordinate_list[$k]['distance'] =  $ctl_obj->getDistance($coordinate['latitude'], $coordinate['longitude'], $v['latitude'], $v['longitude']);

                                }

                        }

                }

                //判断是否为好友关系

                $friends = DB::fetch_all('SELECT fuid FROM '.DB::table('home_friend').' WHERE uid = '.$_GET['uid']);

                foreach($friends as $k=>$v ){

                        $fuids[] = $v['fuid'];

                }

               //拼装数据

                foreach($coordinate_list as $k => $v ){

                 //是否在对方黑名单

                $checkbid = DB::fetch_first('SELECT * FROM '.DB::table('mocuz_blackfriend')." WHERE uid = {$v['uid']} AND bid = {$_GET['uid']}");

                //是否是自己黑名单

                $isblack = DB::fetch_first('SELECT * FROM '.DB::table('mocuz_blackfriend')." where uid = '".$_G['uid']."' AND bid = {$v['uid']}");

                        $result[] = array(

                                'uid' => (string)$v['uid'],

                                'username' => (string)$v['space_data']['username'],

                                'gender' => !empty($v['gender'])?$v['gender']:'0',

                                'age' => !empty($v["birthyear"])?age($v["birthyear"].'-'.$v["birthmonth"].'-'.$v["birthday"]):'',

                                'affectivestatus' => !empty($v['affectivestatus'])?$v['affectivestatus']:odz_lang('secrect'),

                                'sightml' => !empty($v['sightml'])?(strip_tags($v['sightml'])?strip_tags($v['sightml']):odz_lang('no_message_left')):odz_lang('no_message_left'),

                                'regdate' => date('Y-m-d',$v['space_data']['regdate']),

                                'avatar'=> avatar($v['uid'], 'middle', true),

                                'distance' => (string)round(($v['distance']/1000),2),

                               // 'datetime' => $ctl_obj->time_tran($v['datetime']),

                                'datetime'=>$ctl_obj->my_date_format($v['datetime'],'Y-m-d'),

                                'isfriends' => in_array($v['uid'],$fuids)?'1':'0',

                                'inblack'=>!empty($checkbid)?'1':'0',

                                'isblack'=>!empty($isblack)?'1':'0',

                        );

                }

    }

    odz_result(array('list'=>$result));

  

  

//获取附近的人个人资料  

}else if($_GET['type']=='profile'){

    

	if(empty($_GET['uid']) || empty($_GET['user_uid'])){

		odz_error('param error');

	}

        $credits = DB::fetch_first('SELECT credits FROM '.DB::table('common_member')." WHERE uid = '$_GET[user_uid]'");

        $age="";

        $space  = DB::fetch_first('SELECT * FROM '.DB::table('common_member')." where uid = {$_GET['user_uid']}");

        $sightml= DB::fetch_first('SELECT sightml FROM '.DB::table('common_member_field_forum')." WHERE uid = '$_GET[user_uid]'");

        $user = DB::fetch_first('SELECT gender,birthyear,birthmonth,birthday ,affectivestatus FROM '.DB::table('common_member_profile')." WHERE uid = '$_GET[user_uid]'");

        if($user['birthyear']){

          $age=$ctl_obj->age($user[birthyear].'-'.$user[birthmonth].'-'.$user[birthday]);  

        }

        if(!$space){

            odz_error('member_nonexistence');

        }

        $profile = array(

          'uid' => $space['uid'],

          'gender' => empty($user['gender'])?'0':$user['gender'],

          'username' => (string)$space['username'],

          'regdate' => date("Y-m-d",$space['regdate']),

          'sightml' => !empty($sightml['sightml'])?(strip_tags($sightml['sightml'])?strip_tags($sightml['sightml']):odz_lang('no_message_left')):odz_lang('no_message_left'),

          'affectivestatus'=>$user['affectivestatus']?$user['affectivestatus']:odz_lang('secrect'),

          'age' => (string)$age,

          'regdate'=>date("Y-m-d",$space['regdate']),

          'avatar' => avatar($space['uid'], 'small', true),

          'credits'=>!empty($credits['credits'])?(string)$credits['credits']:'0',

        );

       

        //判断inblack isblack

        $inblack = '0';//对方黑名单 

        $isblack = '0';//自己黑名单

        $bid = $_GET['user_uid'];

        $checkisblack = DB::fetch_first('SELECT * FROM '.DB::table('mocuz_blackfriend')." where uid = '".$_G['uid']."' AND bid = {$bid}");

        if($checkisblack){$isblack = '1';}

        $checkinblack = DB::fetch_first('SELECT * FROM '.DB::table('mocuz_blackfriend')." where uid = {$bid} AND bid = '".$_G['uid']."'");

        if($checkinblack){$inblack = '1';}

        

        $profile['inblack'] =  $inblack;

        $profile['isblack'] =  $isblack;

        unset($space);

        // 我的帖子(取最近一条)

        $thread = DB::fetch_first('SELECT subject FROM '.DB::table('forum_thread')." WHERE authorid = '$_GET[user_uid]' AND closed = 0 AND displayorder !=-1 AND fid != '".$_G['mocuz_config']['share_fid']."' ORDER BY dateline desc limit 0,1");

        $profile['subject'] = empty($thread['subject'])?'':$thread['subject'];

        //我的坛友圈(取最近3条)

        $imagelist =array();

        $query = DB::query('SELECT *  FROM '.DB::table('forum_post')." WHERE authorid = '".$_GET[user_uid]."' AND fid = '".$_G['mocuz_config']['share_fid']."' AND invisible=0 AND attachment=2 ORDER BY dateline desc limit 0,3");

        while($row = DB::fetch($query)){

               $thread_list[] = $row; 

        }

         require_once libfile('function/attachment');

         require_once 'includes/functions/attachment.php';

         foreach($thread_list as $keys => $forum_threads) {

                $forum_thread_lists=$forum_threads;

                $_G['tid']=$forum_threads['tid'];



                odz_parseattach($forum_threads['pid'], '', $forum_thread_lists, '');

                foreach($forum_thread_lists[$forum_threads['pid']]['attachments'] as  $attach) {

                    if ($attach['isimage'] != 0) {

                            $url_ex=$attach['url_ex'];

                    }

                }

                $imagelist[] = $url_ex;

        }

        $profile['friends_circle'] = $imagelist;

        odz_result(array('list'=>$profile));

//跟新经纬度坐标

}else if($_GET['type']=='coordinate'){

	if(empty($_GET['uid'])){

		odz_error('param error');

	}

    $coordinate = DB::fetch_first('SELECT uid,latitude,longitude,datetime  FROM '.DB::table('mocuz_member_coordinate')." WHERE uid = '$_GET[uid]'");

    

	if(DISCUZ_VERSION == 'X2.5'){

		$num =  DB::fetch_all('SELECT count(*) FROM '.DB::table('home_notification')." WHERE uid = '$_GET[uid]' AND type='friend' AND new=1 AND from_idtype='friendrequest' ");

	}else{

		 $num =  DB::fetch_all('SELECT count(*) FROM '.DB::table('home_notification')." WHERE uid = '$_GET[uid]' AND type='friend' AND new=1 AND category=2 AND from_idtype='friendrequest' ");

	}

		

	$num = $num[0]['count(*)']?(string)$num[0]['count(*)']:'';

    

    if(empty($coordinate)){

        $data1=array('uid' => $_GET['uid'], 'latitude' => $_GET['latitude'],'longitude' => $_GET['longitude'],'datetime' => time());

        if($_GET['platform'] == 'ios'){

                bd_encrypt($_GET['longitude'],$_GET['latitude']);

        }

        if(DB::insert('mocuz_member_coordinate',$data1)){

            odz_result(array('num'=>$num));

        }else{

            odz_result(array('errcode'=>-1));

        }

    }else{

        if($coordinate['latitude'] && $coordinate['longitude']){

            $data1=array('latitude' => $_GET['latitude'],'longitude' => $_GET['longitude'],'datetime' => time());

             DB::update('mocuz_member_coordinate', $data1, array(

                'uid' => $_GET['uid']

            ));

        }

        odz_result(array('num'=>$num)); 

    }

}else if($_GET['type']=='business'){

//附近商家

	$result = array();

	$arr = array();

	$page       = isset($_GET['page'])?trim($_GET['page']):1;

    $offset     = ($page-1)*20;

    $order      = '';



	$result = DB::fetch_all('SELECT c.uid,c.username,f.sightml  FROM '.DB::table('common_member').' as c inner join '.DB::table('common_member_field_forum').' as f '.

                    " on c.uid=f.uid WHERE c.groupid = 34 limit ".$offset.", 20");



	$count = DB::fetch_all('SELECT count(*)  FROM '.DB::table('common_member').' as c inner join '.DB::table('common_member_field_forum').' as f '.

                    " on c.uid=f.uid WHERE c.groupid = 34 ");

	foreach($result as $k=>$v){



		$arr[] = array(

			'uid' =>$v['uid'],

			'avatar'=>avatar($v['uid'], 'small', true),

			'sightml' => !empty($v['sightml'])?(strip_tags($v['sightml'])?strip_tags($v['sightml']):odz_lang('no_message_left')):odz_lang('no_message_left'),

			'username'=>(string)$v['username'],

		

		);

	}



	odz_result(array('list'=>$arr,'counts'=>!empty($count[0]['count(*)'])?(string)($count[0]['count(*)']):'0','page_count'=>!empty($count[0]['count(*)'])?(string)(ceil(($count[0]['count(*)'])/20)):'0')); 

}



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);

    $data1['longitude'] = $z * cos($theta) + 0.0065;

    $data1['latitude'] = $z * sin($theta) + 0.006;

    return $data1;

}

?>