<?php

// 获取用户附近的圈子
require_once ("../user_include.inc");

ErrorLogger::doOutput("Compass...ajax_get_nearby_circle_list.php....Start.", 0);

//获取参数
$unionId = ParamUtil::getRequestString("unionId");
$longitude = ParamUtil::getRequestString("longitude");//用户位置的经度
$latitude = ParamUtil::getRequestString("latitude");//用户位置的纬度

$result = array();

//参数检查
if(empty($unionId) || empty($longitude) || empty($latitude)) {
	$result["message"] = "参数错误！";
	responseNG($result);
}

//判断用户是否存在
$param = array();
$param['unionid'] = $unionId;
$param['delete_flg'] = false;
$userList = UserMst::getList($param,'id','desc', 0, 1);
if(empty($userList)) {
	$result["message"] = "用户不存在！";
	responseNG($result);
}

$userMst = $userList[0];

//获取用户当前所处的区县
$lbsUrl = 'https://apis.map.qq.com/ws/geocoder/v1?key=' . LBS_KEY . '&location=' . $latitude . ',' . $longitude;
$lbsObj =  file_get_contents($lbsUrl);
$jsonObj = json_decode($lbsObj); //对JSON格式的字符串进行编码
$lbsArray = get_object_vars($jsonObj);//转换成数组
$resultObj = $lbsArray['result'];
if($lbsArray['status'] != "0" || $resultObj->ad_info->nation_code!=156) {
	$result["message"] = "位置信息错误！";
	responseNG($result);
}

$province = $resultObj->address_component->province;
$city = $resultObj->address_component->city;
$district = $resultObj->address_component->district;

//获取用户附近的圈子
$circleList = array();

//查询圈子列表
$param = array();
$param['province'] = $province;
$param['city'] = $city;
$param['district'] = $district;
$param['delete_flg'] = false;
$tmpCircleList = CircleDat::getList($param,'id','desc');

//循环计算距离当前的距离
if(!empty($tmpCircleList)) {
	foreach($tmpCircleList as $tmp) {
		$from = $latitude . "," . $longitude;
		$to = $tmp->latitude . "," . $tmp->longitude;
		
		//距离比较
		$distanceUrl = 'https://apis.map.qq.com/ws/distance/v1/?from=' . $from . '&key=' . LBS_KEY . '&mode=driving&to=' . $to;
		$distanceObj =  file_get_contents($distanceUrl);
		$jsonObj = json_decode($distanceObj); //对JSON格式的字符串进行编码
		$distanceArray = get_object_vars($jsonObj);//转换成数组
		if($distanceArray['status'] == "0" && $distanceArray['result']->elements[0]->distance <= 3000) {
			$circleList[] = array("circle_id"=>$tmp->id, "circle_title"=>$tmp->title, "member_count"=>$tmp->member_count, "front_image"=>$tmp->front_image);
		}
	}
}


//组装返回数据
$result["circleList"] = $circleList;

ErrorLogger::doOutput("Compass...ajax_get_nearby_circle_list.php....End.", 0);

//返回结果
responseOK($result);

function responseNG($result) {
	$result = array("status"=>"NG", "result"=>$result);
	print json_encode($result);
	exit;
}
function responseOK($result) {
	$result = array("status"=>"OK", "result"=>$result);
	print json_encode($result);
	exit;
}
?>