<?php

// 获取管辖区域内学校排名
require_once ("../user_include.inc");

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

//获取参数
$unionId = ParamUtil::getRequestString("unionId");
$page = ParamUtil::getRequestNumber("page", 0);

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

$result = array();

//判断用户是否存在
$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];

//管辖区域
$province = $userMst->province;
$city = $userMst->city;
$district = $userMst->district;

//管辖区域内学校数量以及列表
//todo：后面改成从别的系统获取
//每页显示条数
$rowCount = 15;
$offset = $page * $rowCount;


$param = array();
$param['province'] = $province;
if(!empty($city)) {
	$param['city'] = $city;
}
if(!empty($district)) {
	$param['district'] = $district;
}
$param['delete_flg'] = false;
$tmpList = SchoolMst::getList($param, 'province', 'asc, city asc, district asc', $offset, $rowCount);
$schoolCount = SchoolMst::getListCount($param);
$pageCount = ceil($schoolCount/$rowCount);

$schoolList = array();
//查询每所学校的能力分汇总
if(!empty($tmpList)) {
	foreach($tmpList as $tmp) {
		$sql = "select sum(ability_point) as ability_point from user_mst where delete_flg = false and school_no='{$tmp->school_no}' and original_source='{$tmp->original_source}'";
		$db = &CompassDBManager::getInstance();
		$tmpPointList = $db->executeQuery($sql);
		if($tmpPointList[0]['ability_point'] > 0) {
			$tmp->ability_point = $tmpPointList[0]['ability_point'];
		} else {
			$tmp->ability_point = "0";
		}

		$schoolList[] = $tmp;
	}
}


//能力分汇总
$abilityPoint = 0;
$sql = "select sum(ability_point) as ability_point from user_mst where delete_flg = false and school_no is not null and province='{$province}'";
if(!empty($city)) {
	$sql .= " and city='{$city}'";
}
if(!empty($district)) {
	$sql .= " and district='{$district}'";
}

$db = &CompassDBManager::getInstance();
$tmp = $db->executeQuery($sql);
if(!empty($tmp)) {
	$abilityPoint = $tmp[0]['ability_point'];
}

//接口返回数据
$result["page"] = $page;
$result["rowCount"] = $rowCount;
$result["pageCount"] = $pageCount;
$result["schoolCount"] = $schoolCount;
$result["schoolList"] = $schoolList;
$result["abilityPoint"] = $abilityPoint;

ErrorLogger::doOutput("Compass...ajax_get_area_info.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;
}
?>