<?php
/**
 * functions.php
 * 本文件定义了后台管理的一些函数。
 */

require_once("database.php");
require_once("dbconfig.php");
require_once("EmayClient.class.php");

/**
 * 利用$_POST数据登陆系统
 * @return mix 如果成功，返回true，否则返回失败原因字符串。应该使用“===true”来判断是否成功。
 */
function login(){
	//准备数据
	$username = addslashes(trim($_POST["username"]));
	$password = addslashes(trim($_POST["password"]));
	
    $db = db_connect();
    
    //查询数据库
    $sql = "SELECT `ID`, `Name`, `Privileges`, `Level`, `HeadID`, `Head`, `Ancestors`, " .
    		"`CityID`, `City`, `Realname` FROM `Agent` " .
    		"WHERE `Username`='{$username}' AND `Password`=MD5('{$password}') AND `Hide`=0;";
    $rs = $db->query($sql);
    
    //获取结果
    $re = false;
    
    if($rs->num_rows==1) {
    	$row = $rs->fetch_assoc();
		$_SESSION['admin_is_login'] = true;
		$_SESSION['admin_agent_id'] = $row["ID"];
		$_SESSION['admin_agent_name'] = $row["Name"];
		$_SESSION['admin_privileges'] = $row["Privileges"];
		$_SESSION['admin_level'] = $row["Level"];
		$_SESSION['admin_headid'] = $row["HeadID"];
		$_SESSION['admin_head'] = $row["Head"];
		$_SESSION['admin_ancestors'] = $row["Ancestors"];
		$_SESSION['admin_city_id'] = $row["CityID"];
		$_SESSION['admin_city'] = $row["City"];
		$_SESSION['admin_real_name'] = $row["Realname"];
		$_SESSION['admin_username'] = $username;
    	$_SESSION['admin_display_name'] = $row["Name"];
    	$re = true;

    	$_SESSION['admin_descendants'] = get_agent_descendants_set($row["ID"]); 
    	
		agent_log("登录", "成功。");
    }
    else {
    	$sql = "SELECT `ID`,`UUID`,`Name`,`Telephone`,`CityId`,`City`, " .
    			"`CityDefault`,`AgentId`,`Agent`,`Rating`,`Mobile`,`BusinessHour`, " .
    			"`ID`,`BusinessMemo`,`Fee`,`MinMoney`,`Scope`,`Discount`," .
    			"`Notice`,`Takeout`,`Latitude`,`Longitude`,`Address`,`Linkman`," .
    			"`LinkPhone`,`Keyword`,`Memo`,`LastUpdate`,`Commission`,`Username`,`AddTime`," .
    			"`DiscountIn`,`SaleAd`,`Staple`,`IsPrint`, " .
    			"`MEMBER_CODE`,`FEYIN_KEY`,`DEVICE_NO`" .
    			"FROM `Restaurant` " .
    			"WHERE `Username`='{$username}' AND `Password`=MD5('{$password}') AND `Hide`=0;";
    	$rs = $db->query($sql);
    	if($row = $rs->fetch_assoc()){ //餐馆登陆
			$_SESSION['admin_is_login'] = true;
			$_SESSION['admin_restaurant_id'] = $row["ID"];
			$_SESSION['admin_restaurant_name'] = $row["Name"];
			$_SESSION['admin_city_id'] = $row["CityId"];
			$_SESSION['admin_city'] = $row["City"];
			$_SESSION['admin_ragent_id'] = $row["AgentId"];
			$_SESSION['admin_ragent_name'] = $row["Agent"];
    		$_SESSION['admin_is_restaurant'] = true;
    		$_SESSION['admin_display_name'] = $row["Name"];
			$_SESSION['admin_privileges'] = '餐馆管理,我的餐馆,修改餐馆资料,添加餐品,删除餐品,修改餐品资料,订单管理,查看当前订单,查看历史订单,手工下单,财务管理,日销售额,月销售额,自定义查看销售额';

			$_SESSION['admin_thisrestaurant'] = '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"telephone":"'.$row['Telephone'].'", "cityid":'.$row['CityId'].', "city":"'.$row['City'].'", ' .
				'"citydefault":' . ( empty($row['CityDefault']) ? 'false, ' : 'true, ' ) .
				'"latitude":'.$row['Latitude'].', "longitude":'.($row['Longitude']+0).', ' .
				'"agentid":'.$row['AgentId'].', "agent":"'.$row['Agent'].'", ' .
				'"rating":'.$row['Rating'].', "mobile":"'.$row['Mobile'].'", ' .
				'"businesshour":"'.$row['BusinessHour'].'", "businessmemo":"'.$row['BusinessMemo'].'", ' .
				'"fee":'.($row['Fee']+0).', "minmoney":'.($row['MinMoney']+0).', ' .
				'"scope":'.($row['Scope']+0).', ' .
				'"discount":"'.((empty($row['Discount']) || ($row['Discount']+0==10))? "10" : ($row['Discount']+0)).'", ' .
				'"notice":"'.$row['Notice'].'", ' .
				'"takeout":' . ( empty($row['Takeout']) ? 'false, ' : 'true, ' ) .
				'"address":"'.$row['Address'].'", "linkman":"'.$row['Linkman'].'", ' .
				'"linkphone":"'.$row['LinkPhone'].'", "keyword":"'.$row['Keyword'].'", ' .
				'"memo":"'.$row['Memo'].'", "commission":'.($row['Commission']+0).',  ' .
				'"username":"'.$row['Username'].'",  "salead":"'.$row['SaleAd'].'", "staple":"'.$row['Staple'].'",  ' .
				'"isprint":' . ( ord($row['Takeout'])==0 ? 'false, ' : 'true, ' ) .
				'"membercode":"'.$row['MEMBER_CODE'].'",  "feyinkey":"'.$row['FEYIN_KEY'].'",  ' .
				'"deviceno":"'.$row['DEVICE_NO'].'",  ' .
				'"discountin":"'.((empty($row['DiscountIn']) || ($row['DiscountIn']+0==10))? "10" : ($row['DiscountIn']+0)).'", ' .
				'"addtime":"'.substr($row['AddTime'],0,10).'" ' .
				'}';
			restaurant_log("登录","成功。");
    		$re = true;
    	}
    	else {
			$sql = "INSERT INTO `AgentLog`(`AgentID`, `Name`, `CityID`, `OpTime`," .
					"`City`, `Realname`, `Username`, `IP`, `Operation`, `Data`) " .
					"VALUES('0',' ','0','".get_datetime()."',' ',' '," .
					"'{$username}','".get_client_ip()."','登录', '失败：用户名或者密码不正确')" ;
			$db->query($sql);		
	    	$re = "用户名或者密码不正确。";
    	}
    }
    
    //更新最后登录时间和IP
    if ( $re===true && empty($_SESSION['admin_is_restaurant']) ) {
    	$ip = get_client_ip();
    	$sql = "UPDATE `Agent` SET `LastIp`='{$ip}' , `LastTime`='".get_datetime()."' " .
    			"WHERE `ID`={$_SESSION['admin_agent_id']}";
    	$db->query($sql);
    }
    
    $db->close();
    
	return $re;
}

/**
 * 登出
 */
function logout() {
    if(isset($_SESSION['admin_is_restaurant'])){
    	restaurant_log("登出", "成功");
    }
    else {
    	agent_log("登出", "成功");
    }
	clear_session();
}

/**
 * 修改密码
 */
function change_password() {
	check_login();
	
	//准备数据
	$newpassword = addslashes(trim($_POST["newpassword"]));
	$oldpassword = addslashes(trim($_POST["oldpassword"]));
	if(empty($newpassword)) {
		agent_log("修改密码", "失败：新密码为空。");
		return error_json("新密码为空。");
	}
	if(empty($oldpassword)) {
		agent_log("修改密码", "失败：原密码为空。");
		return error_json("原密码为空。");
	}
	
    $re = "";
    $db = db_connect();
    
    $success = true;
    
    //查询数据库验证原密码
    $sql = "SELECT `ID` FROM `Agent` " .
    		"WHERE `ID`='{$_SESSION['admin_agent_id']}' AND `Password`=MD5('{$oldpassword}') AND `Hide`=0;";
    if(isset($_SESSION['admin_restaurant_id'])){
	    $sql = "SELECT `ID` FROM `Restaurant` " .
	    		"WHERE `ID`='{$_SESSION['admin_restaurant_id']}' AND `Password`=MD5('{$oldpassword}') AND `Hide`=0;";
    }
    $rs = $db->query($sql);
    if($rs->num_rows==1) {
    	//更新数据库
    	$sql = "UPDATE `Agent` SET `Password`=MD5('{$newpassword}') " .
    			"WHERE `ID`='{$_SESSION['admin_agent_id']}';";
    	if(isset($_SESSION['admin_restaurant_id'])) {
	    	$sql = "UPDATE `Restaurant` SET `Password`=MD5('{$newpassword}') " .
	    			"WHERE `ID`='{$_SESSION['admin_restaurant_id']}';";
    	}
    	$result = $db->query($sql);
    	
    	 //返回结果
	    $re = "";
	    if( $result!==FALSE ) {
	    	$re = success_json_no_data();
	    }
	    else {
	    	$success = "数据库更新失败。";
	    	$re = error_json( "数据库更新失败。" );
	    }
    }
    else {
    	$success = "原密码不正确。";
    	$re = error_json("原密码不正确。");
    }
    
    agent_log("修改密码", ($success===true? "成功" : "失败：".$success) );
    $db->close();
    return $re;
}

/**
 * 检查用户是否已经登录，如果没有则清除Session，并转到主页登录界面
 * 如果已经登录，返回true
 */
function check_login($nojson = false) {
	if( (!empty($_SESSION['admin_is_restaurant']) 
			&& (!isset( $_SESSION['admin_is_login'] ) || $_SESSION['admin_is_login']!=true 
				|| !isset($_SESSION['admin_restaurant_id']) 
				|| !isset($_SESSION['admin_restaurant_name'])
				|| !isset($_SESSION['admin_city_id'])
				|| !isset($_SESSION['admin_city'])
				|| !isset($_SESSION['admin_ragent_id'])
				|| !isset($_SESSION['admin_ragent_name'])
			)
		)
	 ||
	 	( empty($_SESSION['admin_is_restaurant'])
	 		&&(!isset( $_SESSION['admin_is_login'] ) || $_SESSION['admin_is_login']!=true 
				|| !isset( $_SESSION['admin_agent_id'] ) 
				|| !isset( $_SESSION['admin_agent_name'] ) 
				|| !isset( $_SESSION['admin_privileges'] ) 
				|| !isset( $_SESSION['admin_level'] ) 
				|| !isset( $_SESSION['admin_head'] ) 
				|| !isset( $_SESSION['admin_ancestors'] ) 
				|| !isset( $_SESSION['admin_city_id'] ) 
				|| !isset( $_SESSION['admin_city'] ) 
				|| !isset( $_SESSION['admin_real_name'] ) 
				|| !isset( $_SESSION['admin_username'] ) 
			)
		)
	)
	{
		clear_session();
		if($nojson) {
			header('Content-Type: text/html; charset=utf-8');
			header("Refresh: 3; url=index.php");
			die('<script type="text/javascript">alert("你还没有登录，3秒后将转到登录界面。");</script>');
		}
		else {//'{"success": false, "msg": "你还没有登录，即将转到登录界面。", "url": "index.php"}'
			die( error_json("你还没有登录，即将转到登录界面。", "index.php") );
		}
	}
	else {
		return true;
	}
}

/**
 * 检查权限（包括是否登陆）
 */
function check_privilege( $require ) {
	 return check_login() && strpos($_SESSION['admin_privileges'], $require)!==false;
}

/**
 * 清除session数据
 */
function clear_session() {
	date_default_timezone_set('PRC');
	session_destroy();
	setcookie(session_name(),'',time()-3600);
	$_SESSION = array();
}

/**
 * 根据权限获取菜单
 */
function get_menus(){
	check_login();
	//准备数据
	$privileges = get_privilege_set();
	if(empty($privileges)) return '{"success": true, "menus":[]}';
	
	$db = db_connect();
	
	//查询数据库
	$sql = "SELECT `IDText`, `Label`, `Icon`, `Widget`, `ShowAtHome`, `BigIcon` FROM `Menu` " .
			"WHERE `Label` IN({$privileges}) ORDER BY `IDText`; ";
	$rs = $db->query($sql);		
		
	$class1 = "";
	$menus_json = "";
	$menu_json = "";
	$sub_menu_json = "";
	$menu_json_not_close = false;
	while( $menu = $rs->fetch_assoc() ) {
		$id_text = $menu['IDText'];
		
		if ( substr($id_text,0,2) != $class1 ) { //遇到了新的菜单项			
			//如果$menu_json未关闭，则关闭
			if($menu_json_not_close){
				if ( substr($menu_json, -1, 1) == "," ) { //去掉末尾的一个小逗号
					$menu_json = substr($menu_json, 0, strlen($menu_json)-1);
				}
				$menu_json .= ']}';
				$menu_json_not_close = false;
				$menus_json .= $menu_json . ',';
			}
			$class1 = substr($id_text,0,2);
			$menu_json =  '{"label":"'.$menu['Label'].'","icon":"'.$menu['Icon'].'", "items": [';
			$menu_json_not_close = true;
		}
		else {
			$sub_menu_json = '{"label":"'.$menu['Label'].'","icon":"'.$menu['Icon'].'","widget":"'.$menu['Widget'].'", ';
			if($menu['ShowAtHome']){
				$sub_menu_json .= '"showAtHome":true, "bigIcon":"'.$menu['BigIcon'].'"}';
			}
			else {
				$sub_menu_json .= '"showAtHome":false}';
			}
			$menu_json .= $sub_menu_json . ",";
		}
	}
	
	if($menu_json_not_close){
		if ( substr($menu_json, -1, 1) == "," ) { //去掉末尾的一个小逗号
			$menu_json = substr($menu_json, 0, strlen($menu_json)-1);
		}
		$menu_json .= ']}';
		$menu_json_not_close = false;
		$menus_json .= $menu_json ;
	}
	
	$menus_json = "[".$menus_json."]";

	
	$re = '{"success": true, "menus":' . $menus_json . '}';
	
    $db->close();
    
	return $re;
}

/**
 * 将权限字符串从“a,b,c”变成“'a','b','c'”的形式
 */
function get_privilege_set() {
	check_login();
	if( !isset( $_SESSION['admin_privileges'] ) ) return "";
	
	$re = "";
	
	$privileges = explode ("," , $_SESSION['admin_privileges']);
	foreach ( $privileges as $privilege ) {
		$re .= ",'" . trim($privilege) . "'";
	}
	
	if ( strlen($re) > 0 )  $re = substr($re, 1);
	
	return $re;
}

/**
 * 获取城市的JSON列表
 * 总代理将获取到所有城市的列表，城市代理只能获取到本城市的列表（一条记录）
 */
function get_cities_json() {
	check_login();
	$re = "";
	$db = db_connect();
	
	$cityid = "";
	if ( $_SESSION['admin_city_id']!=0 ) {
		$cityid = $_SESSION['admin_city_id'];
	}
	
	$condition = empty($cityid) ? "" : " AND  `ID`='$cityid' ";
	
	$sql = "SELECT COUNT(`ID`) FROM `City` WHERE `Hide`=0 " . $condition;
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `Name`, `Latitude`, `Longitude`, `ZoomLevel`, `Sequence` FROM `City` " .
			"WHERE `Hide`=0 " . $condition .
			" ORDER BY `Sequence` ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "cities": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"latitude":'.$row['Latitude'].', "longitude":'.$row['Longitude'].', ' .
				'"zoomlevel":'.$row['ZoomLevel'].', "sequence":'.$row['Sequence'].'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	//for test
	//$re = '{"total":2, "cities":[{"id":1242,"name":"北京","latitude":39.9081809,"longitude":116.407413,"zoomlevel":14},{"id":2,"name":"广州","latitude":32.56345,"longitude":118.32424,"zoomlevel":15}]}';
	return $re;
}


/**
 * 获取自己及下级代理的JSON列表
 */
function get_agents_json() {
	check_login();
	
	$agent_id = $_SESSION['admin_agent_id'];
	
	$re = "";
	$db = db_connect();
	
	$sql = "SELECT COUNT(`ID`) FROM `Agent` " .
			"WHERE (`ID`='{$agent_id}' OR `Ancestors`='{$agent_id}' OR " .
			"`Ancestors` LIKE '{$agent_id}%' OR `Ancestors` LIKE '%,{$agent_id}' " .
			"OR `Ancestors` LIKE '%,{$agent_id},%') AND `Hide`=0";
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `Name`, `Level`, `Head`, `HeadID`, `Ancestors`, " .
			"`CityID`, `City`, `Username`, `Privileges`, `Realname`, " .
			"`Telephone`, `Mobile`, `Memo`,`AddDate` FROM `Agent` " .
			"WHERE (`ID`='{$agent_id}' OR `Ancestors`='{$agent_id}' OR " .
			"`Ancestors` LIKE '{$agent_id}%' OR `Ancestors` LIKE '%,{$agent_id}' " .
			"OR `Ancestors` LIKE '%,{$agent_id},%') AND `Hide`=0";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "agents": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"level":'.$row['Level'].', "head":"'.$row['Head'].'", "headid":'.$row['HeadID'].', ' .
				'"ancestors":"'.$row['Ancestors'].'", ' .
				'"cityid":'.$row['CityID'].', "city":"'.$row['City'].'", ' .
				'"username":"'.$row['Username'].'", "privileges":"'.$row['Privileges'].'", ' .
				'"realname":"'.$row['Realname'].'", "telephone":"'.$row['Telephone'].'",' .
				'"mobile":"'.$row['Mobile'].'", "memo":"'.$row['Memo'].'", "adddate":"'.$row['AddDate'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

/**
 * 利用$_POST的数据添加城市，返回操作结果的json
 */
function add_city() {
	//权限验证
	if( !check_privilege( "添加城市" ) ) {
		agent_log("添加城市", "城市名字：".trim($_POST["name"])."，失败：没有添加城市的权限。");
		die( error_json ( "没有添加城市的权限。" ) );
	}
	
	//准备数据
	$name = addslashes(trim($_POST["name"]));
	$latitude = addslashes(trim($_POST["latitude"]));
	$longitude = addslashes(trim($_POST["longitude"]));
	$zoomlevel = addslashes(trim($_POST["zoomlevel"]));
	if(empty($name)){
		agent_log("添加城市", "失败：城市名字为空。");
		return error_json("城市名字为空");
	}
	if(empty($latitude)){
		agent_log("添加城市", "城市名字：".$name."，失败：城市坐标纬度为空。");
		return error_json("城市坐标纬度为空");
	}
	if(empty($longitude)){
		agent_log("添加城市", "城市名字：".$name."，失败：城市坐标经度为空。");
		return error_json("城市坐标经度为空");
	}
	if(empty($zoomlevel)){
		agent_log("添加城市", "城市名字：".$name."，失败：城市地图缩放倍数为空。");
		return error_json("城市地图缩放倍数为空");
	}
	
	//数据库操作
    $db = db_connect();
    
    $sql = "SELECT MAX(`Sequence`) FROM `City` WHERE `Hide`=0;";
    $sr = $db->query($sql);
    $seq_to_be_row = $sr->fetch_row();
    $seq_to_be = $seq_to_be_row[0] + 1;
    
    $sql = "INSERT INTO `City`(`Name`,`Latitude`,`Longitude`,`ZoomLevel`,`Sequence`) " .
    		"VALUES('{$name}','{$latitude}','{$longitude}','{$zoomlevel}','{$seq_to_be}')";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE && $db->affected_rows==1 ) {
		agent_log("添加城市", "城市名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("添加城市", "城市名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 利用$_POST的数据更新城市信息，返回操作结果的json
 */
function update_city() {
	//权限验证
	if( !check_privilege( "修改城市信息" ) ) {
		agent_log("修改城市信息", "城市名字：".trim($_POST["name"])."，失败：没有修改城市信息的权限。");
		die( error_json ( "没有修改城市信息的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$latitude = addslashes(trim($_POST["latitude"]));
	$longitude = addslashes(trim($_POST["longitude"]));
	$zoomlevel = addslashes(trim($_POST["zoomlevel"]));
	if(empty($id)){
		agent_log("修改城市信息", "城市名字：".$name."，失败：系统错误：城市ID为空。");
		return error_json("系统错误：城市ID为空");
	}
	if(empty($name)){
		agent_log("修改城市信息", "失败：城市名字为空。");
		return error_json("城市名字为空");
	}
	if(empty($latitude)){
		agent_log("修改城市信息", "城市名字：".$name."，失败：城市坐标纬度为空。");
		return error_json("城市坐标纬度为空");
	}
	if(empty($name)){
		agent_log("修改城市信息", "城市名字：".$name."，失败：城市坐标经度为空。");
		return error_json("城市坐标经度为空");
	}
	if(empty($zoomlevel)){
		agent_log("修改城市信息", "城市名字：".$name."，失败：城市地图缩放倍数为空。");
		return error_json("城市地图缩放倍数为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `City` SET `Name`='{$name}',`Latitude`='{$latitude}',`Longitude`='{$longitude}',`ZoomLevel`='{$zoomlevel}' " .
    		"WHERE `ID`='{$id}'";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE) {
		agent_log("修改城市信息", "城市名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("修改城市信息", "城市名字：".$name."，失败：数据库更新失败。");
    	$re = error_json( "数据库更新失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 利用$_POST的数据删除城市，返回操作结果的json
 */
function delete_city() {
	//权限验证
	if( !check_privilege( "删除城市" ) ) {
		agent_log("删除城市", "城市名字：".trim($_POST["name"])."，失败：没有删除城市的权限。");
		die( error_json ( "没有删除城市的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$sequence = addslashes(trim($_POST["sequence"])) + 0;
	
	if(empty($id)){
		agent_log("删除城市", "失败：系统错误：城市ID为空。");
		return error_json("系统错误：城市ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    //先更新其他纪录的序号
    if($sequence>0){
    	$sql = "UPDATE `City` SET `Sequence`=`Sequence`-1 WHERE `Sequence`>'{$sequence}' AND `Hide`=0;";
    	$db->query($sql);
    }
    
    $sql = "UPDATE `City` SET `Hide`=1 WHERE `ID`='{$id}'" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("删除城市", "城市名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除城市", "城市名字：".$name."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 删除多个城市（由于目前使用单选模式，所以此方法已弃用)
 */
function delete_cities () {
	//权限验证
	if( !check_privilege( "删除城市" ) ) {
		agent_log("删除城市", "城市列表：".trim($_POST["names"])."，失败：没有删除城市的权限。");
		die( error_json ( "没有删除城市的权限。" ) );
	}
	
	//准备数据
	$ids = addslashes(trim($_POST["ids"]));
	$names = addslashes(trim($_POST["names"]));
	if(empty($ids)){
		agent_log("删除城市", "失败：系统错误：城市ID为空。");
		return error_json("系统错误：城市ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `City` SET `Hide`=1 WHERE `ID` IN ({$ids})" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE) {
		agent_log("删除城市", "城市列表：".$names."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除城市", "城市列表：".$names."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 根据$_POST['data']调整城市的顺序
 */
function sequence_city() {
	//权限验证
	if( !check_privilege( "修改城市信息" ) ) {
		agent_log("修改城市信息", "调整城市顺序失败：没有修改城市信息的权限。");
		die( error_json ( "修改城市信息的权限。" ) );
	}
	
	$data = addslashes(trim($_POST["data"]));
	if(empty($data)) {
		agent_log("修改城市信息", "调整城市顺序失败：提供的数据为空");
		die( error_json ( "数据为空。" ) );
	}
	$oldnews = explode(",", $data);
	if(count($oldnews)<2) { //至少应该有两组数据
		agent_log("修改城市信息", "调整城市顺序失败：提供的数据格式不正确");
		die( error_json ( "格式不正确。" ) );
	}
	
	$db = db_connect();
	foreach ( $oldnews as $oldnew ) {
		$a = explode(":", $oldnew);
		if(count($a)!=3) continue;
		
		$ID = $a[0]; $old = $a[1];  $new = $a[2];
		$sql = "UPDATE `City` SET `Sequence`='{$new}' " .
				"WHERE `ID`='{$ID}' AND `Sequence`='{$old}' ";
		$db->query($sql);
	}
	$db->close();
	return success_json_no_data();
}
/**
 * 获取一个城市的区域信息。
 */
function get_regions_json() {
	check_login();
	
	$cityid = addslashes(trim($_REQUEST["cityid"]));
	
	$re = "";
	$db = db_connect();
	$sql = "SELECT COUNT(`ID`) FROM `Region` WHERE `CityID`='{$cityid}' AND `Hide`=0;";
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
		
	$sql = "SELECT `ID`, `Name`, `CityID`, `City`, `Sequence`, " .
			"`Latitude`, `Longitude`, `ZoomLevel` FROM `Region` " .
			"WHERE `CityID`='{$cityid}' AND `Hide`=0 " .
			"ORDER BY `Sequence` ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "regions": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"cityid":'.$row['CityID'].', "city":"'.$row['City'].'", "sequence":'.$row['Sequence'].', ' .
				'"latitude":'.$row['Latitude'].', "longitude":'.$row['Longitude'].', "zoomlevel":'.$row['ZoomLevel'].'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

/**
 * 利用$_POST的数据添加区域区域，返回操作结果的json
 */
function add_region() {
	//权限验证
	if( !check_privilege( "添加区域" ) ) {
		agent_log("添加区域", "区域名字：".trim($_POST["name"])."，失败：没有添加区域的权限。");
		die( error_json ( "没有添加区域的权限。" ) );
	}
	
	//准备数据
	$name = addslashes(trim($_POST["name"]));
	$cityid = addslashes(trim($_POST["cityid"]));
	$city = addslashes(trim($_POST["city"]));
	$latitude = addslashes(trim($_POST["latitude"]));
	$longitude = addslashes(trim($_POST["longitude"]));
	$zoomlevel = addslashes(trim($_POST["zoomlevel"]));
	if(empty($name)){
		agent_log("添加区域", "失败：区域名字为空。");
		return error_json("区域名字为空");
	}
	if(empty($cityid) || empty($city)){
		agent_log("添加区域", "区域名字：".$name."，失败：区域所属城市为空。");
		return error_json("区域所属城市为空");
	}
	if(empty($latitude)){
		agent_log("添加区域", "区域名字：".$name."，失败：区域坐标纬度为空。");
		return error_json("区域坐标纬度为空");
	}
	if(empty($longitude)){
		agent_log("添加区域", "区域名字：".$name."，失败：区域坐标经度为空。");
		return error_json("区域坐标经度为空");
	}
	if(empty($zoomlevel)){
		agent_log("添加区域", "区域名字：".$name."，失败：区域地图缩放倍数为空。");
		return error_json("区域地图缩放倍数为空");
	}
	
	//数据库操作
    $db = db_connect();
    
    $sql = "SELECT MAX(`Sequence`) FROM `Region` WHERE `CityID`='{$cityid}' AND `Hide`=0;";
    $sr = $db->query($sql);
    $seq_to_be_row = $sr->fetch_row();
    $seq_to_be = $seq_to_be_row[0] + 1;
    
    $sql = "INSERT INTO `Region`(`Name`,`CityID`,`City`,`Latitude`,`Longitude`,`ZoomLevel`,`Sequence`) " .
    		"VALUES('{$name}','{$cityid}','{$city}','{$latitude}','{$longitude}','{$zoomlevel}','{$seq_to_be}')";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE && $db->affected_rows==1 ) {
		agent_log("添加区域", "区域名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("添加区域", "区域名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 利用$_POST的数据修改区域信息，返回操作结果的json
 */
function update_region() {
	//权限验证
	if( !check_privilege( "修改区域信息" ) ) {
		agent_log("修改区域信息", "区域名字：".trim($_POST["name"])."，失败：没有修改区域信息的权限。");
		die( error_json ( "没有修改区域信息的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$cityid = addslashes(trim($_POST["cityid"]));
	$city = addslashes(trim($_POST["city"]));
	$latitude = addslashes(trim($_POST["latitude"]));
	$longitude = addslashes(trim($_POST["longitude"]));
	$zoomlevel = addslashes(trim($_POST["zoomlevel"]));
	if(empty($id)){
		agent_log("修改区域信息", "失败：系统错误：区域id为空。");
		return error_json("系统错误：区域id为空");
	}
	if(empty($name)){
		agent_log("修改区域信息", "失败：区域名字为空。");
		return error_json("区域名字为空");
	}
	if(empty($cityid) || empty($city)){
		agent_log("修改区域信息", "区域名字：".$name."，失败：区域所属城市为空。");
		return error_json("区域所属城市为空");
	}
	if(empty($latitude)){
		agent_log("修改区域信息", "区域名字：".$name."，失败：区域坐标纬度为空。");
		return error_json("区域坐标纬度为空");
	}
	if(empty($longitude)){
		agent_log("修改区域信息", "区域名字：".$name."，失败：区域坐标经度为空。");
		return error_json("区域坐标经度为空");
	}
	if(empty($zoomlevel)){
		agent_log("修改区域信息", "区域名字：".$name."，失败：区域地图缩放倍数为空。");
		return error_json("区域地图缩放倍数为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Region` SET `Name`='{$name}',`CityID`='{$cityid}',`City`='{$city}'," .
    		"`Latitude`='{$latitude}',`Longitude`='{$longitude}',`ZoomLevel`='{$zoomlevel}' " .
    		"WHERE `ID`='{$id}'";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("修改区域信息", "区域名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("修改区域信息", "区域名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 利用$_POST的数据删除区域，返回操作结果的json
 */
function delete_region() {
	//权限验证
	if( !check_privilege( "删除区域" ) ) {
		agent_log("删除区域", "区域名字：".trim($_POST["name"])."，失败：没有删除区域的权限。");
		die( error_json ( "没有删除区域的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$sequence = addslashes(trim($_POST["sequence"])) + 0;
	$cityid = addslashes(trim($_POST["cityid"])) + 0;
	if(empty($id) || empty($sequence) || empty($cityid)){
		agent_log("删除区域", "失败：系统错误：某些必须的项为空。");
		return error_json("系统错误：某些必须的项为空");
	}
	
	//数据库操作
    $db = db_connect();
	
    //先更新其他纪录的序号
    if($sequence>0 && $cityid>0){
    	$sql = "UPDATE `Region` SET `Sequence`=`Sequence`-1 " .
    			"WHERE `CityID`='{$cityid}' AND `Sequence`>'{$sequence}' AND `Hide`=0;";
    	$db->query($sql);
    }
    
    $sql = "UPDATE `Region` SET `Hide`=1 WHERE `ID`='{$id}'" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("删除区域", "区域名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除区域", "区域名字：".$name."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 根据$_POST['data']调整城市区域的顺序
 */
function sequence_region() {
	//权限验证
	if( !check_privilege( "修改区域信息" ) ) {
		agent_log("修改区域信息", "调整城市区域顺序失败：没有修改区域信息的权限。");
		die( error_json ( "修改城市区域信息的权限。" ) );
	}
	
	$data = addslashes(trim($_POST["data"]));
	if(empty($data)) {
		agent_log("修改区域信息", "调整城市区域顺序失败：提供的数据为空");
		die( error_json ( "数据为空。" ) );
	}
	$oldnews = explode(",", $data);
	if(count($oldnews)<2) { //至少应该有两组数据
		agent_log("修改区域信息", "调整城市区域顺序失败：提供的数据格式不正确");
		die( error_json ( "格式不正确。" ) );
	}
	
	$db = db_connect();
	foreach ( $oldnews as $oldnew ) {
		$a = explode(":", $oldnew);
		if(count($a)!=3) continue;
		
		$ID = $a[0]; $old = $a[1];  $new = $a[2];
		$sql = "UPDATE `Region` SET `Sequence`='{$new}' " .
				"WHERE `ID`='{$ID}' AND `Sequence`='{$old}' ";
		$db->query($sql);
	}
	$db->close();
	return success_json_no_data();
}


function delete_regions () {
	//权限验证
	if( !check_privilege( "删除区域" ) ) {
		agent_log("删除区域", "区域列表：".trim($_POST["names"])."，失败：没有删除区域的权限。");
		die( error_json ( "没有删除区域的权限。" ) );
	}
	
	//准备数据
	$ids = addslashes(trim($_POST["ids"]));
	$names = addslashes(trim($_POST["names"]));
	if(empty($ids)){
		agent_log("删除区域", "失败：系统错误：区域ID为空。");
		return error_json("系统错误：区域ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Region` SET `Hide`=1 WHERE `ID` IN ({$ids})" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE) {
		agent_log("删除区域", "区域列表：".$names."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除区域", "区域列表：".$names."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 根据$_POST的数据添加一个代理数据到数据库，并返回操作结果的json
 */
function add_agent() {
	//权限验证
	if( !check_privilege( "添加代理" ) ) {
		agent_log("添加代理", "代理名字：".trim($_POST["name"])."，失败：没有添加代理的权限。");
		die( error_json ( "没有添加代理的权限。" ) );
	}
	
	
	//准备数据
	$name = addslashes(trim($_POST["name"]));
	$headid = addslashes(trim($_POST["headid"]));
	$head = addslashes(trim($_POST["head"]));
	$level = addslashes(trim($_POST["level"]));
	$ancestors = addslashes(trim($_POST["ancestors"]));
	$cityid = addslashes(trim($_POST["cityid"]));
	$city = addslashes(trim($_POST["city"]));
	$username = addslashes(trim($_POST["username"]));
	$password = addslashes(trim($_POST["password"]));
	$realname = addslashes(trim($_POST["realname"]));
	$telephone = addslashes(trim($_POST["telephone"]));//以下为非必填项
	$mobile = addslashes(trim($_POST["mobile"]));
	$memo = addslashes(trim($_POST["memo"]));
	//检查数据
	if(empty($name)){
		agent_log("添加代理", "失败：代理名称为空。");
		return error_json("代理名称为空。");
	}
	if(empty($head) || empty($headid)){
		agent_log("添加代理", "代理名称：".$name."，失败：上级代理为空。");
		return error_json("上级代理为空。");
	}
	if(empty($level) || empty($ancestors)){
		agent_log("添加代理", "代理名称：".$name."，失败：代理级别为空2。");
		return error_json("上级代理为空。");
	}
	if(empty($cityid) || empty($city)){
		agent_log("添加代理", "代理名称：".$name."，失败：所属城市为空。");
		return error_json("所属城市为空。");
	}
	if(empty($username)){
		agent_log("添加代理", "代理名称：".$name."，失败：操作员用户名为空。");
		return error_json("操作员用户名为空。");
	}
	if(empty($password)){
		agent_log("添加代理", "代理名称：".$name."，失败：操作员密码为空。");
		return error_json("操作员密码为空。");
	}
	if(empty($realname)){
		agent_log("添加代理", "代理名称：".$name."，失败：代理姓名为空。");
		return error_json("代理姓名为空。");
	}
	
	$privileges = get_privileges_of_adding_agent();
	
	//数据库操作
    $db = db_connect();
    //先查询用户名是否已经注册了
    $sql = "SELECT `ID` FROM `Agent` WHERE `Username`='{$username}' AND `Hide`=0; ";
    
    $rs = $db->query($sql);
    if( $rs->num_rows>0 ) {
		agent_log("添加代理", "代理名称：".$name."，失败：用户名[{$username}]已经存在。");
		$re = error_json( "用户名[{$username}]已经存在。" );
	    $db->close();
	    return $re;
    }
    
    $sql = "INSERT INTO `Agent` ( " .
    		"`Name`,`Level`,`HeadID`,`Head`,`Ancestors`," .
    		"`CityID`,`City`,`Username`," .
    		"`Password`,`Privileges`,`Realname`" .
    		(empty($telephone) ? "":",`Telephone`") .
    		(empty($mobile) ? "":",`Mobile`") .
    		(empty($memo) ? "":",`Memo`") .
    		",`AddDate`) VALUES(" .
    		"'{$name}','{$level}','{$headid}','{$head}','{$ancestors}'," .
    		"'{$cityid}','{$city}','{$username}'," .
    		"MD5('{$password}'),'{$privileges}','{$realname}'" .
    		(empty($telephone) ? "":",'{$telephone}'") .
    		(empty($mobile) ? "":",'{$mobile}'") .
    		(empty($memo) ? "":",'{$memo}'") .
    		",DATE(NOW())); " ;
    $result = $db->query($sql);
    
    //返回结果
	 $re = "";
	if( $result!==FALSE && $db->affected_rows==1 ) {
		agent_log("添加代理", "代理名称：".$name."，成功。");
		$re = success_json_no_data();
	}
	else {
		agent_log("添加代理", "代理名称：".$name."，失败：数据库记录删除失败。");
		$re = error_json( "数据库记录删除失败。" );
	}
    
    $db->close();
    return $re;
}

/**
 * 更新代理信息。
 */
function update_agent() {
	//权限验证
	if( !check_privilege( "修改代理信息" ) ) {
		agent_log("修改代理信息", "代理名字：".trim($_POST["name"])."，失败：没有修改代理信息的权限。");
		die( error_json ( "没有修改代理信息的权限。" ) );
	}
	
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$headid = addslashes(trim($_POST["headid"]));
	$head = addslashes(trim($_POST["head"]));
	$level = addslashes(trim($_POST["level"]));
	$ancestors = addslashes(trim($_POST["ancestors"]));
	$cityid = addslashes(trim($_POST["cityid"]));
	$city = addslashes(trim($_POST["city"]));
	$username = addslashes(trim($_POST["username"]));
	$password = addslashes(trim($_POST["password"]));
	$realname = addslashes(trim($_POST["realname"]));
	$telephone = addslashes(trim($_POST["telephone"]));//以下为非必填项
	$mobile = addslashes(trim($_POST["mobile"]));
	$memo = addslashes(trim($_POST["memo"]));;
	$adddate = addslashes(trim($_POST["adddate"]));
	//检查数据
	if(empty($name)){
		agent_log("修改代理信息", "失败：代理名称为空。");
		return error_json("代理名称为空。");
	}
	if(empty($id)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：代理id为空。");
		return error_json("系统错误：代理id为空。");
	}
	if(empty($head) || empty($headid)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：上级代理为空。");
		return error_json("上级代理为空。");
	}
	if(empty($level)||empty($ancestors)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：代理级别为空。");
		return error_json("上级代理为空。");
	}
	if(empty($cityid) || empty($city)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：所属城市为空。");
		return error_json("所属城市为空。");
	}
	if(empty($username)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：操作员用户名为空。");
		return error_json("操作员用户名为空。");
	}
	if(empty($realname)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：代理姓名为空。");
		return error_json("代理姓名为空。");
	}
	if(empty($adddate)){
		agent_log("修改代理信息", "代理名称：".$name."，失败：代理加入日期为空。");
		return error_json("代理加入日期为空。");
	}
	
	//从Session中提取一些数据
	$privileges = get_privileges_of_adding_agent();
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Agent` " .
    		"SET `Name`='{$name}',`Level`='{$level}',`HeadID`='{$headid}',`Head`='{$head}'," .
    		"`Ancestors`='{$ancestors}',`CityID`='{$cityid}',`City`='{$city}'," .
    		"`Username`='{$username}',`Privileges`='{$privileges}',`Realname`='{$realname}'" .
    		(empty($password) ? "":",`Password`=MD5('{$password}')") .
    		(empty($telephone) ? ",`Telephone`=NULL":",`Telephone`='{$telephone}'") .
    		(empty($mobile) ? ",`Mobile`=NULL":",`Mobile`='{$mobile}'") .
    		(empty($memo) ? ",`Memo`=NULL":",`Memo`='{$memo}'") .
    		",`AddDate`=DATE('{$adddate}')  WHERE `ID`='{$id}'";
    $result = $db->query($sql);
    
    //返回结果
	 $re = "";
	if( $result!==FALSE) {
		agent_log("修改代理信息", "代理名称：".$name."，成功。");
		$re = success_json_no_data();
	}
	else {
		agent_log("修改代理信息", "代理名称：".$name."，失败：数据库记录修改失败。");
		$re = error_json( "数据库记录修改失败。" );
	}
    
    $db->close();
    return $re;
}


/**
 * 利用$_POST的数据删除代理，返回操作结果的json
 */
function delete_agent() {
	//权限验证
	if( !check_privilege( "删除代理" ) ) {
		agent_log("删除代理", "代理名字：".trim($_POST["name"])."，失败：没有删除代理的权限。");
		die( error_json ( "没有删除代理的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	if(empty($id)){
		agent_log("删除代理", "失败：系统错误：代理ID为空。");
		return error_json("系统错误：代理ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Agent` SET `Hide`=1 WHERE `ID`='{$id}'" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("删除代理", "代理名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除代理", "代理名字：".$name."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}


function delete_agents () {
	//权限验证
	if( !check_privilege( "删除代理" ) ) {
		agent_log("删除代理", "代理列表：".trim($_POST["names"])."，失败：没有删除代理的权限。");
		die( error_json ( "没有删除代理的权限。" ) );
	}
	
	//准备数据
	$ids = addslashes(trim($_POST["ids"]));
	$names = addslashes(trim($_POST["names"]));
	if(empty($ids)){
		agent_log("删除代理", "失败：系统错误：代理ID为空。");
		return error_json("系统错误：代理ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Agent` SET `Hide`=1 WHERE `ID` IN ({$ids})" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE) {
		agent_log("删除代理", "代理列表：".$names."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除代理", "代理列表：".$names."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 获取餐馆json。
 */
function get_restaurants_json() {
	check_login();
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( isset($_SESSION['admin_is_restaurant'])){
		$condition = " AND `ID`='{$_SESSION['admin_restaurant_id']}' ";
	}
	else {
		if($_REQUEST['cityid']) {
			$cityid = addslashes(trim($_REQUEST["cityid"]));
			$condition .= " AND `CityId`='{$cityid}' ";
		}
		if ( $_SESSION['admin_city_id']!=0 ) {
			$condition .= " AND `CityId`='{$_SESSION['admin_city_id']}' ";
		}
		
		if( !empty($_REQUEST["searchCityId"]) ) {
			$searchCityId = addslashes(trim($_REQUEST['searchCityId']));
			$condition .= " AND `CityId`='{$searchCityId}' ";
		}
		if( !empty($_REQUEST["searchText"]) ||  !empty($_REQUEST["query"])) {
			$searchText = addslashes(trim($_REQUEST['searchText']));
			$searchText = empty($searchText) ? addslashes(trim($_REQUEST['query'])) : $searchText;
			$condition .= " AND (`Name` LIKE '%{$searchText}%' " .
					"OR `Telephone` LIKE '%{$searchText}%' " .
					"OR `City` LIKE '%{$searchText}%' " .
					"OR `Agent` LIKE '%{$searchText}%' " .
					"OR `Mobile` LIKE '%{$searchText}%' " .
					"OR `BusinessMemo` LIKE '%{$searchText}%' " .
					"OR `Notice` LIKE '%{$searchText}%' " .
					"OR `Address` LIKE '%{$searchText}%' " .
					"OR `Linkman` LIKE '%{$searchText}%' " .
					"OR `LinkPhone` LIKE '%{$searchText}%' " .
					"OR `Keyword` LIKE '%{$searchText}%' " .
					"OR `Memo` LIKE '%{$searchText}%' ) ";
		}
	}
	
	$sql = "SELECT COUNT(`ID`) FROM `Restaurant` WHERE `Hide`=0 " . $condition;
	
	//echo $sql . "\n\n";
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `Name`, `Telephone`, `CityId`, `City`, " .
			"`RegionID`,`Region`,`CityDefault`, `AgentId`, `Agent`, `Rating`, " .
			"`Mobile`, `Latitude`, `Longitude`, `Takeout`, " .
			"`BusinessHour`, `BusinessMemo`, `Fee`, `MinMoney`, " .
			"`Scope`, `Discount`, `Notice`, `Address`, " .
			"`Linkman`, `LinkPhone`, `Keyword`, `Memo`," .
			"`Commission`, `Username`, `AddTime`," .
			"`DiscountIn`,`SaleAd`,`Staple`,`IsPrint`," . 
			"`MEMBER_CODE`, `FEYIN_KEY`, `DEVICE_NO`" .
			"FROM `Restaurant` WHERE `Hide`=0 " . $condition;
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "restaurants": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"telephone":"'.$row['Telephone'].'", "cityid":'.$row['CityId'].', "city":"'.$row['City'].'", ' .
				'"regionid":"'.$row['RegionID'].'", "region":"'.$row['Region'].'", ' .
				'"citydefault":' . ( empty($row['CityDefault']) ? 'false, ' : 'true, ' ) .
				'"latitude":'.$row['Latitude'].', "longitude":'.($row['Longitude']+0).', ' .
				'"agentid":'.$row['AgentId'].', "agent":"'.$row['Agent'].'", ' .
				'"rating":'.$row['Rating'].', "mobile":"'.$row['Mobile'].'", ' .
				'"businesshour":"'.$row['BusinessHour'].'", "businessmemo":"'.$row['BusinessMemo'].'", ' .
				'"fee":'.($row['Fee']+0).', "minmoney":'.($row['MinMoney']+0).', ' .
				'"scope":'.($row['Scope']+0).', ' .
				'"discount":' . ( (empty($row['Discount']) || ($row['DiscountIn']+0==10)) ? '"10", ' : '"'.($row['Discount']+0).'", ' ) .
				'"notice":"'.$row['Notice'].'", ' .
				'"takeout":' . ( empty($row['Takeout']) ? 'false, ' : 'true, ' ) .
				'"address":"'.$row['Address'].'", "linkman":"'.$row['Linkman'].'", ' .
				'"linkphone":"'.$row['LinkPhone'].'", "keyword":"'.$row['Keyword'].'", ' .
				'"memo":"'.$row['Memo'].'", "commission":'.($row['Commission']+0).',  ' .
				'"username":"'.$row['Username'].'",  "salead":"'.$row['SaleAd'].'",  ' .
				'"staple":"'.$row['Staple'].'" ,' .
				'"isprint":' . ( ord($row['IsPrint'])==0 ? 'false, ' : 'true, ' ) .
				'"membercode":"'.$row['MEMBER_CODE'].'",  "feyinkey":"'.$row['FEYIN_KEY'].'",  ' .
				'"deviceno":"'.$row['DEVICE_NO'].'", ' .
				'"addtime":"'.substr($row['AddTime'],0,10).'", ' .
				'"discountin":' . ( (empty($row['DiscountIn']) || ($row['DiscountIn']+0==10)) ? '"10", ' : '"'.($row['DiscountIn']+0).'", ' ) .
				'"address":"'.$row['Address'].'" ' .
				
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	if(!empty($_REQUEST['callback'])) {
		$re = $_REQUEST['callback']."(".$re.");";
	}
	
	return $re;
}

/**
 * 根据$_POST数据添加餐馆到数据库，并返回操作结果JSON
 */
function add_restaurant() {
	//权限验证
	if( !check_privilege( "添加餐馆" ) ) {
		agent_log("添加餐馆", "餐馆名称：".trim($_POST["names"])."，失败：没有添加餐馆的权限。");
		die( error_json ( "没有添加餐馆的权限。" ) );
	}
	
	//准备数据
	//必填项
	$name = addslashes(trim($_POST["name"]));
	$telephone = addslashes(trim($_POST["telephone"]));
	$cityid = addslashes(trim($_POST["cityid"])) + 0;
	$city = addslashes(trim($_POST["city"]));
	$regionid = addslashes(trim($_POST["regionid"])) + 0;
	$region = addslashes(trim($_POST["region"]));
	$citydefault = addslashes(trim($_POST["citydefault"])) + 0;
	$agentid = addslashes(trim($_POST["agentid"])) + 0;
	$agent = addslashes(trim($_POST["agent"]));
	$rating = addslashes(trim($_POST["rating"])) + 0;
	$mobile = addslashes(trim($_POST["mobile"]));
	$commission = addslashes(trim($_POST["commission"]))+0;
	$username = addslashes(trim($_POST["username"]));
	$password = addslashes(trim($_POST["password"]));
	$takeout = addslashes(trim($_POST["takeout"])) + 0;
	$latitude = addslashes(trim($_POST["latitude"])) + 0;
	$longitude = addslashes(trim($_POST["longitude"]))+ 0;
	$discountin = addslashes(trim($_POST["discountin"]));
	$salead = addslashes(trim($_POST["salead"]));
	$deviceno = addslashes(trim($_POST["deviceno"]));
	$feyinkey = addslashes(trim($_POST["feyinkey"]));
	$membercode = addslashes(trim($_POST["membercode"]));
	//$staple=addslashes(trim($_POST["staple"]));
		
	if(empty($name)){
		agent_log("添加餐馆", "失败：餐馆名称为空。");
		return error_json("餐馆名称为空。");
	}
	if(empty($telephone)){
		agent_log("添加餐馆", "失败：餐馆电话为空。");
		return error_json("餐馆电话为空。");
	}
	if(empty($cityid) || empty($city)){
		agent_log("添加餐馆", "失败：系统错误：餐馆所属城市为空。");
		return error_json("系统错误：餐馆所属城市为空。");
	}
	if(empty($agentid) || empty($agent)){
		agent_log("添加餐馆", "失败：系统错误：餐馆所属代理为空。");
		return error_json("系统错误：餐馆所属代理为空。");
	}
	if(empty($rating)){
		agent_log("添加餐馆", "失败：系统错误：餐馆评级为空。");
		return error_json("系统错误：餐馆评级为空。");
	}
	if(empty($mobile)){
		agent_log("添加餐馆", "失败：餐馆短信手机号码为空。");
		return error_json("餐馆短信手机号码为空。");
	}
	if(empty($username)){
		agent_log("添加餐馆", "失败：登录用户名为空。");
		return error_json("登录用户名为空。");
	}
	if(empty($password)){
		agent_log("添加餐馆", "失败：登录密码为空。");
		return error_json("登录密码为空。");
	}
	if(empty($latitude) || empty($longitude)){
		agent_log("添加餐馆", "失败：餐馆坐标为空。");
		return error_json("餐馆坐标为空。");
	}
	//选填
	$staple=addslashes(trim($_POST["staple"]));
	$isprint=addslashes(trim($_POST["isprint"]));
	$businesshour = addslashes(trim($_POST["businesshour"]));
	$businessmemo = addslashes(trim($_POST["businessmemo"]));
	$fee = addslashes(trim($_POST["fee"])) + 0;
	$minmoney = addslashes(trim($_POST["minmoney"])) + 0;
	$scope = addslashes(trim($_POST["scope"])) + 0;
	$discount = addslashes(trim($_POST["discount"])) + 0;
	$discount = (empty($discount) || $discount<0 || $discount>10) ? null : $discount;
	$notice = addslashes(trim($_POST["notice"]));
	$address = addslashes(trim($_POST["address"]));
	$linkman = addslashes(trim($_POST["linkman"]));
	$linkphone = addslashes(trim($_POST["linkphone"]));
	$keyword = addslashes(trim($_POST["keyword"]));
	$memo = addslashes(trim($_POST["memo"]));
	if($isprint==on)
	{
		$isprint=1;
	}
	else {
		$isprint=0;
	}
	$db = db_connect();
	
	//先检查数据库用户名是否已经存在
	$sql = "SELECT `ID` FROM `Restaurant` WHERE `Username`='{$username}';";
	$rs = $db->query($sql);
	if($row=$rs->fetch_assoc()){
		$db->close();
		agent_log("添加餐馆", "失败：用户名已经存在。");
		return error_json("用户名已经存在。");
	}
	//用户名也不能在代理表中存在
	$sql = "SELECT `ID` FROM `Agent` WHERE `Username`='{$username}';";
	$rs = $db->query($sql);
	if($row=$rs->fetch_assoc()){
		$db->close();
		agent_log("添加餐馆", "失败：用户名已经存在。");
		return error_json("用户名已经存在。");
	}
	
	$uuid = restaurant_uuid();
	
	//插入数据
	$sql = "INSERT INTO `Restaurant` (`UUID`, `Name`, `Telephone`, `CityId`, `City`, " .
			"`RegionID`,`Region`,`CityDefault`, `AgentId`, `Agent`, `Rating`, " .
			"`Mobile`, `Latitude`, `Longitude`, `Takeout`, " .
			"`BusinessHour`, `BusinessMemo`, `Fee`, `MinMoney`, " .
			"`Scope`, `Discount`, `Notice`, `Address`, " .
			"`Linkman`, `LinkPhone`, `Keyword`, `Memo`, " .
			"`DiscountIn`,`SaleAd`,`Staple`,`IsPrint`,`MEMBER_CODE`,`FEYIN_KEY`,`DEVICE_NO`,`LastUpdate`, " .
			"`Commission`, `Username`, `Password`,`AddTime`) " .
			"VALUES('{$uuid}', '{$name}', '{$telephone}', '{$cityid}', '{$city}', " .
			"'{$regionid}','{$region}','{$citydefault}', '{$agentid}', '{$agent}', '{$rating}', " .
			"'{$mobile}', '{$latitude}', '{$longitude}', '{$takeout}', " .
			((empty($businesshour)) ? "NULL, " : "'{$businesshour}', ") .
			((empty($businessmemo)) ? "NULL, " : "'{$businessmemo}', ") .
			((empty($fee)) ? "NULL, " : "'{$fee}', ") .
			((empty($minmoney)) ? "NULL, " : "'{$minmoney}', ") .
			((empty($scope)) ? "'500', " : "'{$scope}', ") .
			((empty($discount)) ? "'10', " : "'{$discount}', ") .
			((empty($notice)) ? "NULL, " : "'{$notice}', ") .
			((empty($address)) ? "NULL, " : "'{$address}', ") .
			((empty($linkman)) ? "NULL, " : "'{$linkman}', ") .
			((empty($linkphone)) ? "NULL, " : "'{$linkphone}', ") .
			((empty($keyword)) ? "NULL, " : "'{$keyword}', ") .
			((empty($memo)) ? "NULL, " : "'{$memo}', ") .
			((empty($discountin)) ? "'10', " : "'{$discountin}', ") .
			((empty($salead)) ? "NULL, " : "'{$salead}', ") .
			((empty($staple)) ? "NULL, " : "'{$staple}', ") .
			((empty($isprint)) ? "0, " : "{$isprint}, ") .
			((empty($membercode)) ? "NULL, " : "'{$membercode}', ") .
			((empty($feyinkey)) ? "NULL, " : "'{$feyinkey}', ") .
			((empty($deviceno)) ? "NULL, " : "'{$deviceno}', ") .
			"'".get_datetime()."','{$commission}', '{$username}', MD5('{$password}')," .
			"CURRENT_TIMESTAMP)";
	//echo $sql;
    $result = $db->query($sql);
    
    
    
    //返回结果
    $re = "";
    if( $result!==FALSE && $db->affected_rows==1 ) {
		agent_log("添加餐馆", "餐馆名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("添加餐馆", "餐馆名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 生成一个UUID给一个餐馆，会查询数据库，确保数据库里没有餐馆使用这个UUID
 */
function restaurant_uuid() {
	$uuid = null;
	$db = db_connect();
	$sql = "SELECT `UUID` FROM `Restaurant` WHERE `UUID`='{$uuid}';";
	do {
		$uuid = uuid6();
		$rs = $db->query($sql);
	}
	while($rs->num_rows > 0);
	$db->close();
	return $uuid;
}

/**
 * 根据$_POST数据更新餐馆信息，并返回操作结果JSON
 */
function update_restaurant() {
	//权限验证
	if( !check_privilege( "修改餐馆资料" ) ) {
		agent_log("修改餐馆资料", "餐馆名称：".trim($_POST["names"])."，失败：没有修改餐馆资料的权限。");
		die( error_json ( "没有修改餐馆资料的权限。" ) );
	}
	
	//准备数据
	//必填项
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$telephone = addslashes(trim($_POST["telephone"]));
	$cityid = addslashes(trim($_POST["cityid"])) + 0;
	$city = addslashes(trim($_POST["city"]));
	$regionid = addslashes(trim($_POST["regionid"])) + 0;
	$region = addslashes(trim($_POST["region"]));
	$citydefault = addslashes(trim($_POST["citydefault"])) + 0;
	$agentid = addslashes(trim($_POST["agentid"])) + 0;
	$agent = addslashes(trim($_POST["agent"]));
	$rating = addslashes(trim($_POST["rating"])) + 0;
	$mobile = addslashes(trim($_POST["mobile"]));
	$commission = addslashes(trim($_POST["commission"]))+0;
	$username = addslashes(trim($_POST["username"]));
	$password = addslashes(trim($_POST["password"]));
	$takeout = addslashes(trim($_POST["takeout"])) + 0;
	$latitude = addslashes(trim($_POST["latitude"])) + 0;
	$longitude = addslashes(trim($_POST["longitude"]))+ 0;
	$discountin = addslashes(trim($_POST["discountin"]));
	$salead = addslashes(trim($_POST["salead"]));
	$deviceno = addslashes(trim($_POST["deviceno"]));
	$feyinkey = addslashes(trim($_POST["feyinkey"]));
	$membercode = addslashes(trim($_POST["membercode"]));
	$staple=addslashes(trim($_POST["staple"]));
	
	$isprint=addslashes(trim($_POST["isprint"]));
	
	if($isprint==on)
	{
		$isprint=1;
	}
	else {
		$isprint=0;
	}
	
	//echo $isprint;
	
	if(empty($id)){
		agent_log("修改餐馆资料", "失败：系统错误：餐馆id为空。");
		return error_json("系统错误：餐馆id为空。");
	}if(empty($name)){
		agent_log("修改餐馆资料", "失败：餐馆名称为空。");
		return error_json("餐馆名称为空。");
	}
	if(empty($telephone)){
		agent_log("修改餐馆资料", "失败：餐馆电话为空。");
		return error_json("餐馆电话为空。");
	}
	if(!isset($_SESSION['admin_is_restaurant'])){
		if(empty($cityid) || empty($city)){
			agent_log("修改餐馆资料", "失败：系统错误：餐馆所属城市为空。");
			return error_json("系统错误：餐馆所属城市为空。");
		}
		if(empty($agentid) || empty($agent)){
			agent_log("修改餐馆资料", "失败：系统错误：餐馆所属代理为空。");
			return error_json("系统错误：餐馆所属代理为空。");
		}
		if(empty($rating)){
			agent_log("修改餐馆资料", "失败：系统错误：餐馆评级为空。");
			return error_json("系统错误：餐馆评级为空。");
		}
	}
	else{
		if(!empty($cityid) || !empty($city)){
			agent_log("修改餐馆资料", "失败：餐馆试图修改所属城市。");
			return error_json("你没有权限修改所属城市。");
		}
		if(!empty($agentid) || !empty($agent)){
			agent_log("修改餐馆资料", "失败：餐馆试图修改所属代理。");
			return error_json("你没有权限修改所属代理。");
		}
		if(!empty($rating)){
			agent_log("修改餐馆资料", "失败：餐馆试图修改评级。");
			return error_json("你没有权限修改评级。");
		}
	}
	if(empty($mobile)){
		agent_log("修改餐馆资料", "失败：餐馆短信手机号码为空。");
		return error_json("餐馆短信手机号码为空。");
	}
	if(empty($username)){
		agent_log("修改餐馆资料", "失败：登录用户名为空。");
		return error_json("登录用户名为空。");
	}
	if(empty($latitude) || empty($longitude)){
		agent_log("修改餐馆资料", "失败：餐馆坐标为空。");
		return error_json("餐馆坐标为空。");
	}
	//选填
	$businesshour = addslashes(trim($_POST["businesshour"]));
	$businessmemo = addslashes(trim($_POST["businessmemo"]));
	$fee = addslashes(trim($_POST["fee"])) + 0;
	$minmoney = addslashes(trim($_POST["minmoney"])) + 0;
	$scope = addslashes(trim($_POST["scope"])) + 0;
	$discount = addslashes(trim($_POST["discount"])) + 0;
	$discount = (empty($discount) || $discount<0 || $discount>10) ? null : $discount;
	$notice = addslashes(trim($_POST["notice"]));
	$address = addslashes(trim($_POST["address"]));
	$linkman = addslashes(trim($_POST["linkman"]));
	$linkphone = addslashes(trim($_POST["linkphone"]));
	$keyword = addslashes(trim($_POST["keyword"]));
	$memo = addslashes(trim($_POST["memo"]));
	
	$db = db_connect();
	$sql = "UPDATE `Restaurant` SET `Name`='{$name}', `Telephone`='{$telephone}', " .
			(isset($_SESSION['admin_is_restaurant']) ? "" :
				"`CityId`='{$cityid}', `City`='{$city}', `CityDefault`='{$citydefault}', " .
				"`RegionID`='{$regionid}', `Region`='{$region}', " .
				"`AgentId`='{$agentid}', `Agent`='{$agent}', `Rating`='{$rating}', " .
				"`Commission`='{$commission}', "
			) .
			"`Mobile`='{$mobile}', `Latitude`='{$latitude}', `Longitude`='{$longitude}', " .
			"`Takeout`='{$takeout}', " .
			"`Staple`='{$staple}', " .
			"`IsPrint`={$isprint}, " .
			"`BusinessHour`=". ((empty($businesshour)) ? "NULL, " : "'{$businesshour}', ") . 
			"`BusinessMemo`=". ((empty($businessmemo)) ? "NULL, " : "'{$businessmemo}', ") .
			"`Fee`=". ((empty($fee)) ? "NULL, " : "'{$fee}', ") .
			"`MinMoney`=". ((empty($minmoney)) ? "NULL, " : "'{$minmoney}', ") .
			"`Scope`=". ((empty($scope)) ? "'500'" : "'{$scope}', ") .
			"`Discount`=". ((empty($discount)) ? "'10', " : "'{$discount}', ") .
			"`Notice`=". ((empty($notice)) ? "NULL, " : "'{$notice}', ") .
			"`Address`=". ((empty($address)) ? "NULL, " : "'{$address}', ") .
			"`Linkman`=". ((empty($linkman)) ? "NULL, " : "'{$linkman}', ") .
			"`LinkPhone`=". ((empty($linkphone)) ? "NULL, " : "'{$linkphone}', ") .
			"`Keyword`=". ((empty($keyword)) ? "NULL, " : "'{$keyword}', ") .
			"`Memo`=". ((empty($memo)) ? "NULL, " : "'{$memo}', ") .
			"`DiscountIn`=". ((empty($discountin)) ? "'10', " : "'{$discountin}', ") .
			"`SaleAd`=". ((empty($salead)) ? "NULL, " : "'{$salead}', ") .
			"`DEVICE_NO`=". ((empty($deviceno)) ? "NULL, " : "'{$deviceno}', ") .
			"`FEYIN_KEY`=". ((empty($feyinkey)) ? "NULL, " : "'{$feyinkey}', ") .
			"`MEMBER_CODE`=". ((empty($membercode)) ? "NULL, " : "'{$membercode}', ") .
			"`Username`='{$username}',`LastUpdate`='".get_datetime()."' " .
			(empty($password) ? "" : ", `Password`=MD5('{$password}') ") .
			" WHERE `ID`='{$id}'";
	//echo $sql;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("修改餐馆资料", "餐馆名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("修改餐馆资料", "餐馆名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 利用$_POST的数据删除餐馆，返回操作结果的json
 */
function delete_restaurant() {
	//权限验证
	if( !check_privilege( "删除餐馆" ) ) {
		agent_log("删除餐馆", "餐馆名字：".trim($_POST["name"])."，失败：没有删除餐馆的权限。");
		die( error_json ( "没有删除餐馆的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	if(empty($id)){
		agent_log("删除餐馆", "失败：系统错误：餐馆ID为空。");
		return error_json("系统错误：餐馆ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Restaurant` SET `Hide`=1 WHERE `ID`='{$id}'" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("删除餐馆", "餐馆名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除餐馆", "餐馆名字：".$name."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}



function delete_restaurants () {
	//权限验证
	if( !check_privilege( "删除餐馆" ) ) {
		agent_log("删除餐馆", "餐馆列表：".trim($_POST["names"])."，失败：没有删除餐馆的权限。");
		die( error_json ( "没有删除餐馆的权限。" ) );
	}
	
	//准备数据
	$ids = addslashes(trim($_POST["ids"]));
	$names = addslashes(trim($_POST["names"]));
	if(empty($ids)){
		agent_log("删除餐馆", "失败：系统错误：餐馆ID为空。");
		return error_json("系统错误：餐馆ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Restaurant` SET `Hide`=1 WHERE `ID` IN ({$ids})" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE) {
		agent_log("删除餐馆", "餐馆列表：".$names."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除餐馆", "餐馆列表：".$names."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}

function get_sections_json() {
	check_login();
	
	$restaurantid = addslashes(trim($_REQUEST["restaurantid"]));
	
	$re = "";
	$db = db_connect();
	$sql = "SELECT COUNT(`ID`) FROM `Section` WHERE `RestaurantID`='{$restaurantid}' AND `Hide`=0;";
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
		
	$sql = "SELECT `ID`, `Name`, `RestaurantID`, `Restaurant`, " .
			"`DenyOrder`, `LastUpdate`, `Sequence` FROM `Section` " .
			"WHERE `RestaurantID`='{$restaurantid}' AND `Hide`=0 " .
			"ORDER BY `Sequence` ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "sections": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"restaurantid":'.$row['RestaurantID'].', "restaurant":"'.$row['Restaurant'].'", ' .
				'"denyorder":' . ( ( empty($row['DenyOrder']) )? "false, " : "true, ") .
				'"lastupdate":"'.$row['LastUpdate'].'", "sequence":"'.$row['Sequence'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}


/**
 * 利用$_POST的数据添加餐品分类，返回操作结果的json
 */
function add_section() {
	//权限验证
	if( !check_privilege( "添加餐品" ) ) {
		agent_log("添加餐品分类", "餐品分类名字：".trim($_POST["name"])."，失败：没有添加餐品的权限。");
		die( error_json ( "没有添加餐品的权限，所以不能添加餐品分类。" ) );
	}
	
	//准备数据
	$name = addslashes(trim($_POST["name"]));
	$restaurantid = addslashes(trim($_POST["restaurantid"]));
	$restaurant = addslashes(trim($_POST["restaurant"]));
	$sequence = addslashes(trim($_POST["sequence"]));
	$denyorder = addslashes(trim($_POST["denyorder"]));
	$denyorder = ($denyorder=='true' ? 1 : 0);
	if(empty($name)){
		agent_log("添加餐品", "失败：餐品分类名字为空。");
		return error_json("餐品分类名字为空");
	}
	if(empty($restaurantid) || empty($restaurant)){
		agent_log("添加餐品分类", "餐品分类名字：".$name."，失败：餐品分类所属餐馆为空。");
		return error_json("餐品分类所属餐馆为空");
	}
	
	//数据库操作
    $db = db_connect();
    
    if(empty($sequence)){
	    $sql = "SELECT MAX(`Sequence`) FROM `Section` WHERE `RestaurantID`='{$restaurantid}' AND `Hide`=0;";
	    $sr = $db->query($sql);
	    $seq_to_be_row = $sr->fetch_row();
	    $sequence = $seq_to_be_row[0] + 1;
    }
    else {
    	$sql = "UPDATE `Section` SET `Sequence`=`Sequence`+1 " .
    			"WHERE `RestaurantID`='{$restaurantid}' AND `Hide`=0 " .
    			"AND `Sequence`>='{$sequence}' ";
    	$db->query($sql);
    }
    
    $sql = "INSERT INTO `Section`(`Name`,`RestaurantID`,`Restaurant`,`DenyOrder`,`Sequence`,`LastUpdate`) " .
    		"VALUES('{$name}','{$restaurantid}','{$restaurant}','{$denyorder}','{$sequence}','".get_datetime()."')";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE && $db->affected_rows==1 ) {
		agent_log("添加餐品分类", "餐品分类名字：".$name."，成功");
    	$re = '{"success":true, "id": '.$db->insert_id().'}';
    }
    else {
		agent_log("添加餐品分类", "餐品分类名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 利用$_POST的数据删除餐品分类，返回操作结果的json
 */
function delete_section() {
	//权限验证
	if( !check_privilege( "删除餐品" ) ) {
		agent_log("删除餐品分类", "餐品分类名字：".trim($_POST["name"])."，失败：没有删除餐品的权限。");
		die( error_json ( "没有删除餐品的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$sequence = addslashes(trim($_POST["sequence"])) + 0;
	$restaurantid = addslashes(trim($_POST["restaurantid"])) + 0;
	if(empty($id) || empty($sequence) || empty($restaurantid)){
		agent_log("删除餐品分类", "失败：系统错误：某些必须的项为空。");
		return error_json("系统错误：某些必须的项为空");
	}
	
	//数据库操作
    $db = db_connect();
    
    //先更新其他纪录的序号
    if($sequence>0 && $restaurantid>0){
    	$sql = "UPDATE `Section` SET `Sequence`=`Sequence`-1 " .
    			"WHERE `RestaurantID`='{$restaurantid}' AND `Sequence`>'{$sequence}' AND `Hide`=0;";
    	$db->query($sql);
    }

    //删除Dish表中的记录
    $sql = "UPDATE `Dish` SET `Hide`=1 " .
    		"WHERE `SectionID`='{$id}' " .
    		"AND `RestaurantID`='{$restaurantid}' ";
    $db->query($sql);
    
    //删除Section表中的记录
    $sql = "UPDATE `Section` SET `Hide`=1 WHERE `ID`='{$id}'" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("删除餐品分类", "餐品分类名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除餐品分类", "餐品分类名字：".$name."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 根据$_POST['data']调整餐品分类的顺序
 */
function sequence_section() {
	//权限验证
	if( !check_privilege( "修改餐品资料" ) ) {
		agent_log("修改餐品分类资料", "调整餐品分类顺序失败：没有修改餐品分类资料的权限。");
		die( error_json ( "修改餐品分类信息的权限。" ) );
	}
	
	$data = addslashes(trim($_POST["data"]));
	if(empty($data)) {
		agent_log("修改餐品分类资料", "调整餐品分类顺序失败：提供的数据为空");
		die( error_json ( "数据为空。" ) );
	}
	$oldnews = explode(",", $data);
	if(count($oldnews)<2) { //至少应该有两组数据
		agent_log("修改餐品分类资料", "调整餐品分类顺序失败：提供的数据格式不正确");
		die( error_json ( "格式不正确。" ) );
	}
	
	$db = db_connect();
	foreach ( $oldnews as $oldnew ) {
		$a = explode(":", $oldnew);
		if(count($a)!=3) continue;
		
		$ID = $a[0]; $old = $a[1];  $new = $a[2];
		$sql = "UPDATE `Section` SET `Sequence`='{$new}' " .
				"WHERE `ID`='{$ID}' AND `Sequence`='{$old}' ";
		$db->query($sql);
	}
	$db->close();
	return success_json_no_data();
}


/**
 * 利用$_POST的数据修改餐品分类资料，返回操作结果的json
 */
function update_section() {
	//权限验证
	if( !check_privilege( "修改餐品资料" ) ) {
		agent_log("修改餐品分类资料", "餐品分类名字：".trim($_POST["name"])."，失败：没有修改餐品资料的权限。");
		die( error_json ( "没有修改餐品资料的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$restaurantid = addslashes(trim($_POST["restaurantid"]));
	$restaurant = addslashes(trim($_POST["restaurant"]));
	$denyorder = addslashes(trim($_POST["denyorder"]));
	$denyorder = ($denyorder=='true' ? 1 : 0);
	if(empty($id)){
		agent_log("修改餐品分类资料", "失败：系统错误：餐品分类id为空。");
		return error_json("系统错误：餐品分类id为空");
	}
	if(empty($name)){
		agent_log("修改餐品分类资料", "失败：餐品分类名字为空。");
		return error_json("餐品分类名字为空");
	}
	if(empty($restaurantid) || empty($restaurant)){
		agent_log("修改餐品分类资料", "餐品分类名字：".$name."，失败：餐品分类所属餐馆为空。");
		return error_json("餐品分类所属餐馆为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Section` SET `Name`='{$name}', `RestaurantID`='{$restaurantid}', " .
    		"`Restaurant`='{$restaurant}', `DenyOrder`='{$denyorder}', " .
    		"`LastUpdate`='".get_datetime()."' " .
    		"WHERE `ID`='{$id}'";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("修改餐品分类资料", "餐品分类名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("修改餐品分类资料", "餐品分类名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    //更新餐馆的最后更新时间
    $sql = "UPDATE `Restaurant` SET `LastUpdate`='".get_datetime()."' WHERE `ID`='{$restaurantid}' ";
    $db->query($sql);
    
    $db->close();
    return $re;
}


function get_dishes_json () {
	check_login();
	
	$restaurantid = addslashes(trim($_REQUEST["restaurantid"]));
	
	$re = "";
	$db = db_connect();
	$sql = "SELECT COUNT(`ID`) FROM `Dish` WHERE `RestaurantID`='{$restaurantid}' AND `Hide`=0;";
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
		
	$sql = "SELECT `ID`, `Name`, `SectionID`, `Section`, `RestaurantID`, `Restaurant`, " .
			"`Annotation`, `Price`, `DiscountPrice`, `DenyOrder`, `LastUpdate`, `Sequence`,`dishCount` " .
			"FROM `Dish` " .
			"WHERE `RestaurantID`='{$restaurantid}' AND `Hide`=0 " .
			"ORDER BY `Sequence` "; //ExtJS会对Section进行排序的
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "dishes": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "name":"'.$row['Name'].'", ' .
				'"sectionid":'.$row['SectionID'].', "section":"'.$row['Section'].'", ' .
				'"restaurantid":'.$row['RestaurantID'].', "restaurant":"'.$row['Restaurant'].'", ' .
				'"annotation":"'.$row['Annotation'].'", "price":"'.$row['Price'].'", ' .
				'"discountprice":"'.$row['DiscountPrice'].'", ' .
				'"denyorder":' . ( ( empty($row['DenyOrder']) )? "false, " : "true, ") .
				'"lastupdate":"'.$row['LastUpdate'].'", "sequence":"'.$row['Sequence'].'","dishCount":"'.$row['dishCount'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}


/**
 * 利用$_POST的数据添加餐品，返回操作结果的json
 */
function add_dish() {
	//权限验证
	if( !check_privilege( "添加餐品" ) ) {
		agent_log("添加餐品", "餐品名字：".trim($_POST["name"])."，失败：没有添加餐品的权限。");
		die( error_json ( "没有添加餐品的权限，所以不能添加餐品。" ) );
	}
	
	//准备数据
	$name = addslashes(trim($_POST["name"]));
	$sectionid = addslashes(trim($_POST["sectionid"]));
	$section = addslashes(trim($_POST["section"]));
	$restaurantid = addslashes(trim($_POST["restaurantid"]));
	$restaurant = addslashes(trim($_POST["restaurant"]));
	$denyorder = addslashes(trim($_POST["denyorder"]));
	$denyorder = ($denyorder=='true' ? 1 : 0);
	$annotation = addslashes(trim($_POST["annotation"]));
	$price = addslashes(trim($_POST["price"]));
	$discountprice = addslashes(trim($_POST["discountprice"]));
	$sequence = addslashes(trim($_POST["sequence"]));
	$dishCount= addslashes(trim($_POST["dishCount"])); 
	if($dishCount=="")
		$dishCount="0";
	
	if(empty($name)){
		agent_log("添加餐品", "失败：餐品名字为空。");
		return error_json("餐品名字为空");
	}
	if(empty($restaurantid) || empty($restaurant)){
		agent_log("添加餐品", "餐品名字：".$name."，失败：餐品所属餐馆为空。");
		return error_json("餐品所属餐馆为空");
	}
	if(empty($sectionid) || empty($section)){
		agent_log("添加餐品", "餐品名字：".$name."，失败：餐品所属分类为空。");
		return error_json("餐品所属分类为空");
	}
	if(!isset($price)) {
		agent_log("添加餐品", "餐品名字：".$name."，失败：餐品价格为空。");
		return error_json("餐品价格为空");
	}
	$price = $price + 0; //转成数字形式。
	
	//数据库操作
    $db = db_connect();
        
    if(empty($sequence)){
	    $sql = "SELECT MAX(`Sequence`) FROM `Dish` " .
	    		"WHERE `RestaurantID`='{$restaurantid}' " .
	    		"AND `SectionID`='{$sectionid}' AND `Hide`=0;";
	    $sr = $db->query($sql);
	    $seq_to_be_row = $sr->fetch_row();
	    $sequence = $seq_to_be_row[0] + 1;
    }
    else {
    	$sql = "UPDATE `Dish` SET `Sequence`=`Sequence`+1 " .
    			"WHERE `RestaurantID`='{$restaurantid}' " .
    			"AND `SectionID`='{$sectionid}' AND `Hide`=0 " .
    			"AND `Sequence`>='{$sequence}' ";
    	$db->query($sql);
    }
    
    $sql = "INSERT INTO `Dish`(`Name`,`SectionID`,`Section`," .
    		"`RestaurantID`,`Restaurant`,`Annotation`,`Price`," .
    		"`DiscountPrice`,`DenyOrder`,`Sequence`,`LastUpdate`,`dishCount`) " .
    		"VALUES('{$name}','{$sectionid}','{$section}'," .
    		"'{$restaurantid}','{$restaurant}'," .
    		(empty($annotation) ? "NULL," : "'{$annotation}',") . 
    		"'{$price}'," .
    		(empty($discountprice) ? "NULL," : "'{$discountprice}',") . 
    		"'{$denyorder}','{$sequence}','".get_datetime()."','".$dishCount."') ";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE && $db->affected_rows==1 ) {
		agent_log("添加餐品", "餐品名字：".$name."，成功");
    	$re = '{"success":true, "id": '.$db->insert_id().'}';
    }
    else {
		agent_log("添加餐品", "餐品名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}

/**
 * 利用$_POST的数据修改餐品资料，返回操作结果的json
 */
function update_dish() {
	//权限验证
	if( !check_privilege( "修改餐品资料" ) ) {
		agent_log("修改餐品资料", "餐品名字：".trim($_POST["name"])."，失败：没有修改餐品资料的权限。");
		die( error_json ( "没有修改餐品资料的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$sectionid = addslashes(trim($_POST["sectionid"]));
	$section = addslashes(trim($_POST["section"]));
	$restaurantid = addslashes(trim($_POST["restaurantid"]));
	$restaurant = addslashes(trim($_POST["restaurant"]));
	$denyorder = addslashes(trim($_POST["denyorder"]));
	$denyorder = ($denyorder=='true' ? 1 : 0);
	$annotation = addslashes(trim($_POST["annotation"]));
	$price = addslashes(trim($_POST["price"]));
	$discountprice = addslashes(trim($_POST["discountprice"]));
	$dishCount=addslashes(trim($_POST["dishCount"]));
	if(empty($dishCount))
	{
		$dishCount=0;
	}
	if(empty($id)){
		agent_log("修改餐品资料", "失败：系统错误：餐品id为空。");
		return error_json("系统错误：餐品id为空");
	}
	if(empty($name)){
		agent_log("添加餐品", "失败：餐品名字为空。");
		return error_json("餐品名字为空");
	}
	if(empty($restaurantid) || empty($restaurant)){
		agent_log("添加餐品", "餐品名字：".$name."，失败：餐品所属餐馆为空。");
		return error_json("餐品所属餐馆为空");
	}
	if(empty($sectionid) || empty($section)){
		agent_log("添加餐品", "餐品名字：".$name."，失败：餐品所属分类为空。");
		return error_json("餐品所属分类为空");
	}
	if(!isset($price)) {
		agent_log("添加餐品", "餐品名字：".$name."，失败：餐品价格为空。");
		return error_json("餐品价格为空");
	}
	$price = $price + 0; //转成数字形式。
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Dish` SET `Name`='{$name}', `RestaurantID`='{$restaurantid}', `Restaurant`='{$restaurant}', " .
    		"`SectionID`='{$sectionid}', `Section`='{$section}', " .
    		"`Annotation`=" . (empty($annotation) ? "NULL," : "'{$annotation}',") .
    		"`Price`='{$price}', `DenyOrder`='{$denyorder}', " .
    		"`DiscountPrice`=" . (empty($discountprice) ? "NULL, " : "'{$discountprice}', ") .
    		"`LastUpdate`='".get_datetime()."' ," .
    		"`dishCount` =".$dishCount.
    		" WHERE `ID`='{$id}'";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("修改餐品资料", "餐品名字：".$name."，成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("修改餐品资料", "餐品名字：".$name."，失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    //更新餐馆的最后更新时间
    $sql = "UPDATE `Restaurant` SET `LastUpdate`='".get_datetime()."' WHERE `ID`='{$restaurantid}' ";
    $db->query($sql);
    
    $db->close();
    return $re;
}


/**
 * 利用$_POST的数据删除餐品，返回操作结果的json
 */
function delete_dish() {
	//权限验证
	if( !check_privilege( "删除餐品" ) ) {
		agent_log("删除餐品", "餐品名字：".trim($_POST["name"])."，失败：没有删除餐品的权限。");
		die( error_json ( "没有删除餐品的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$name = addslashes(trim($_POST["name"]));
	$sequence = addslashes(trim($_POST["sequence"])) + 0;
	$restaurantid = addslashes(trim($_POST["restaurantid"])) + 0;
	$sectionid = addslashes(trim($_POST["sectionid"])) + 0;
	if(empty($id)){
		agent_log("删除餐品", "失败：系统错误：餐品ID为空。");
		return error_json("系统错误：餐品ID为空");
	}
	
	//数据库操作
    $db = db_connect();
	
    //先更新其他纪录的序号
    if($sequence>0 && $restaurantid>0){
    	$sql = "UPDATE `Dish` SET `Sequence`=`Sequence`-1 " .
    			"WHERE `RestaurantID`='{$restaurantid}' AND `Sequence`>'{$sequence}' " .
    			"AND `SectionID`='{$sectionid}' AND `Hide`=0;";
    	$db->query($sql);
    }
    
    $sql = "UPDATE `Dish` SET `Hide`=1 WHERE `ID`='{$id}'" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("删除餐品", "餐品名字：".$name."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除餐品", "餐品名字：".$name."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}


/**
 * 根据$_POST['data']调整餐品的顺序
 */
function sequence_dish() {
	//权限验证
	if( !check_privilege( "修改餐品资料" ) ) {
		agent_log("修改餐品资料", "调整餐品顺序失败：没有修改餐品资料的权限。");
		die( error_json ( "修改餐品信息的权限。" ) );
	}
	
	$data = addslashes(trim($_POST["data"]));
	if(empty($data)) {
		agent_log("修改餐品资料", "调整餐品顺序失败：提供的数据为空");
		die( error_json ( "数据为空。" ) );
	}
	$oldnews = explode(",", $data);
	if(count($oldnews)<2) { //至少应该有两组数据
		agent_log("修改餐品资料", "调整餐品顺序失败：提供的数据格式不正确");
		die( error_json ( "格式不正确。" ) );
	}
	
	$db = db_connect();
	foreach ( $oldnews as $oldnew ) {
		$a = explode(":", $oldnew);
		if(count($a)!=3) continue;
		
		$ID = $a[0]; $old = $a[1];  $new = $a[2];
		$sql = "UPDATE `Dish` SET `Sequence`='{$new}' " .
				"WHERE `ID`='{$ID}' AND `Sequence`='{$old}' ";
		$db->query($sql);
	}
	$db->close();
	return success_json_no_data();
}

/**
 * 获取客户列表
 */
function get_customs_json() {
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Email` LIKE '%{$searchText}%' " .
				"OR `Mobile` LIKE '%{$searchText}%' " .
				"OR `Username` LIKE '%{$searchText}%' " .
				"OR `LastIp` LIKE '%{$searchText}%' ) ";
	}
	if( !empty($_REQUEST["query"]) ) {
		$query = addslashes(trim($_REQUEST["query"]));
		$condition .= " AND (`Email` LIKE '%{$query}%' " .
				"OR `Mobile` LIKE '%{$query}%' " .
				"OR `Username` LIKE '%{$query}%' " .
				"OR `LastIp` LIKE '%{$query}%' ) ";
	}
	if (  !empty($_REQUEST['searchRegType']) ) {
		$searchRegType = addslashes(trim($_REQUEST['searchRegType']));
		$condition .= " AND `RegType`='{$searchRegType}' ";
	}
	if (  !empty($_REQUEST['searchClient']) ) {
		$searchClient = addslashes(trim($_REQUEST['searchClient']));
		$condition .= " AND `LastClient`='{$searchClient}' ";
	}
	
	$sql = "SELECT COUNT(`ID`) FROM `Custom` WHERE `Hide`=0 " . $condition;
	
	//echo $sql . "\n\n";
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `Email`, `Mobile`, `Username`, `CityHint`, " .
			"`WelcomeHint`, `MapHint`, `RegTime`, `RegType`, " .
			"`LastClient`, `LastCityID`, `LastCity`, `LastIp`, " .
			"`LastTime`, `Corporation`, `EmailVerified`, `MobileVerified`, " .
			"`MobileVerifying` FROM `Custom` WHERE `Hide`=0 " . $condition;
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "customs": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "Email":"'.$row['Email'].'", ' .
				'"Mobile":"'.$row['Mobile'].'", "Username":"'.$row['Username'].'", ' .
				'"CityHint":' . ( empty($row['CityHint']) ? 'false, ' : 'true, ' ) .
				'"WelcomeHint":' . ( empty($row['WelcomeHint']) ? 'false, ' : 'true, ' ) .
				'"MapHint":' . ( empty($row['MapHint']) ? 'false, ' : 'true, ' ) .
				'"RegTime":"'.$row['RegTime'].'", "RegType":"'.$row['RegType'].'", ' .
				'"LastClient":"'.$row['LastClient'].'", "LastCityID":"'.$row['LastCityID'].'", ' .
				'"LastCity":"'.$row['LastCity'].'", "LastIp":"'.$row['LastIp'].'", ' .
				'"LastTime":"'.$row['LastTime'].'", "Corporation":"'.$row['Corporation'].'", ' .
				'"EmailVerified":' . ( empty($row['EmailVerified']) ? 'false, ' : 'true, ' ) .
				'"MobileVerified":' . ( empty($row['MobileVerified']) ? 'false, ' : 'true, ' ) .
				'"MobileVerifying":' . ( empty($row['MobileVerifying']) ? 'false, ' : 'true, ' ) .
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	if(!empty($_REQUEST['callback'])) {
		$re = $_REQUEST['callback']."(".$re.");";
	}
	
	return $re;
}


function get_agentlogs_json() {
	if(!check_privilege('代理操作日志')) return "";
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Name` LIKE '%{$searchText}%' " .
				"OR `City` LIKE '%{$searchText}%' " .
				"OR `Realname` LIKE '%{$searchText}%' " .
				"OR `Username` LIKE '%{$searchText}%' " .
				"OR `Operation` LIKE '%{$searchText}%' " .
				"OR `Data` LIKE '%{$searchText}%' ) ";
	}
	if ( !empty($_REQUEST['searchCityId']) ) {
		$searchCityId = addslashes(trim($_REQUEST['searchCityId']));
		$condition .= " AND `CityID`='{$searchCityId}' ";
	}
	if ( !empty($_REQUEST['searchDateFrom']) ) {
		$searchDateFrom = addslashes(trim($_REQUEST['searchDateFrom']));
		$searchDateFrom = substr($searchDateFrom, 0, 10);
		$searchHourFrom = addslashes(trim($_REQUEST['searchHourFrom'])) + 0;
		$searchMinuteFrom = addslashes(trim($_REQUEST['searchMinuteFrom'])) + 0;
		$from = $searchDateFrom . " " . str_pad($searchHourFrom, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteFrom, 2, "0", STR_PAD_LEFT). ':00';
		$condition .= " AND `OpTime`>'{$from}' ";
	}
	if ( !empty($_REQUEST['searchDateEnd']) ) {
		$searchDateEnd = addslashes(trim($_REQUEST['searchDateEnd']));
		$searchDateEnd = substr($searchDateEnd, 0, 10);
		$searchHourEnd = addslashes(trim($_REQUEST['searchHourEnd'])) + 0;
		$searchHourEnd = empty($searchHourEnd) ? 23 : $searchHourEnd;
		$searchMinuteEnd = addslashes(trim($_REQUEST['searchMinuteEnd'])) + 0;
		$searchMinuteEnd = empty($searchMinuteEnd) ? 59 : $searchMinuteEnd;
		$end = $searchDateEnd . " " . str_pad($searchHourEnd, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteEnd, 2, "0", STR_PAD_LEFT). ':59';
		$condition .= " AND `OpTime`<'{$end}' ";
	}
	if ( !empty($_REQUEST['searchIP']) ) {
		$searchIP = addslashes(trim($_REQUEST['searchIP']));
		$condition .= " AND `IP`='{$searchIP}' ";
	}
	if ( !empty($_REQUEST['searchOperation']) ) {
		$searchOperation = addslashes(trim($_REQUEST['searchOperation']));
		$condition .= " AND `Operation`='{$searchOperation}' ";
	}
	
	$sql = "SELECT COUNT(`ID`) FROM `AgentLog` WHERE 1=1 " . $condition;
	
//	echo $sql . "\n\n";
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `AgentID`, `Name`, `CityID`, `City`, " .
			"`Realname`, `Username`, `OpTime`, `IP`, `Operation`, `Data` " .
			"FROM `AgentLog` WHERE 1=1 " . $condition;
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
//	echo $sql . "\n\n";
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "agentlogs": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "AgentID":'.$row['AgentID'].', ' .
				'"Name":"'.$row['Name'].'", "CityID":'.$row['CityID'].', ' .
				'"City":"'.$row['City'].'", "Realname":"'.$row['Realname'].'", ' .
				'"Username":"'.$row['Username'].'", "OpTime":"'.$row['OpTime'].'", ' .
				'"IP":"'.$row['IP'].'", "Operation":"'.$row['Operation'].'", ' .
				'"Data":"'.$row['Data'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

function get_customlogs_json() {
	if(!check_privilege('客户操作日志')) return "";
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Username` LIKE '%{$searchText}%' " .
				"OR `Email` LIKE '%{$searchText}%' " .
				"OR `Mobile` LIKE '%{$searchText}%' " .
				"OR `Operation` LIKE '%{$searchText}%' " .
				"OR `Data` LIKE '%{$searchText}%' ) ";
	}
	if ( !empty($_REQUEST['searchDateFrom']) ) {
		$searchDateFrom = addslashes(trim($_REQUEST['searchDateFrom']));
		$searchDateFrom = substr($searchDateFrom, 0, 10);
		$searchHourFrom = addslashes(trim($_REQUEST['searchHourFrom'])) + 0;
		$searchMinuteFrom = addslashes(trim($_REQUEST['searchMinuteFrom'])) + 0;
		$from = $searchDateFrom . " " . str_pad($searchHourFrom, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteFrom, 2, "0", STR_PAD_LEFT). ':00';
		$condition .= " AND `OpTime`>'{$from}' ";
	}
	if ( !empty($_REQUEST['searchDateEnd']) ) {
		$searchDateEnd = addslashes(trim($_REQUEST['searchDateEnd']));
		$searchDateEnd = substr($searchDateEnd, 0, 10);
		$searchHourEnd = addslashes(trim($_REQUEST['searchHourEnd'])) + 0;
		$searchHourEnd = empty($searchHourEnd) ? 23 : $searchHourEnd;
		$searchMinuteEnd = addslashes(trim($_REQUEST['searchMinuteEnd'])) + 0;
		$searchMinuteEnd = empty($searchMinuteEnd) ? 59 : $searchMinuteEnd;
		$end = $searchDateEnd . " " . str_pad($searchHourEnd, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteEnd, 2, "0", STR_PAD_LEFT). ':59';
		$condition .= " AND `OpTime`<'{$end}' ";
	}
	if ( !empty($_REQUEST['searchIP']) ) {
		$searchIP = addslashes(trim($_REQUEST['searchIP']));
		$condition .= " AND `IP`='{$searchIP}' ";
	}
	if ( !empty($_REQUEST['searchOperation']) ) {
		$searchOperation = addslashes(trim($_REQUEST['searchOperation']));
		$condition .= " AND `Operation`='{$searchOperation}' ";
	}
	
	$sql = "SELECT COUNT(`ID`) FROM `CustomLog` WHERE 1=1 " . $condition;
	
//	echo $sql . "\n\n";
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `CustomID`, `Username`, `Email`, `Mobile`, " .
			"`OpTime`, `IP`, `Operation`, `Data` " .
			"FROM `CustomLog` WHERE 1=1 " . $condition;
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
//	echo $sql . "\n\n";
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "customlogs": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "CustomID":'.$row['CustomID'].', ' .
				'"Username":"'.$row['Username'].'", ' .
				'"Email":"'.$row['Email'].'", "Mobile":"'.$row['Mobile'].'", ' .
				'"OpTime":"'.$row['OpTime'].'", ' .
				'"IP":"'.$row['IP'].'", "Operation":"'.$row['Operation'].'", ' .
				'"Data":"'.$row['Data'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

function get_QAs_json() {
	if(!check_privilege('留言列表')) return "";
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Name` LIKE '%{$searchText}%' " .
				"OR `Email` LIKE '%{$searchText}%' " .
				"OR `Question` LIKE '%{$searchText}%' " .
				"OR `Answer` LIKE '%{$searchText}%' " .
				"OR `IP` LIKE '%{$searchText}%' ) ";
	}
	if ( !empty($_REQUEST['searchDateFrom']) ) {
		$searchDateFrom = addslashes(trim($_REQUEST['searchDateFrom']));
		$searchDateFrom = substr($searchDateFrom, 0, 10);
		$searchHourFrom = addslashes(trim($_REQUEST['searchHourFrom'])) + 0;
		$searchMinuteFrom = addslashes(trim($_REQUEST['searchMinuteFrom'])) + 0;
		$from = $searchDateFrom . " " . str_pad($searchHourFrom, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteFrom, 2, "0", STR_PAD_LEFT). ':00';
		$condition .= " AND `QTime`>'{$from}' ";
	}
	if ( !empty($_REQUEST['searchDateEnd']) ) {
		$searchDateEnd = addslashes(trim($_REQUEST['searchDateEnd']));
		$searchDateEnd = substr($searchDateEnd, 0, 10);
		$searchHourEnd = addslashes(trim($_REQUEST['searchHourEnd'])) + 0;
		$searchHourEnd = empty($searchHourEnd) ? 23 : $searchHourEnd;
		$searchMinuteEnd = addslashes(trim($_REQUEST['searchMinuteEnd'])) + 0;
		$searchMinuteEnd = empty($searchMinuteEnd) ? 59 : $searchMinuteEnd;
		$end = $searchDateEnd . " " . str_pad($searchHourEnd, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteEnd, 2, "0", STR_PAD_LEFT). ':59';
		$condition .= " AND `QTime`<'{$end}' ";
	}
	if ( !empty($_REQUEST['searchIP']) ) {
		$searchIP = addslashes(trim($_REQUEST['searchIP']));
		$condition .= " AND `IP`='{$searchIP}' ";
	}
	
	$sql = "SELECT COUNT(`ID`) FROM `QA` WHERE `Hide`=0 " . $condition;
	
//	echo $sql . "\n\n";
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `CustomID`, `Email`, `Name`, " .
			"`IP`, `Question`, `QTime`, `Answer`, `ATime`, `Show` " .
			"FROM `QA` WHERE `Hide`=0 " . $condition;
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
//	echo $sql . "\n\n";
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "qas": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "CustomID":"'.$row['CustomID'].'", ' .
				'"Email":"'.$row['Email'].'", "Name":"'.$row['Name'].'", ' .
				'"IP":"'.$row['IP'].'", "Question":"'.$row['Question'].'", ' .
				'"QTime":"'.$row['QTime'].'", "Answer":"'.$row['Answer'].'", ' .
				'"ATime":"'.$row['ATime'].'", ' .
				'"Show":' . ( empty($row['Show']) ? 'false' : 'true' ) . 
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

/**
 * 根据$_POST['id']、$_POST['Answer']和$_POST['Show']更新留言表[QA]的有关记录
 */
function update_qa () {
	//权限验证
	if( !check_privilege( "留言回复" ) ) {
		agent_log("留言回复", "留言回复失败：没有留言回复的权限。");
		die( error_json ( "没有留言回复的权限。" ) );
	}
	
	//准备数据
	$id = addslashes(trim($_POST["id"]));
	$Answer = addslashes(trim($_POST["Answer"]));
	$Show = (addslashes(trim($_POST["Show"])) == 'true') ? 1 : 0;
	if(empty($id)){
		agent_log("留言回复", "留言回复失败：系统错误：留言id为空。");
		return error_json("系统错误：留言id为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `QA` SET `Answer`=".(empty($Answer)? "NULL" : "'{$Answer}'").", " .
    		"`ATime`=".(empty($Answer)? "NULL" : "'".get_datetime()."'").", " .
    		"`Show`='{$Show}' " .
    		" WHERE `ID`='{$id}'";
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE ) {
		agent_log("留言回复", "成功");
    	$re = success_json_no_data();
    }
    else {
		agent_log("留言回复", "失败：数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
    $db->close();
    return $re;
}

function get_sms_setting() {
	//权限验证
	if( !check_privilege( "短信平台设置" ) ) {
		agent_log("短信平台设置", "获取短信平台设置失败：没有短信平台设置的权限。");
		die( error_json ( "没有短信平台设置的权限。" ) );
	}
	
    $db = db_connect();
    $settings = array();
    $sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
    $rs = $db->query($sql);
    while( $row = $rs->fetch_assoc() ) {
    	$_SESSION['admin_setting_'.$row['Property']] = $row['Value'];
    	array_push($settings, '"'.$row['Property'].'": "'.$row['Value'].'"');
    }
    $re = '{"success": true, "settings": {'.implode(",", $settings).'}}';
    $db->close();
    return $re;
}

function save_sms_setting() {
	//权限验证
	if( !check_privilege( "短信平台设置" ) ) {
		agent_log("短信平台设置", "保存短信平台设置失败：没有短信平台设置的权限。");
		die( error_json ( "没有短信平台设置的权限。" ) );
	}
	
	//准备数据  TODO HERERE
	$platform = addslashes(trim($_POST["platform"]));
// 	$url = addslashes(trim($_POST["url"]));
	$userid = addslashes(trim($_POST["userid"]));
	$account = addslashes(trim($_POST["account"]));
	$password = addslashes(trim($_POST["password"]));
	
	$EMY_softwareSerialNo = addslashes(trim($_POST["EMY_softwareSerialNo"]));
	$EMY_password = addslashes(trim($_POST["EMY_password"]));
	$EMY_eName = addslashes(trim($_POST["EMY_eName"]));
	$EMY_linkMan = addslashes(trim($_POST["EMY_linkMan"]));
	$EMY_phoneNum = addslashes(trim($_POST["EMY_phoneNum"]));
	$EMY_mobile = addslashes(trim($_POST["EMY_mobile"]));
	$EMY_email = addslashes(trim($_POST["EMY_email"]));
	$EMY_fax = addslashes(trim($_POST["EMY_fax"]));
	$EMY_address = addslashes(trim($_POST["EMY_address"]));
	$EMY_postcode = addslashes(trim($_POST["EMY_postcode"]));
	
	if(empty($platform)){
		agent_log("短信平台设置", "保存短信平台设置失败：短信平台为空。");
		return error_json("短信平台为空。");
	}

	if($platform=='企信') {
//	 	if(empty($url)){
// 			agent_log("短信平台设置", "保存短信平台设置失败：平台URL为空。");
// 			return error_json("平台URL为空");
// 		}
		if(empty($userid)){
			agent_log("短信平台设置", "保存短信平台设置失败：企业ID为空。");
			return error_json("企业ID为空");
		}
		if(empty($account)){
			agent_log("短信平台设置", "保存短信平台设置失败：用户账户为空。");
			return error_json("用户账户为空");
		}
		if(empty($password)){
			agent_log("短信平台设置", "保存短信平台设置失败：密码为空。");
			return error_json("密码为空");
		}
	}
	elseif($platform=='亿美') {
		if(empty($EMY_softwareSerialNo)){
			agent_log("短信平台设置", "保存短信平台设置失败：序列号为空。");
			return error_json("序列号为空");
		}
		if(empty($EMY_password)){
			agent_log("短信平台设置", "保存短信平台设置失败：密码为空。");
			return error_json("密码为空");
		}
		if(empty($EMY_eName)){
			agent_log("短信平台设置", "保存短信平台设置失败：企业名称为空。");
			return error_json("企业名称为空");
		}
		if(empty($EMY_linkMan)){
			agent_log("短信平台设置", "保存短信平台设置失败：联系人姓名为空。");
			return error_json("联系人姓名为空");
		}
		if(empty($EMY_phoneNum)){
			agent_log("短信平台设置", "保存短信平台设置失败：联系电话为空。");
			return error_json("联系电话为空");
		}
		if(empty($EMY_mobile)){
			agent_log("短信平台设置", "保存短信平台设置失败：联系手机号码为空。");
			return error_json("联系手机号码为空");
		}
		if(empty($EMY_email)){
			agent_log("短信平台设置", "保存短信平台设置失败：联系电子邮件为空。");
			return error_json("联系电子邮件为空");
		}
		if(empty($EMY_fax)){
			agent_log("短信平台设置", "保存短信平台设置失败：传真号码为空。");
			return error_json("传真号码为空");
		}
		if(empty($EMY_address)){
			agent_log("短信平台设置", "保存短信平台设置失败：联系地址为空。");
			return error_json("联系地址为空");
		}
		if(empty($EMY_postcode)){
			agent_log("短信平台设置", "保存短信平台设置失败：邮政编码为空。");
			return error_json("邮政编码为空");
		}
	}
	
    $db = db_connect();
    $settings = array();
    
    $sql = "UPDATE `Setting` SET `Value`='{$platform}' WHERE `Property`='SMS_platform'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_platform'] = $platform;
    
    
//     $sql = "UPDATE `Setting` SET `Value`='{$url}' WHERE `Property`='SMS_url'";
//     $db->query($sql);
//     $_SESSION['admin_setting_SMS_url'] = $url;
    
    $sql = "UPDATE `Setting` SET `Value`='{$userid}' WHERE `Property`='SMS_userid'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_userid'] = $userid;
    
    $sql = "UPDATE `Setting` SET `Value`='{$account}' WHERE `Property`='SMS_account'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_account'] = $account;
    
    $sql = "UPDATE `Setting` SET `Value`='{$password}' WHERE `Property`='SMS_password'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_password'] = $password;

    $sql = "UPDATE `Setting` SET `Value`='{$EMY_softwareSerialNo}' WHERE `Property`='SMS_EMY_softwareSerialNo'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_softwareSerialNo'] = $EMY_softwareSerialNo;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_password}' WHERE `Property`='SMS_EMY_password'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_password'] = $EMY_password;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_eName}' WHERE `Property`='SMS_EMY_eName'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_eName'] = $EMY_eName;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_linkMan}' WHERE `Property`='SMS_EMY_linkMan'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_linkMan'] = $EMY_linkMan;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_phoneNum}' WHERE `Property`='SMS_EMY_phoneNum'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_phoneNum'] = $EMY_phoneNum;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_mobile}' WHERE `Property`='SMS_EMY_mobile'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_mobile'] = $EMY_mobile;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_email}' WHERE `Property`='SMS_EMY_email'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_email'] = $EMY_email;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_fax}' WHERE `Property`='SMS_EMY_fax'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_fax'] = $EMY_fax;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_address}' WHERE `Property`='SMS_EMY_address'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_address'] = $EMY_address;
    
    $sql = "UPDATE `Setting` SET `Value`='{$EMY_postcode}' WHERE `Property`='SMS_EMY_postcode'";
    $db->query($sql);
    $_SESSION['admin_setting_SMS_EMY_postcode'] = $EMY_postcode;
    
    $db->close();
    
    $re = success_json_no_data();
    return $re;
}

function get_emay_client() {
	
	$gwUrl = 'http://sdkhttp.eucp.b2m.cn/sdk/SDKService?wsdl';
	$serialNumber = $_SESSION['admin_setting_SMS_EMY_softwareSerialNo'];
	$password = $_SESSION['admin_setting_SMS_EMY_password'];
	$sessionKey = get_emay_session_key();
	$connectTimeOut = 2;
	$readTimeOut = 10;
	$proxyhost = false;
	$proxyport = false;
	$proxyusername = false;
	$proxypassword = false;
	
	$client = new EmayClient($gwUrl,$serialNumber,$password,$sessionKey,$proxyhost,$proxyport,$proxyusername,$proxypassword,$connectTimeOut,$readTimeOut);
	$client->setOutgoingEncoding("UTF-8");
	return $client;
}

function get_emay_session_key() {
	$re = "";
	if(empty($_SESSION['admin_setting_SMS_EMY_sessionkey'])) {
		$re = rand(100000,999999);
        $db = db_connect();
		$sql = "UPDATE `Setting` SET `Value`='{$re}' WHERE `Property`='SMS_EMY_sessionkey'";
		$db->query($sql);
		$_SESSION['admin_setting_SMS_EMY_sessionkey'] = $re;
	}
	else {
		$re = $_SESSION['admin_setting_SMS_EMY_sessionkey'];
	}
	return $re;
}

function emay_sms_login() {
	if(empty($_SESSION['admin_setting_SMS_EMY_softwareSerialNo'])){
		get_sms_setting();
	}
	
	if(empty($_SESSION['admin_setting_SMS_EMY_softwareSerialNo'])){
		die( error_json ( "你需要先设置亿美短信平台的序列号才能登录" ) );
	}
	
	if(!empty($_SESSION['admin_setting_SMS_EMY_sessionkey'])) { //已经登录
		return success_json_no_data();
	}
	
	$client = get_emay_client();
	$statusCode = $client->login();
	
	if ($statusCode!=null && $statusCode=="0"){
        $eName = $_SESSION['admin_setting_SMS_EMY_eName'];
        $linkMan = $_SESSION['admin_setting_SMS_EMY_linkMan'];
        $phoneNum = $_SESSION['admin_setting_SMS_EMY_phoneNum'];
        $mobile = $_SESSION['admin_setting_SMS_EMY_mobile'];
        $email = $_SESSION['admin_setting_SMS_EMY_email'];
        $fax = $_SESSION['admin_setting_SMS_EMY_fax'];
        $address = $_SESSION['admin_setting_SMS_EMY_address'];
        $postcode = $_SESSION['admin_setting_SMS_EMY_postcode'];
        
        $statusCode = $client->registDetailInfo($eName,$linkMan,$phoneNum,$mobile,$email,$fax,$address,$postcode);
        
		return success_json_no_data();
	}
	else {
		return error_json ( "注册失败，处理状态码:".$statusCode );
	}
}

function emay_sms_logout() {
	if(empty($_SESSION['admin_setting_SMS_EMY_softwareSerialNo']) || empty($_SESSION['admin_setting_SMS_EMY_sessionkey'])){
		get_sms_setting();
	}
	
	if(empty($_SESSION['admin_setting_SMS_EMY_softwareSerialNo'])){
		die( error_json ( "你需要先设置亿美短信平台的序列号才能注销登录" ) );
	}
	
	if(empty($_SESSION['admin_setting_SMS_EMY_sessionkey'])) { //已经登录
		die( error_json ( "还没有登录" ) );
	}
	
	$client = get_emay_client();
	$statusCode = $client->logout();
	
	if ($statusCode!=null && $statusCode=="0"){
		$db = db_connect();
		$sql = "UPDATE `Setting` SET `Value`='' WHERE `Property`='SMS_EMY_sessionkey'";
		$db->query($sql);
		$_SESSION['admin_setting_SMS_EMY_sessionkey'] = '';
		$db->close();
		return success_json_no_data();
	}
	else {
		return error_json ( "注销失败，处理状态码:".$statusCode );
	}
}

function get_sms_json() {
	if(!check_privilege('短信记录')) return "";
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Receiver` LIKE '%{$searchText}%' " .
				"OR `Content` LIKE '%{$searchText}%' " .
				"OR `Result` LIKE '%{$searchText}%' ) ";
	}
	if ( !empty($_REQUEST['searchDateFrom']) ) {
		$searchDateFrom = addslashes(trim($_REQUEST['searchDateFrom']));
		$searchDateFrom = substr($searchDateFrom, 0, 10);
		$searchHourFrom = addslashes(trim($_REQUEST['searchHourFrom'])) + 0;
		$searchMinuteFrom = addslashes(trim($_REQUEST['searchMinuteFrom'])) + 0;
		$from = $searchDateFrom . " " . str_pad($searchHourFrom, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteFrom, 2, "0", STR_PAD_LEFT). ':00';
		$condition .= " AND `SentTime`>'{$from}' ";
	}
	if ( !empty($_REQUEST['searchDateEnd']) ) {
		$searchDateEnd = addslashes(trim($_REQUEST['searchDateEnd']));
		$searchDateEnd = substr($searchDateEnd, 0, 10);
		$searchHourEnd = addslashes(trim($_REQUEST['searchHourEnd'])) + 0;
		$searchHourEnd = empty($searchHourEnd) ? 23 : $searchHourEnd;
		$searchMinuteEnd = addslashes(trim($_REQUEST['searchMinuteEnd'])) + 0;
		$searchMinuteEnd = empty($searchMinuteEnd) ? 59 : $searchMinuteEnd;
		$end = $searchDateEnd . " " . str_pad($searchHourEnd, 2, "0", STR_PAD_LEFT) . ':' .  str_pad($searchMinuteEnd, 2, "0", STR_PAD_LEFT). ':59';
		$condition .= " AND `SentTime`<'{$end}' ";
	}
	if ( !empty($_REQUEST['searchStatus']) ) {
		$searchStatus = addslashes(trim($_REQUEST['searchStatus']));
		$condition .= " AND `Status`='{$searchStatus}' ";
	}
	
	$sql = "SELECT COUNT(`ID`) FROM `Sms` WHERE `Hide`=0 " . $condition;
	
//	echo $sql . "\n\n";
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `Receiver`, `Content`, `SentTime`, `RecvTime`, " .
			"`Success`, `ReturnStatus`, `Result`, `ReferenceID`, `Status`, `Remain`, `CustomID` " .
			"FROM `Sms` WHERE `Hide`=0 " . $condition;
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
//	echo $sql . "\n\n";
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "sms": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "Receiver":"'.$row['Receiver'].'", ' .
				'"Content":"'.$row['Content'].'", "SentTime":"'.$row['SentTime'].'", ' .
				'"RecvTime":"'.$row['RecvTime'].'", ' .
				'"Success":' . ( empty($row['Success']) ? 'false, ' : 'true, ' ) .
				'"ReturnStatus":"'.$row['ReturnStatus'].'", "Result":"'.$row['Result'].'", ' .
				'"Status":"'.$row['Status'].'", "Remain":"'.$row['Remain'].'", ' .
				'"ReferenceID":"'.$row['ReferenceID'].'", "CustomID":"'.$row['CustomID'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
	
}

function sms_delete () {
	//权限验证
	if( !check_privilege( "删除短信记录" ) ) {
		agent_log("删除短信记录", "短信ID：".trim($_POST["ids"])."，失败：没有删除短信记录的权限。");
		die( error_json ( "没有删除短信记录的权限。" ) );
	}
	
	//准备数据
	$ids = addslashes(trim($_POST["ids"]));
	if(empty($ids)){
		agent_log("删除短信记录", "失败：系统错误：短信ID为空。");
		return error_json("系统错误：短信ID为空");
	}
	
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Sms` SET `Hide`=1 WHERE `ID` IN ({$ids})" ;
    $result = $db->query($sql);
    
    //返回结果
    $re = "";
    if( $result!==FALSE) {
		agent_log("删除短信记录", "短信ID：".$ids."，成功。");
    	$re = success_json_no_data();
    }
    else {
		agent_log("删除短信记录", "短信ID：".$ids."，失败：数据库记录删除失败。");
    	$re = error_json( "数据库记录删除失败。" );
    }
    
    $db->close();
    return $re;
}

function sms_single_send() {
	//权限验证
	if( !check_privilege( "短信单发" ) ) {
		agent_log("短信单发", "失败，手机号码：".trim($_POST["Receiver"])."，短信内容：[".trim($_POST["Content"])."]，失败：没有短信单发的权限。");
		die( error_json ( "没有短信单发的权限。" ) );
	}
	
	//准备数据
	$Receiver = addslashes(trim($_POST["Receiver"]));
	$Content = addslashes(trim($_POST["Content"]));
	if(empty($Receiver)){
		agent_log("短信单发", "失败，短信内容：[".$Content."]，失败：手机号码为空。");
		return error_json("手机号码为空");
	}
	if(empty($Content)){
		agent_log("短信单发", "失败，手机号码：".$Receiver."，失败：短信内容为空。");
		return error_json("短信内容为空");
	}
	if(!is_mobile_number($Receiver)){
		agent_log("短信单发", "失败，手机号码不是有效的手机号码，手机号码：".$Receiver."，短信内容：[".$Content."]。");
    	$re = error_json( "请填写有效的手机号码。" );
		
	}
	
    //返回结果
    $re = "";
    $result = send_sms($Receiver,$Content,null);
    if( is_array($result) && !empty($result) ) {
		agent_log("短信单发", "成功，手机号码：".$Receiver."，短信内容：[".$Content."]。");
    	$re = success_json_no_data();
    }
    elseif($result===false) {
		agent_log("短信单发", "失败，短信没有提交，手机号码：".$Receiver."，短信内容：[".$Content."]。");
    	$re = error_json( "发送失败：短信没有提交。" );
    }
    else {
		agent_log("短信单发", "失败，手机号码：".$Receiver."，短信内容：[".$Content."]，原因：".$result."。");
    	$re = error_json( $result );
    }
    
    return $re;
	
}

/**
 * 获取当前的短信群发接收者列表
 */
function sms_get_queue_json() {
	//权限验证
	if( !check_privilege( "短信群发" ) ) {
		agent_log("短信群发", "获取短信群发列表失败：没有短信群发的权限。");
		die( error_json ( "没有短信群发的权限。" ) );
	}
	
	$re = "";
	$db = db_connect();
	
	$sql = "SELECT COUNT(`ID`) FROM `SmsQueue`;";
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
		
	$sql = "SELECT `SmsQueue`.`ID`, `SmsQueue`.`Receiver`, `SmsQueue`.`Content`, " .
			"`SmsQueue`.`CustomID`, `Custom`.`Username`" .
			"FROM `SmsQueue` LEFT JOIN `Custom` ON `SmsQueue`.`CustomID`=`Custom`.`ID`";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "queue": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "Receiver":"'.$row['Receiver'].'", ' .
				'"Content":"'.$row['Content'].'", "CustomID":"'.$row['CustomID'].'", ' .
				'"isCustom":' . ( empty($row['CustomID']) ? 'false, ' : 'true, ' ) .
				'"Username":"'.$row['Username'].'"}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	return $re;
}

/**
 * 根据$_POST数据添加一个非客户的短信内容
 */
function sms_queue_addone() {
	//权限验证
	if( !check_privilege( "短信群发" ) ) {
		agent_log("短信群发", "添加一个手机号码失败，手机号码：".trim($_POST["Receiver"])."，短信内容：[".trim($_POST["Content"])."]，失败：没有短信群发的权限。");
		die( error_json ( "没有短信群发的权限。" ) );
	}
	
	//准备数据
	$Receiver = addslashes(trim($_POST["Receiver"]));
	$Content = addslashes(trim($_POST["Content"]));
	$CustomID = addslashes(trim($_POST["CustomID"])) + 0;
	if(empty($Receiver)){
		agent_log("短信群发", "添加一个手机号码失败，短信内容：[".$Content."]，失败：手机号码为空。");
		return error_json("手机号码为空");
	}
	if(empty($CustomID) && empty($Content)){
		agent_log("短信群发", "添加一个手机号码失败，手机号码：".$Receiver."，失败：短信内容为空。");
		return error_json("短信内容为空");
	}
	if(!is_mobile_number($Receiver)){
		agent_log("短信群发", "添加一个手机号码失败，手机号码不是有效的手机号码，手机号码：".$Receiver."，短信内容：[".$Content."]。");
    	$re = error_json( "请填写有效的手机号码。" );
	}
	
    //返回结果
    $re = "";
    
    $db = db_connect();
    $sql = "INSERT INTO `SmsQueue`(`Receiver`, `Content`, `CustomID`) " .
    		"VALUES('{$Receiver}', '{$Content}', " .
    		(empty($CustomID) ? "NULL" : "'{$CustomID}'") . 
    		")";
    $db->query($sql);
    
    if( $db->result!==false ) {
		agent_log("短信群发", "添加一个手机号码成功，手机号码：".$Receiver."，短信内容：[".$Content."]。");
    	$re = '{"success":true, "id": '.$db->insert_id().'}';
    }
    else {
		agent_log("短信群发", "添加一个手机号码失败，数据库插入失败。");
    	$re = error_json( "数据库插入失败。" );
    }
    
	$db->close();
    return $re;
}


/**
 * 根据$_POST和短信队列表[SmsQueue]进行短信群发
 */
function sms_group_send() {
	//权限验证
	if( !check_privilege( "短信群发" ) ) {
		agent_log("短信群发", "失败：没有短信群发的权限。");
		die( error_json ( "没有短信群发的权限。" ) );
	}
	
	//准备数据
	$allSameContent = addslashes(trim($_POST["allSameContent"]));
	$emptyContent = addslashes(trim($_POST["emptyContent"]));
	$Content = addslashes(trim($_POST["Content"]));
	if ($allSameContent=='true' && empty($Content)){
		agent_log("短信群发", "失败：选中了“全部按以下内容发送”，但是短信内容为空。");
		die( error_json ( "选中了“全部按以下内容发送”，但是短信内容为空。" ) );
	}
	
	if ($emptyContent=='true' && empty($Content)){
		agent_log("短信群发", "失败：选中了“上述内容为空，则按以下内容发送”，但是短信内容为空。");
		die( error_json ( "选中了“上述内容为空，则按以下内容发送”，但是短信内容为空。" ) );
	}
	
	$re = "";
	$result = false;
	$db = db_connect();
	$sql = "SELECT `ID`, `Receiver`, `Content`, `CustomID` FROM `SmsQueue` ORDER BY `Content`;";
	$rs = $db->query($sql);
	
	if($allSameContent=='true') {//全部按照$Content进行发送
		$ids = array();	
		$receivers = array();
		$customIds = array();
		while($row = $rs->fetch_assoc()) {
			array_push($ids, $row['ID']);
			array_push($receivers, $row['Receiver']);
			array_push($customIds, $row['CustomID']);
		}
		$result = send_sms($receivers,$Content, $customIds);
		if($result !==false) {
			$sql = "DELETE FROM `SmsQueue`;";
			$db->query($sql);
			if(is_array($result) && count($result)==count($ids)) {
				$re = success_json_no_data();
			}
			else {
				$re = error_json($result);
			}
		}
	}
	else {
		$sent = false;
		$allOK = true;
		$errorMsg = "";
		$currentContent = "";
		$ids = array();	
		$receivers = array();
		$customIds = array();
		while($row = $rs->fetch_assoc()) {
			if($row['Content']!=$currentContent) {
				if($currentContent=="" && $emptyContent=='true'){
					$result = send_sms($receivers,$Content, $customIds);
					$sent = true;
				}
				else if($currentContent!="") {
					$result = send_sms($receivers,$currentContent, $customIds);
					$sent = true;
				}
				else {
					$sent = false;
				}
				
				if( $sent ) {
					if($result !== false){
						$sql = "DELETE FROM `SmsQueue` WHERE `ID` IN (".implode(",",$ids).")";
						$db->query($sql);
						$allOK = $allOK && is_array($result) && (count($result)==count($ids));
						if(!is_array($result)){
							$errorMsg = "部分失败原因：" . $result . "<br>";
						} 
					}
				}
				
				$ids = array();	
				$receivers = array();
				$customIds = array();
				$currentContent = $row['Content'];
				$sent = false;
			}
			array_push($ids, $row['ID']);
			array_push($receivers, $row['Receiver']);
			array_push($customIds, $row['CustomID']);
		}
		
		if(!$sent) {
			$result = send_sms($receivers,$currentContent, $customIds);
			if($result !== false){
				$sql = "DELETE FROM `SmsQueue` WHERE `ID` IN (".implode(",",$ids).")";
				$db->query($sql);
				$allOK = $allOK && is_array($result) && (count($result)==count($ids));
				if(!is_array($result)){
					$errorMsg = "部分失败原因：" . $result . "<br>";
				} 
			}
		}
		
		if($allOK) $re = success_json_no_data();
		else $re = error_json($errorMsg);
	}
	$db->close();
	return $re;
}

/**
 * 获取当前的订单列表JSON
 */
function get_orders_json() {
	if(!check_privilege('查看当前订单')) return "";
	
	process_long_time();
	
	$re = "";
	$db = db_connect();
	
	$condition = " `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			(!isset($_SESSION['admin_is_restaurant']) ? 
				"AND `Restaurant`.`AgentId` IN ({$_SESSION['admin_descendants']}) "
				: "AND `Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' "
			) .
			"AND (`Order`.`Status` = '正在送餐' " .
			(!isset($_SESSION['admin_is_restaurant']) ? " OR `Order`.`Status` = '等待手机验证' " : "") .
			(!isset($_SESSION['admin_is_restaurant']) ? " OR `Order`.`Status` = '创建' " : "") .
			") " .
			"AND `Restaurant`.`Hide`=0 ";
	
	$sql = "SELECT COUNT(`Order`.`ID`) FROM `Order`,`Restaurant` WHERE " . $condition;
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `Order`.`ID`, `Order`.`CustomID`, `Order`.`RestaurantID`, " .
			"`Restaurant`.`Name` as Restaurant, `Order`.`Mobile`, `Order`.`CreateTime`, " .
			"`Order`.`Address`, `Order`.`Notes`, `Order`.`Total`, `Order`.`Status`, " .
			"`Order`.`CTime`, `Order`.`Urged`, `Order`.`EndTime`,`Order`.`SmsSent` ,`Restaurant`.`Agent`, " .
			"`Order`.`Takeout`, `Order`.`TimeNote`, `Order`.`Discount`, `Order`.`DiscountTotal`, `Order`.`VeriCode` " .
			"FROM `Order`,`Restaurant` WHERE " . $condition . 
			" ORDER BY `Order`.`ID` ASC ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$sql = "SELECT TA.*, `Custom`.`Username` FROM " .
		"(" . $sql .")  AS TA " .
		"LEFT JOIN `Custom` ON TA.`CustomID` =  `Custom`.`ID` ";

	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "orders": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.($row['ID']+0).', "CustomID":'.($row['CustomID']+0).', ' .
				'"RestaurantID":'.($row['RestaurantID']+0).', "Restaurant":"'.$row['Restaurant'].'", ' .
				'"Mobile":"'.$row['Mobile'].'", "CreateTime":"'.$row['CreateTime'].'", ' .
				'"Address":"'.$row['Address'].'", "Notes":"'.$row['Notes'].'", ' .
				'"Total":'.($row['Total']+0).', "Status":"'.$row['Status'].'", ' .
				'"CTime":"'.$row['CTime'].'", "CustomName":"'.$row['Username'].'", ' .
				'"Urged":' . ( empty($row['Urged']) ? 'false, ' : 'true,' ) .
				'"SmsSent":' . ( empty($row['SmsSent']) ? 'false, ' : 'true,' ) .
				'"EndTime":"'.$row['EndTime'].'", "Agent":"'.$row['Agent'].'", ' .
				'"Takeout":"'.(empty($row['Takeout'])? "到店消费" : "送餐上门").'", ' .
				'"TimeNote":"'.$row['TimeNote'].'", "VeriCode":"'.$row['VeriCode'].'",' .
				'"Discount":"'.($row['Discount']+0).'", "DiscountTotal":"'.($row['DiscountTotal']+0).'" ' .
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

/**
 * 获取历史订单列表JSON
 */
function get_history_orders_json() {
	if(!check_privilege('查看历史订单')) return "";
	$re = "";
	$db = db_connect();
	
	$condition = " `Order`.`RestaurantID`=`Restaurant`.`ID` " .
			(!isset($_SESSION['admin_is_restaurant']) ? 
				"AND `Restaurant`.`AgentId` IN ({$_SESSION['admin_descendants']}) "
				: "AND `Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' "
			) .
			"AND (`Order`.`Status` = '已取消' " .
			" OR `Order`.`Status` = '自动删除' " .
			" OR `Order`.`Status` = '成功结束' " .
			") " .
			"AND `Restaurant`.`Hide`=0 ";
	
	$sql = "SELECT COUNT(`Order`.`ID`) FROM `Order`,`Restaurant` WHERE " . $condition;
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `Order`.`ID`, `Order`.`CustomID`, `Order`.`RestaurantID`, " .
			"`Restaurant`.`Name` as Restaurant, `Order`.`Mobile`, `Order`.`CreateTime`, " .
			"`Order`.`Address`, `Order`.`Notes`, `Order`.`Total`, `Order`.`Status`, " .
			"`Order`.`CTime`, `Order`.`Urged`, `Order`.`EndTime`,`Order`.`SmsSent` ,`Restaurant`.`Agent`, " .
			"`Order`.`Takeout`, `Order`.`TimeNote`, `Order`.`Discount`, `Order`.`DiscountTotal`, `Order`.`VeriCode` " .
			"FROM `Order`,`Restaurant` WHERE " . $condition .
			" ORDER BY `Order`.`ID` ASC ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$sql = "SELECT TA.*, `Custom`.`Username` FROM " .
			"(" . $sql .")  AS TA " .
			"LEFT JOIN `Custom` ON TA.`CustomID` =  `Custom`.`ID` ";
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "orders": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.($row['ID']+0).', "CustomID":'.($row['CustomID']+0).', ' .
				'"RestaurantID":'.($row['RestaurantID']+0).', "Restaurant":"'.$row['Restaurant'].'", ' .
				'"Mobile":"'.$row['Mobile'].'", "CreateTime":"'.$row['CreateTime'].'", ' .
				'"Address":"'.$row['Address'].'", "Notes":"'.$row['Notes'].'", ' .
				'"Total":'.($row['Total']+0).', "Status":"'.$row['Status'].'", ' .
				'"CTime":"'.$row['CTime'].'", "CustomName":"'.$row['Username'].'", ' .
				'"Urged":' . ( empty($row['Urged']) ? 'false, ' : 'true,' ) .
				'"SmsSent":' . ( empty($row['SmsSent']) ? 'false, ' : 'true,' ) .
				'"EndTime":"'.$row['EndTime'].'", "Agent":"'.$row['Agent'].'",' .
				'"Takeout":"'.(empty($row['Takeout'])? "到店消费" : "送餐上门").'", ' .
				'"TimeNote":"'.$row['TimeNote'].'", "VeriCode":"'.$row['VeriCode'].'",' .
				'"Discount":"'.($row['Discount']+0).'", "DiscountTotal":"'.($row['DiscountTotal']+0).'" ' .
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}


function get_order_items_json() {
	$orderid = $_REQUEST['orderid']+0;
	if(!check_privilege('查看当前订单')
		|| !check_privilege('查看历史订单')
		|| empty($orderid))
	{
		return "";
	}
	
	$re = "";
	$db = db_connect();
	
	$sql = "SELECT COUNT(`ID`) FROM `OrderItem` WHERE `OrderID`='{$orderid}'" ;
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `OrderID`, `DishID`, `Name`, `Price`, `Count`, `RestaurantID`, `Restaurant` " .
			"FROM `OrderItem` WHERE `OrderID`='{$orderid}'" ;
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "orderitems": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.($row['ID']+0).', "OrderID":'.($row['OrderID']+0).', "DishID":'.($row['DishID']+0).', ' .
				'"RestaurantID":'.($row['RestaurantID']+0).', "Restaurant":"'.$row['Restaurant'].'", ' .
				'"Name":"'.$row['Name'].'", "Price":'.($row['Price']+0).', "Count":'.($row['Count']+0) .
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

function get_order_process_json() {
	$orderid = $_REQUEST['orderid']+0;
	if(!check_privilege('查看当前订单')
		|| !check_privilege('查看历史订单')
		|| empty($orderid))
	{
		return "";
	}
	
	$re = "";
	$db = db_connect();
	
	$sql = "SELECT COUNT(`ID`) FROM `OrderProcess` WHERE `OrderID`='{$orderid}'" ;
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `OrderID`, `Type`, `Time`, `Activity` " .
			"FROM `OrderProcess` WHERE `OrderID`='{$orderid}'" ;
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "orderprocess": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.($row['ID']+0).', "OrderID":'.($row['OrderID']+0).', ' .
				'"Type":'.($row['Type']+0).', "Time":"'.$row['Time'].'", "Activity":"'.$row['Activity'].'"' .
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

function get_custom_address_json() {
	$customid = $_REQUEST['customid']+0;
	if(empty($customid))
	{
		return "";
	}
	
	$re = "";
	$db = db_connect();
	
	$sql = "SELECT COUNT(`ID`) FROM `CustomAddress` WHERE `CustomID`='{$customid}'" ;
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `ID`, `CustomID`, `Address` " .
			"FROM `CustomAddress` WHERE `CustomID`='{$customid}'" ;
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "addresses": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.($row['ID']+0).', "CustomID":'.($row['CustomID']+0).', ' .
				'"Address":"'.$row['Address'].'"' .
				'}';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

/**
 * 手工下单
 */
function drop_order() {
	if(!check_privilege('手工下单')){
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：没有手工下单的权限。");
		}
		else {
			agent_log("手工下单", "失败：没有手工下单的权限。"); //应该只有代理可能没有下单功能
		}
		die( error_json ( "没有手工下单的权限。" ) );
	}
	
	//准备数据
	$customid = addslashes(trim($_POST["customid"])) + 0;
	$restaurantid = addslashes(trim($_POST["restaurantid"])) + 0;
	$restaurant = addslashes(trim($_POST["restaurant"]));
	$restaurantmobile = addslashes(trim($_POST["restaurantmobile"]));
	$mobile = addslashes(trim($_POST["mobile"]));
	$address = addslashes(trim($_POST["address"]));
	$notes = addslashes(trim($_POST["notes"]));
	if (empty($restaurantid)){
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：系统错误，餐馆id为空。");
		}
		else {
			agent_log("手工下单", "失败：系统错误，餐馆id为空。");
		}
		die( error_json ( "系统错误，餐馆id为空。" ) );
	}
	if (empty($customid)){
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：系统错误，顾客id为空。");
		}
		else {
			agent_log("手工下单", "失败：系统错误，顾客id为空。");
		}
		die( error_json ( "系统错误，顾客id为空。" ) );
	}
	if (!is_mobile_number( $restaurantmobile )){
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：系统错误：餐馆手机号码不是有效的手机号码。");
		}
		else {
			agent_log("手工下单", "失败：系统错误：餐馆手机号码不是有效的手机号码。");
		}
		die( error_json ( "系统错误：餐馆手机号码不是有效的手机号码。" ) );
	}
	if (!is_mobile_number( $mobile )){
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：手机号码不是有效的手机号码。");
		}
		else {
			agent_log("手工下单", "失败：手机号码不是有效的手机号码。");
		}
		die( error_json ( "手机号码不是有效的手机号码。" ) );
	}
	if (empty($address)){
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：顾客地址为空。");
		}
		else {
			agent_log("手工下单", "失败：顾客地址为空。");
		}
		die( error_json ( "顾客地址为空。" ) );
	}
	$dishes = explode(",",addslashes(trim($_POST["dishes"])));
	$names = explode(",",addslashes(trim($_POST["names"])));
	$prices = explode(",",addslashes(trim($_POST["prices"])));
	$count = explode(",",addslashes(trim($_POST["count"])));
	if(count($dishes)!=count($count) || count($names)!=count($count) || count($names)!=count($count)) {
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log("手工下单", "失败：系统错误：餐品数据不合法。");
		}
		else {
			agent_log("手工下单", "失败：系统错误：餐品数据不合法。");
		}
		die( error_json ( "系统错误：餐品数据不合法。<br>注意：餐品名称不能包含英文的逗号。" ) );
	}
	
	$db = db_connect();
	$re = "";
	
	//保存订单信息
	$sql = "INSERT INTO `Order`(`CustomID`,`RestaurantID`,`Mobile`,`Address`,`Notes`,`CreateTime`,`LastUpdate`)" .
			"VALUES('{$customid}', '{$restaurantid}', '{$mobile}', " .
			"'{$address}', '{$notes}', '".get_datetime()."', '".get_datetime()."')";
	$db->query($sql);
	if($db->result!==false) {
		$id = $db->insert_id();
		$total = 0;
		//保存订单项
		$items = array();
		foreach($dishes as $index => $dishid) {
			$total += $prices[$index] * $count[$index];
			$sql = "INSERT INTO `OrderItem`(`OrderID`,`DishID`,`Name`,`Price`," .
					"`Count`,`RestaurantID`,`Restaurant`)" .
					"VALUES('{$id}','{$dishid}','{$names[$index]}','{$prices[$index]}'," .
					"'{$count[$index]}','{$restaurantid}','{$restaurant}')";
			$db->query($sql);
			array_push($items, $names[$index] . "，" . ($prices[$index]+0) . "元x" . $count[$index]);
		}
		
		$sql = "UPDATE `Order` SET `Total`='{$total}' WHERE `ID`='{$id}';";
		$db->query($sql);
		if(isset($_SESSION['admin_is_restaurant'])){
			restaurant_log('手工下单', '成功，餐馆：'.$restaurant."，共计：".$total."元。");
		}
		else {
			agent_log('手工下单', '成功，餐馆：'.$restaurant."，共计：".$total."元。");
		}
		
		
		if(isset($_SESSION['admin_is_restaurant'])){
			order_process($id, 1,"餐馆手工下单");
			order_process($id, 5,"餐馆手工下单");
			order_process($id, 7,"餐馆手工下单");
		}
		else {
			order_process($id, 1,"代理手工下单");
			
			if(!isset($_SESSION['admin_setting_SITE_NAME'])){
				read_setting();
			}
			
			$content = $_SESSION['admin_setting_SITE_NAME'] . "客户订单：" . implode("；", $items) . "；共计" . $total . "元。" .
					"客户：" . $mobile . "；地址：" . $address . "；要求：" . (empty($notes) ? "无" : $notes) .
	//				"。请回复“1" . $orderid . "”确认订单，回复“2" . $orderid . "”取消订单，如有说明请在数字后面输入。" .
					"";
			$ids = send_sms($restaurantmobile, $content, $customid);
			if(is_array($ids) && !empty($ids)){
				$sql = "INSERT INTO `OrderSms`(`SmsID`,`CustomID`,`OrderID`,`RestaurantID`,`Restaurant`,`Content`,`SentTime`) " .
						"VALUES('".$ids[0]."','{$customid}', '{$id}', '{$restaurantid}', '{$restaurant}','{$content}','".get_datetime()."')" ;
				$db->query($sql);
			
				$sql = "UPDATE `Order` SET `Status`='正在送餐',`SmsSent`=1,`LastUpdate`='".get_datetime()."' WHERE `ID`='{$orderid}';";
				$db->query($sql);
				order_process($id, 3,"代理手工下单");
				order_process($id, 5,"代理手工下单");
				agent_log('手工下单', '订单短信成功发送给餐馆。');
				$re = success_json_no_data();
			}
			elseif($ids === false) {
				$sql = "UPDATE `Order` SET `Status`='已取消',`SmsSent`=0, EndTime='".get_datetime()."',`LastUpdate`='".get_datetime()."'  WHERE `ID`='{$orderid}';";
				$db->query($sql);
				order_process($id, 8,"非常抱歉，未能通知餐馆，本单已自动删除");
				agent_log('手工下单', '订单短信发送给餐馆失败：由于手机号码错误，根本就没有发送短信。');
				$re = error_json("订单已保存到数据库，但是订单短信发送给餐馆失败：由于手机号码错误，根本就没有发送短信。");
			}
			else {
				$sql = "UPDATE `Order` SET `Status`='已取消',`SmsSent`=0, EndTime='".get_datetime()."',`LastUpdate`='".get_datetime()."'  WHERE `ID`='{$orderid}';";
				$db->query($sql);
				order_process($id, 8,"非常抱歉，未能通知餐馆，本单已自动删除");
				agent_log('手工下单', '订单短信发送给餐馆失败：原因：' . $ids);
				$re = error_json("订单已保存到数据库，但是订单短信发送给餐馆失败：原因：" . $ids);
			}
		}
		
	}
	else {
		$re = error_json("数据库插入失败");
	}
	$db->close();
	return $re;
}

/**
 * 进行获取月结佣金情况
 */
function get_commissions_json() {
	if($_REQUEST['type']=='monthly' && !(check_privilege('按月查询') || check_privilege('月销售额'))){
		agent_log("按月查询财务状况", "失败：没有按月查询查询财务状况的权限。");
		die( error_json ( "没有按月查询财务状况的权限。" ) );
	}
	elseif(!check_privilege('自定义查询') && !check_privilege('自定义查看')){
		agent_log("自定义查询财务状况", "失败：没有自定义查询财务状况的权限。");
		die( error_json ( "没有自定义查询财务状况的权限。" ) );
	}
	
	if(!isset($_SESSION['admin_is_restaurant'])){//如果是代理，再计算自己及下属各机构的日结
		if($_REQUEST['close']=='true'){
			close_agent_commission();
		}
		return get_agent_monthly_commission_json();
	}
	else {//否则，计算餐馆的日结
		if($_REQUEST['close']=='true'){
			close_commission();
		}
		return get_restaurant_monthly_commission_json();
	}
}

/**
 * 代理的月结表：分级显示当月（或者某个指定的月）的数据
 */
function get_agent_monthly_commission_json() { //TODO
	$condition = "";
	$condition2 = "";
	
	$searchYear = empty($_REQUEST['searchYear']) ? date('Y') : addslashes(trim($_REQUEST['searchYear'])) + 0;
	$condition .= " AND `AgentCmsMonthly`.`Year`='{$searchYear}' ";
	$condition2 .= " AND `CmsMonthly`.`Year`='{$searchYear}' ";
	
	$searchMonth = empty($_REQUEST['searchMonth']) ? date('n') : addslashes(trim($_REQUEST['searchMonth'])) + 0;
	$condition .= " AND `AgentCmsMonthly`.`Month`='{$searchMonth}' ";
	$condition2 .= " AND `CmsMonthly`.`Month`='{$searchMonth}' ";
	
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Agent`.`City` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Name` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Telephone` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Mobile` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Username` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Realname` LIKE '%{$searchText}%') ";
		$condition2 .= " AND (`Restaurant`.`City` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Name` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Telephone` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Mobile` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Address` LIKE '%{$searchText}%') ";
	}
	
	if ( !empty($_REQUEST['searchStatus']) ) {
		$searchStatus = addslashes(trim($_REQUEST['searchStatus']));
		$condition .= " AND `AgentCmsMonthly`.`Status`='{$searchStatus}' ";
		$condition2 .= " AND `CmsMonthly`.`Status`='{$searchStatus}' ";
	}
	
	$node = addslashes(trim($_REQUEST["node"])) + 0;
	//直属下级代理，如果是根节点，应该包括自己
	$descendants_set = ($node==0 ? 
					get_agent_descendants_set($_SESSION['admin_agent_id'], true, true) //直属true，包括自己true
					: get_agent_descendants_set($node, true, false)); //直属true，包括自己false

	$re = "";
	$db = db_connect();
	$children = array();
	$me = "";
	
	//先取直属代理的月结数据
	if(!empty($descendants_set)) {
		$sql = "SELECT `Agent`.`ID`, `Agent`.`Name`, `AgentCmsMonthly`.`ID` AS CmsID,  " .
				"`AgentCmsMonthly`.`Year`, `AgentCmsMonthly`.`Month`, `AgentCmsMonthly`.`Day`, " .
				"`AgentCmsMonthly`.`Days`, `AgentCmsMonthly`.`Sale`, `AgentCmsMonthly`.`Rate`, " .
				"`AgentCmsMonthly`.`Commission`, `AgentCmsMonthly`.`Status`, `AgentCmsMonthly`.`CloseTime` " .
				"FROM `AgentCmsMonthly`,`Agent` " .
				"WHERE `AgentCmsMonthly`.`AgentID`=`Agent`.`ID` " .
				"AND `AgentCmsMonthly`.`AgentID` IN ({$descendants_set}) " .
				$condition . 
				"ORDER BY `Agent`.`Level` ASC,  `Agent`.`HeadID` ASC,  `Agent`.`ID` ASC ";
//		echo "先取直属代理的月结数据\nSQL: $sql\n\n";
		$rs = $db->query($sql);
		while($row = $rs->fetch_assoc()) {
			$row_json = 'id: '.($row['ID']+0).',text: "'.$row['Name'].'",CmsID: '.($row['CmsID']+0).', ' .
					'Year:'.($row['Year']+0).', Month:'.$row['Month'].', Day:"'.$row['Day'].'", ' .
					'Days:"'.$row['Days'].'", Sale:"'.(empty($row['Sale']) ? "0.00": $row['Sale']).'", Rate:"'.$row['Rate'].'", ' .
					'Commission:"'.(empty($row['Commission']) ? "0.00": $row['Commission']).'", Status:"'.$row['Status'].'", CloseTime:"'.$row['CloseTime'].'", ' .
					'leaf:false, iconCls: "tree_node_agent" ';
			if($row['ID']==$_SESSION['admin_agent_id'])
				$me = $row_json;
			else 
				$children[] = "{" . $row_json. "}";
		}
	}
	
	//再加上直属餐馆的数据
	$agent_id = ($node==0 ? $_SESSION['admin_agent_id'] : $node);
	$sql = "SELECT `Restaurant`.`ID`, `Restaurant`.`Name`, `CmsMonthly`.`ID` AS CmsID, " .
			"`CmsMonthly`.`Year`, `CmsMonthly`.`Month`, `CmsMonthly`.`Day`, " .
			"`CmsMonthly`.`Days`, `CmsMonthly`.`Sale`, `CmsMonthly`.`Rate`, " .
			"`CmsMonthly`.`Commission`, `CmsMonthly`.`Status`, `CmsMonthly`.`CloseTime` " .
			"FROM `CmsMonthly`,`Restaurant` " .
			"WHERE `CmsMonthly`.`RestaurantID`=`Restaurant`.`ID` " .
			"AND `Restaurant`.`AgentId`='{$agent_id}'" .
			$condition2 . 
			"ORDER BY `Restaurant`.`Name` ASC ";
//	echo "再加上直属餐馆的数据\nSQL: $sql\n\n";
	$rs = $db->query($sql);
	while($row = $rs->fetch_assoc()) {
		$row_json = 'id: "Restaurant_'.($row['ID']+0).'",text: "'.$row['Name'].'",CmsID: '.($row['CmsID']+0).', ' .
				'Year:'.($row['Year']+0).', Month:'.$row['Month'].', Day:"'.$row['Day'].'", ' .
				'Days:"'.$row['Days'].'", Sale:"'.(empty($row['Sale']) ? "0.00": $row['Sale']).'", Rate:"'.$row['Rate'].'%", ' .
				'Commission:"'.(empty($row['Commission']) ? "0.00": $row['Commission']).'", Status:"'.$row['Status'].'", CloseTime:"'.$row['CloseTime'].'", ' .
				'leaf:true, iconCls: "tree_node_restaurent" ';
		$children[] = "{" . $row_json. "}";
	}

	//组装结果
	$re = ($node==0 ? 
			(empty($me) ? "[".implode(",",$children)."]" : "[{".$me.",expanded: true,children:[".implode(",",$children)."]}]")
		 : ("[".implode(",",$children)."]"));
	
	$db->close();
	return $re;
}


/**
 * 餐馆的月结表：分页显示多月的数据
 */
function get_restaurant_monthly_commission_json() {
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if ( !empty($_REQUEST['searchYear']) ) {
		$searchYear = addslashes(trim($_REQUEST['searchYear']));
		$condition .= " AND `CmsMonthly`.`Year`='{$searchYear}' ";
	}
	if ( !empty($_REQUEST['searchMonth']) ) {
		$searchMonth = addslashes(trim($_REQUEST['searchMonth']));
		$condition .= " AND `CmsMonthly`.`Month`='{$searchMonth}' ";
	}
	if ( !empty($_REQUEST['searchStatus']) ) {
		$searchStatus = addslashes(trim($_REQUEST['searchStatus']));
		$condition .= " AND `CmsMonthly`.`Status`='{$searchStatus}' ";
	}
	
	$sql = "SELECT COUNT(`CmsMonthly`.`ID`) FROM `CmsMonthly` " .
			"WHERE `CmsMonthly`.`RestaurantID`='{$_SESSION['admin_restaurant_id']}' " 
			. $condition; 
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `CmsMonthly`.`ID`, `CmsMonthly`.`RestaurantID`, `Restaurant`.`Name` AS Restaurant, " .
			"`Restaurant`.`Agent`, `CmsMonthly`.`Year`, `CmsMonthly`.`Month`, `CmsMonthly`.`Day`, " .
			"`CmsMonthly`.`Days`, `CmsMonthly`.`Sale`, `CmsMonthly`.`Rate`, `CmsMonthly`.`Commission`, " .
			"`CmsMonthly`.`Status`, `CmsMonthly`.`CloseTime` " .
			"FROM `CmsMonthly`, `Restaurant` " .
			"WHERE `CmsMonthly`.`RestaurantID` = `Restaurant`.`ID`  " .
			"AND `Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' " .
			 $condition .
			" ORDER BY `Restaurant`.`AgentID`, `CmsMonthly`.`RestaurantID`, `CmsMonthly`.`Year`, " .
			"`CmsMonthly`.`Month`, `CmsMonthly`.`Day`, `CmsMonthly`.`CloseTime` ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "commissions": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "RestaurantID":'.$row['RestaurantID'].', ' .
				'"Restaurant":"'.$row['Restaurant'].'", "Agent":"'.$row['Agent'].'", ' .
				'"Year":'.($row['Year']+0).', "Month":'.($row['Month']+0).', ' .
				'"Day":"'.$row['Day'].'", "Days":"'.$row['Days'].'", ' .
				'"Sale":"'.(empty($row['Sale']) ? "0.00": $row['Sale']).'", "Rate":"'.($row['Rate']).'%", ' .
				'"Commission":"'.(empty($row['Commission']) ? "0.00": $row['Commission']).'", ' .
				'"Status":"'.$row['Status'].'", "CloseTime":"'.$row['CloseTime'].'"} ';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

function get_daily_commissions_json() {
	if(!check_privilege('按日查询') && !check_privilege('日销售额')){
		agent_log("按日查询财务状况", "失败：没有按日查询查询财务状况的权限。");
		die( error_json ( "没有按日查询财务状况的权限。" ) );
	}
	
	if(!isset($_SESSION['admin_is_restaurant'])){//如果是代理，再计算自己及下属各机构的日结
		if($_REQUEST['close']=='true'){
			close_agent_daily_commission();
		}
		return get_agent_daily_commission_json();
	}
	else {//否则，计算餐馆的日结
		if($_REQUEST['close']=='true'){
			close_daily_commission();
		}
		return get_restaurant_daily_commission_json();
	}
}

function get_agent_daily_commission_json() {// TODO 
	$condition = "";
	$condition2 = "";
	
	$searchYear = empty($_REQUEST['searchYear']) ? date('Y') : addslashes(trim($_REQUEST['searchYear'])) + 0;
	$condition .= " AND DATE_FORMAT(`AgentCmsDaily`.`Day`,'%Y')='{$searchYear}' ";
	$condition2 .= " AND DATE_FORMAT(`CmsDaily`.`Day`,'%Y')='{$searchYear}' ";
	
	$searchMonth = empty($_REQUEST['searchMonth']) ? date('m') : addslashes(trim($_REQUEST['searchMonth'])) + 0;
	$searchMonth = str_pad($searchMonth, 2, "0", STR_PAD_LEFT);
	$condition .= " AND DATE_FORMAT(`AgentCmsDaily`.`Day`,'%m')='{$searchMonth}' ";
	$condition2 .= " AND DATE_FORMAT(`CmsDaily`.`Day`,'%m')='{$searchMonth}' ";
	
	$searchDay = empty($_REQUEST['searchDay']) ? date('j') : addslashes(trim($_REQUEST['searchDay'])) + 0;
	$condition .= " AND DATE_FORMAT(`AgentCmsDaily`.`Day`,'%e')='{$searchDay}' ";
	$condition2 .= " AND DATE_FORMAT(`CmsDaily`.`Day`,'%e')='{$searchDay}' ";
	
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Agent`.`City` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Name` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Telephone` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Mobile` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Username` LIKE '%{$searchText}%' " .
				"OR `Agent`.`Realname` LIKE '%{$searchText}%') ";
		$condition2 .= " AND (`Restaurant`.`City` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Name` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Telephone` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Mobile` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Address` LIKE '%{$searchText}%') ";
	}
	
	if ( !empty($_REQUEST['searchStatus']) ) {
		$searchStatus = addslashes(trim($_REQUEST['searchStatus']));
		$condition .= " AND `AgentCmsDaily`.`Status`='{$searchStatus}' ";
		$condition2 .= " AND `CmsDaily`.`Status`='{$searchStatus}' ";
	}
	
	$node = addslashes(trim($_REQUEST["node"])) + 0;
	//直属下级代理，如果是根节点，应该包括自己
	$descendants_set = ($node==0 ? 
					get_agent_descendants_set($_SESSION['admin_agent_id'], true, true) //直属true，包括自己true
					: get_agent_descendants_set($node, true, false)); //直属true，包括自己false

	$re = "";
	$db = db_connect();
	$children = array();
	$me = "";
	
	//先取直属代理的日结数据
	if(!empty($descendants_set)) {
		$sql = "SELECT `Agent`.`ID`, `Agent`.`Name`, `AgentCmsDaily`.`ID` AS CmsID, " .
				"`AgentCmsDaily`.`Day`, `AgentCmsDaily`.`Sale`, `AgentCmsDaily`.`Rate`, " .
				"`AgentCmsDaily`.`Commission`, `AgentCmsDaily`.`Status`, `AgentCmsDaily`.`CloseTime` " .
				"FROM `AgentCmsDaily`,`Agent` " .
				"WHERE `AgentCmsDaily`.`AgentID`=`Agent`.`ID` " .
				"AND `AgentCmsDaily`.`AgentID` IN ({$descendants_set}) " .
				$condition . 
				"ORDER BY `Agent`.`Level` ASC,  `Agent`.`HeadID` ASC,  `Agent`.`ID` ASC ";
//		echo "先取直属代理的月结数据\nSQL: $sql\n\n";
		$rs = $db->query($sql);
		while($row = $rs->fetch_assoc()) {
			$row_json = 'id: '.($row['ID']+0).',text: "'.$row['Name'].'",CmsID: '.($row['CmsID']+0).', ' .
					'Day:"'.$row['Day'].'", Sale:"'.(empty($row['Sale']) ? "0.00": $row['Sale']).'", Rate:"'.$row['Rate'].'", ' .
					'Commission:"'.(empty($row['Commission']) ? "0.00": $row['Commission']).'", Status:"'.$row['Status'].'", CloseTime:"'.$row['CloseTime'].'", ' .
					'leaf:false, iconCls: "tree_node_agent" ';
			if($row['ID']==$_SESSION['admin_agent_id'])
				$me = $row_json;
			else 
				$children[] = "{" . $row_json. "}";
		}
	}
	
	//再加上直属餐馆的数据
	$agent_id = ($node==0 ? $_SESSION['admin_agent_id'] : $node);
	$sql = "SELECT `Restaurant`.`ID`, `Restaurant`.`Name`, `CmsDaily`.`ID` AS CmsID, " .
			"`CmsDaily`.`Day`, `CmsDaily`.`Sale`, `CmsDaily`.`Rate`, " .
			"`CmsDaily`.`Commission`, `CmsDaily`.`Status`, `CmsDaily`.`CloseTime` " .
			"FROM `CmsDaily`,`Restaurant` " .
			"WHERE `CmsDaily`.`RestaurantID`=`Restaurant`.`ID` " .
			"AND `Restaurant`.`AgentId`='{$agent_id}'" .
			$condition2 . 
			"ORDER BY `Restaurant`.`Name` ASC ";
//	echo "再加上直属餐馆的数据\nSQL: $sql\n\n";
	$rs = $db->query($sql);
	while($row = $rs->fetch_assoc()) {
		$row_json = 'id: "Restaurant_'.($row['ID']+0).'",text: "'.$row['Name'].'",CmsID: '.($row['CmsID']+0).', ' .
				'Day:"'.$row['Day'].'", Sale:"'.(empty($row['Sale']) ? "0.00": $row['Sale']).'", Rate:"'.$row['Rate'].'%", ' .
				'Commission:"'.(empty($row['Commission']) ? "0.00": $row['Commission']).'", Status:"'.$row['Status'].'", CloseTime:"'.$row['CloseTime'].'", ' .
				'leaf:true, iconCls: "tree_node_restaurent" ';
		$children[] = "{" . $row_json. "}";
	}

	//组装结果
	$re = ($node==0 ? 
			(empty($me) ? "[".implode(",",$children)."]" : "[{".$me.",expanded: true,children:[".implode(",",$children)."]}]")
		 : ("[".implode(",",$children)."]"));
	
	$db->close();
	return $re;
}

function get_restaurant_daily_commission_json() {// TODO 
	$re = "";
	$db = db_connect();
	
	$condition = "";
	if( !empty($_REQUEST["searchText"]) ) {
		$searchText = addslashes(trim($_REQUEST['searchText']));
		$condition .= " AND (`Restaurant`.`City` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Name` LIKE '%{$searchText}%' " .
				"OR `Restaurant`.`Agent` LIKE '%{$searchText}%') ";
	}
	if ( !empty($_REQUEST['searchYear']) ) {
		$searchYear = addslashes(trim($_REQUEST['searchYear']));
		$condition .= " AND DATE_FORMAT(`CmsDaily`.`Day`,'%Y')='{$searchYear}' ";
	}
	if ( !empty($_REQUEST['searchMonth']) ) {
		$searchMonth = addslashes(trim($_REQUEST['searchMonth']));
		$searchMonth = str_pad($searchMonth, 2, "0", STR_PAD_LEFT);
		$condition .= " AND DATE_FORMAT(`CmsDaily`.`Day`,'%m')='{$searchMonth}' ";
	}
	if ( !empty($_REQUEST['searchDay']) ) {
		$searchDay = addslashes(trim($_REQUEST['searchDay']));
		$condition .= " AND DATE_FORMAT(`CmsDaily`.`Day`,'%e')='{$searchDay}' ";
	}
	if ( !empty($_REQUEST['searchStatus']) ) {
		$searchStatus = addslashes(trim($_REQUEST['searchStatus']));
		$condition .= " AND `CmsDaily`.`Status`='{$searchStatus}' ";
	}
	
	$sql = "SELECT COUNT(`CmsDaily`.`ID`) FROM `CmsDaily`, `Restaurant` " .
			"WHERE `CmsDaily`.`RestaurantID` = `Restaurant`.`ID` " .
			(!isset($_SESSION['admin_is_restaurant']) ? 
				"AND `Restaurant`.`AgentId` IN ({$_SESSION['admin_descendants']}) "
				: "AND `Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' "
			) .
			"" . $condition;
	
	$total_rs = $db->query($sql);
	$total_row = $total_rs->fetch_row();
	$total = $total_row[0];
	
	$sql = "SELECT `CmsDaily`.`ID`, `CmsDaily`.`RestaurantID`, `Restaurant`.`Name` AS Restaurant, " .
			"`Restaurant`.`Agent`, `CmsDaily`.`Day`, " .
			"`CmsDaily`.`Sale`, `CmsDaily`.`Rate`, `CmsDaily`.`Commission`, " .
			"`CmsDaily`.`Status`, `CmsDaily`.`CloseTime` " .
			"FROM `CmsDaily`, `Restaurant` " .
			"WHERE `CmsDaily`.`RestaurantID` = `Restaurant`.`ID`  " .
			(!isset($_SESSION['admin_is_restaurant']) ? 
				"AND `Restaurant`.`AgentId` IN ({$_SESSION['admin_descendants']}) "
				: "AND `Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' "
			) .
			"" . $condition .
			" ORDER BY `Restaurant`.`AgentID`, `CmsDaily`.`RestaurantID`, " .
			"`CmsDaily`.`Day` DESC, `CmsDaily`.`CloseTime` DESC ";
	
	if ( isset($_REQUEST["page"]) && isset($_REQUEST["start"]) && isset($_REQUEST["limit"]) ) {
		$p = $_REQUEST["page"] + 0;
		$start = $_REQUEST["start"] + 0;
		$limit = $_REQUEST["limit"] + 0;
		$sql .= " LIMIT $start, $limit";
	}
	
	$first = true;
	$rs = $db->query($sql);
	$re = '{"total": ' . $total . ', "commissions": [';
	while ( $row = $rs->fetch_assoc() ) {
		$re .= ($first ? '': ',') . '{"id":'.$row['ID'].', "RestaurantID":'.$row['RestaurantID'].', ' .
				'"Restaurant":"'.$row['Restaurant'].'", "Agent":"'.$row['Agent'].'", ' .
				'"Day":"'.$row['Day'].'", ' .
				'"Sale":"'.(empty($row['Sale']) ? "0.00": $row['Sale']).'", "Rate":"'.($row['Rate']).'%", ' .
				'"Commission":"'.(empty($row['Commission']) ? "0.00": $row['Commission']).'", ' .
				'"Status":"'.$row['Status'].'", "CloseTime":"'.$row['CloseTime'].'"} ';
		$first = false;
	}
	$re .= ']}';
	
	$db->close();
	
	return $re;
}

/**
 * 在计算餐馆的月结的基础上，计算代理的月结
 */
function close_agent_commission() {
	//先计算下属机构的各个餐馆的日结
	close_commission();
	
	//计算一些日子变量
	date_default_timezone_set('PRC');
	$this_month = date('Y-m-01');
//	$this_month_number = date('Ym')+0;
	$today = date('Y-m-d');
	$firstday = date('Y-m-01');
	$thisyear = date('Y');
	$thismonth = date('n');
	$lastmonth = $thismonth=='1' ? '12' :  str_pad($thismonth-1, 2, "0", STR_PAD_LEFT);
	$year_of_lastmonth = $thismonth=='1' ? $thisyear-1 : $thisyear;
	$lastmonth_number = ($year_of_lastmonth.$lastmonth) + 0;
	$lastmonth_firstday = $year_of_lastmonth.'-'.$lastmonth.'-'.'01';
	$lastmonth_lastday = $year_of_lastmonth.'-'.$lastmonth.'-'.days_in_month($year_of_lastmonth, $lastmonth);
	
	//查找未计算完毕的代理
	$db = db_connect();
	$sql = "SELECT `Agent`.`ID`, `Agent`.`AddDate`, MAX(`AgentCmsMonthly`.`Day`) AS LASTDAY " .
			"FROM `Agent` LEFT JOIN `AgentCmsMonthly` " .
			"ON `Agent`.`ID`=`AgentCmsMonthly`.`AgentID` " .
			"WHERE `Agent`.`ID` IN ({$_SESSION['admin_descendants']}) " .
			"AND (`AgentCmsMonthly`.`Day` IS NULL OR `AgentCmsMonthly`.`Day`<=DATE(NOW())) " .
			"AND `Agent`.`Hide`=0 " .
			"GROUP BY `Agent`.`ID` ";
//	echo "查找未计算完毕的代理\nSQL: $sql\n\n";
	$not_close_agent_rs = $db->query($sql);
	while($not_close_agent = $not_close_agent_rs->fetch_assoc()) {
		$not_close_agent_id = $not_close_agent['ID'];
		$startdate = empty($not_close_agent['LASTDAY']) ? $not_close_agent['AddDate'] : $not_close_agent['LASTDAY'];
		
    	$descendants_set = get_agent_descendants_set($not_close_agent_id);
		
		
		//计算并插入上个月以前的数据
		$cur_year = substr($startdate, 0, 4);
		$cur_month = substr($startdate, 5, 2);
		$cur_month_number = $cur_year.$cur_month + 0;
		while($cur_month_number<$lastmonth_number) {
			$cur_month_firstday = $cur_year.'-'.$cur_month.'-01';
			$sql = "INSERT INTO `AgentCmsMonthly`(`AgentID`,`Year`,`Month`,`Day`,
					`Days`,`Sale`,`Commission`,`Status`)
					SELECT {$not_close_agent_id}, {$cur_year},".($cur_month+0).",'{$cur_month_firstday}', 
					'".get_days($cur_year,$cur_month)."',SUM(`CmsMonthly`.`Sale`), SUM(`CmsMonthly`.`Commission`),'未结算'
					FROM `CmsMonthly` , `Restaurant`, `Agent`
					WHERE `CmsMonthly`.`Year`='{$cur_year}' AND `CmsMonthly`.`Month`='".($cur_month+0)."'
					AND `CmsMonthly`.`RestaurantID`=`Restaurant`.`ID`
					AND `Restaurant`.`AgentId` IN ({$descendants_set})
					AND `Agent`.`ID`={$not_close_agent_id}
					AND `Restaurant`.`Hide`=0";
//			echo "计算并插入上个月以前的数据：$cur_year年$cur_month月\nSQL: $sql\n\n";
			$db->query($sql);
			$cur_month = $cur_month+1;
			if($cur_month==13){
				$cur_month = 1;
				$cur_year = $cur_year+1; 
			}
			$cur_month = str_pad($cur_month, 2, "0", STR_PAD_LEFT);
			$cur_month_number = $cur_year.$cur_month + 0;
		}
		
		//更新或插入上个月的数据
		$sql = "SELECT SUM(`CmsMonthly`.`Sale`), SUM(`CmsMonthly`.`Commission`) " .
				"FROM `CmsMonthly`, `Restaurant`, `Agent` " .
				"WHERE `CmsMonthly`.`Year`='{$year_of_lastmonth}' AND `CmsMonthly`.`Month`='".($lastmonth+0)."' " .
				"AND `CmsMonthly`.`RestaurantID`=`Restaurant`.`ID` " .
				"AND `Restaurant`.`AgentId` IN ({$descendants_set}) " .
				"AND `Agent`.`ID`={$not_close_agent_id} " .
				"AND `Restaurant`.`Hide`=0 ";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total_sale = $total_row[0] + 0;
		$total_cms = $total_row[1] + 0;
		
		$sql = "SELECT `ID` FROM `AgentCmsMonthly` " .
				"WHERE `Year`='{$year_of_lastmonth}' AND `Month`='".($lastmonth+0)."' " .
				"AND `AgentID`={$not_close_agent_id}";
//		echo "查找上个月的数据\nSQL: $sql\n\n";
		$yesterday_rs = $db->query($sql);
		if($yesterday_row = $yesterday_rs->fetch_row()) {
			$sql = "UPDATE `AgentCmsMonthly` SET `Sale`='{$total_sale}', `Commission`='{$total_cms}'" .
					"WHERE `ID`='{$yesterday_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `AgentCmsMonthly`(`AgentID`,`Year`,`Month`,`Day`,`Days`,`Sale`,`Commission`,`Status`) " .
					"VALUES('{$not_close_agent_id}','{$year_of_lastmonth}','".($lastmonth+0)."','{$lastmonth_firstday}'," .
					"'".get_days($year_of_lastmonth, $lastmonth+0)."','{$total_sale}','{$total_cms}','未结算') ";
		}
//		echo "更新或插入上个月的数据\nSQL: $sql\n\n";
		$db->query($sql);
		
		
		//更新或插入这个月的数据
		$today = date('Y-m-d');
		$sql = "SELECT SUM(`CmsMonthly`.`Sale`), SUM(`CmsMonthly`.`Commission`) " .
				"FROM `CmsMonthly`, `Restaurant`, `Agent`  " .
				"WHERE `CmsMonthly`.`Year`='{$thisyear}' AND `CmsMonthly`.`Month`='{$thismonth}' " .
				"AND `Restaurant`.`AgentId` IN ({$descendants_set}) " .
				"AND `CmsMonthly`.`RestaurantID`=`Restaurant`.`ID` " .
				"AND `Agent`.`ID`={$not_close_agent_id} " .
				"AND `Restaurant`.`Hide`=0 ";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total_sale = $total_row[0] + 0;
		$total_cms = $total_row[1] + 0;
		
		$sql = "SELECT `ID` FROM `AgentCmsMonthly` " .
				"WHERE `Year`='{$thisyear}' AND `Month`='{$thismonth}'  " .
				"AND `AgentID`={$not_close_agent_id}";
//		echo "查找这个月的数据\nSQL: $sql\n\n";
		$today_rs = $db->query($sql);
		if($today_row = $today_rs->fetch_row()) {
			$sql = "UPDATE `AgentCmsMonthly` SET `Sale`='{$total_sale}', `Commission`='{$total_cms}'" .
					"WHERE `ID`='{$today_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `AgentCmsMonthly`(`AgentID`,`Year`,`Month`,`Day`,`Days`,`Sale`,`Commission`,`Status`) " .
					"VALUES('{$not_close_agent_id}','{$thisyear}','{$thismonth}','{$firstday}'," .
					"'".get_days($thisyear, $thismonth)."','{$total_sale}','{$total_cms}','未结算') ";
		}
//		echo "更新或插入这个月的数据\nSQL: $sql\n\n";
		$db->query($sql);
	}
	$db->close();
}


/**
 * 计算月结
 * 根据$_SESSION计算下属机构的各餐馆的月结
 */
function close_commission() {
	//计算一些日子变量
	date_default_timezone_set('PRC');
	$this_month = date('Y-m-01');
//	$this_month_number = date('Ym')+0;
	$today = date('Y-m-d');
	$firstday = date('Y-m-01');
	$thisyear = date('Y');
	$thismonth = date('n');
	$lastmonth = $thismonth=='1' ? '12' :  str_pad($thismonth-1, 2, "0", STR_PAD_LEFT);
	$year_of_lastmonth = $thismonth=='1' ? $thisyear-1 : $thisyear;
	$lastmonth_number = ($year_of_lastmonth.$lastmonth) + 0;
	$lastmonth_firstday = $year_of_lastmonth.'-'.$lastmonth.'-'.'01';
	$lastmonth_lastday = $year_of_lastmonth.'-'.$lastmonth.'-'.days_in_month($year_of_lastmonth, $lastmonth);
	
	$db = db_connect();
	$sql = "SELECT `Restaurant`.`ID`, `Restaurant`.`AddTime`, " .
			"`Restaurant`.`Commission`, MAX(`CmsMonthly`.`Day`) AS LASTDAY " .
			"FROM `Restaurant` LEFT JOIN `CmsMonthly` " .
			"ON `Restaurant`.`ID`=`CmsMonthly`.`RestaurantID` " .
			"WHERE " .
			(!isset($_SESSION['admin_is_restaurant']) ? 
				"`Restaurant`.`AgentId` IN ({$_SESSION['admin_descendants']}) "
				: "`Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' "
			) .
			"AND (`CmsMonthly`.`Day` IS NULL OR `CmsMonthly`.`Day`<=DATE(NOW())) " .
			"AND `Restaurant`.`Hide`=0 " .
			"GROUP BY  `Restaurant`.`ID` ";
//	echo "SQL:[$sql]\n\n";
	$rs = $db->query($sql);
	while($row = $rs->fetch_assoc()){
		$startdate = empty($row['LASTDAY']) ? $row['AddTime'] : $row['LASTDAY'];
		$rate = $row['Commission'] + 0;
		$restaurantid = $row['ID'];
		
		//插入上个月之前的数据
		$cur_year = substr($startdate, 0, 4);
		$cur_month = substr($startdate, 5, 2);
		$cur_month_number = $cur_year.$cur_month + 0;
		while($cur_month_number<$lastmonth_number) {
			$cur_month_firstday = $cur_year.'-'.$cur_month.'-01';
			$sql = "INSERT INTO `CmsMonthly`(`RestaurantID`,`Year`,`Month`,`Day`,
					`Days`,`Sale`,`Rate`,`Commission`,`Status`)
					SELECT {$restaurantid}, {$cur_year},{$cur_month},'{$cur_month_firstday}', 
					'".get_days($cur_year,$cur_month)."',SUM(`Total`), {$rate}, SUM(`Total`)*{$rate}/100,'未结算'
					FROM `Order` 
					WHERE DATE_FORMAT(`CreateTime`, '%Y-%m')=".($cur_year.'-'.$cur_month)."
					AND `RestaurantID`={$restaurantid}
					";
			$db->query($sql);
			$cur_month = $cur_month+1;
			if($cur_month==13){
				$cur_month = 1;
				$cur_year = $cur_year+1; 
			}
			$cur_month = str_pad($cur_month, 2, "0", STR_PAD_LEFT);
			$cur_month_number = $cur_year.$cur_month + 0;
		}
		
		//插入或更新上个月的数据
		$sql = "SELECT SUM(`Total`) FROM `Order` " .
				"WHERE `CreateTime`<='{$lastmonth_firstday} 23:59:59' AND `CreateTime`>='{$lastmonth_firstday} 00:00:00' " .
				"AND `RestaurantID`={$restaurantid}";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total = $total_row[0] + 0;
		$commission = $total * $rate / 100;
		
		$sql = "SELECT `ID` FROM `CmsMonthly` " .
				"WHERE `Year`='{$year_of_lastmonth}' AND `Month`='".($lastmonth+0)."' " .
				"AND `RestaurantID`={$restaurantid}";
		$lastmonth_rs = $db->query($sql);
		if($lastmonth_row = $lastmonth_rs->fetch_row()) {
			$sql = "UPDATE `CmsMonthly` SET `Sale`='{$total}', `Commission`='{$commission}'" .
					"WHERE `ID`='{$lastmonth_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `CmsMonthly`(`RestaurantID`,`Year`,`Month`,`Day`," .
					"`Days`,`Sale`,`Rate`,`Commission`,`Status`) " .
					"VALUES('{$restaurantid}','{$year_of_lastmonth}','".($lastmonth+0)."','{$lastmonth_firstday}'," .
					"'".get_days($year_of_lastmonth, $lastmonth+0)."','{$total}','{$rate}','{$commission}','未结算') ";
		}
		$db->query($sql);
		
		
		//插入或更新本月的数据
		$sql = "SELECT SUM(`Total`) FROM `Order` " .
				"WHERE `CreateTime`<='{$today} 23:59:59' AND `CreateTime`>='{$firstday} 00:00:00' " .
				"AND `RestaurantID`={$restaurantid}";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total = $total_row[0] + 0;
		$commission = $total * $rate / 100;
		
		$sql = "SELECT `ID` FROM `CmsMonthly` " .
				"WHERE `Year`='{$thisyear}' AND `Month`='{$thismonth}' " .
				"AND `RestaurantID`={$restaurantid}";
		$thismonth_rs = $db->query($sql);
		if($thismonth_row = $thismonth_rs->fetch_row()) {
			$sql = "UPDATE `CmsMonthly` SET `Sale`='{$total}', `Commission`='{$commission}'" .
					"WHERE `ID`='{$thismonth_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `CmsMonthly`(`RestaurantID`,`Year`,`Month`,`Day`," .
					"`Days`,`Sale`,`Rate`,`Commission`,`Status`) " .
					"VALUES('{$restaurantid}','{$thisyear}','{$thismonth}','{$firstday}'," .
					"'".get_days($thisyear, $thismonth)."','{$total}','{$rate}','{$commission}','未结算') ";
		}
		$db->query($sql);
	}
	$db->close();
}


/**
 * 在计算餐馆的日结的基础上，计算代理的日结
 */
function close_agent_daily_commission() {
	date_default_timezone_set('PRC');
	//先计算下属机构的各个餐馆的日结
	close_daily_commission();
	
	$db = db_connect();
	$sql = "SELECT `Agent`.`ID`, `Agent`.`AddDate`, MAX(`AgentCmsDaily`.`Day`) AS LASTDAY " .
			"FROM `Agent` LEFT JOIN `AgentCmsDaily` " .
			"ON `Agent`.`ID`=`AgentCmsDaily`.`AgentID` " .
			"WHERE `Agent`.`ID` IN ({$_SESSION['admin_descendants']}) " .
			"AND (`AgentCmsDaily`.`Day` IS NULL OR `AgentCmsDaily`.`Day`<=DATE(NOW())) " .
			"AND `Agent`.`Hide`=0 " .
			"GROUP BY `Agent`.`ID` ";
	$not_close_agent_rs = $db->query($sql);
	while($not_close_agent = $not_close_agent_rs->fetch_assoc()) {
		$not_close_agent_id = $not_close_agent['ID'];
		$startdate = empty($not_close_agent['LASTDAY']) ? $not_close_agent['AddDate'] : $not_close_agent['LASTDAY'];
		
    	$descendants_set = get_agent_descendants_set($not_close_agent_id);
		
		
		//计算并插入昨天以前的数据
		$df = floor(datediff($startdate));
		for($i=0; $i<($df-1); $i++) {
			$sql = "INSERT INTO `AgentCmsDaily`(`AgentID`,`Day`,`Sale`,`Rate`,`Commission`,`Status`,`CloseTime`)
					SELECT {$not_close_agent_id}, DATE_ADD('{$startdate}',INTERVAL {$i} DAY), 
					SUM(`CmsDaily`.`Sale`), NULL, SUM(`CmsDaily`.`Commission`),'未结算',NULL
					FROM `CmsDaily` , `Restaurant`, `Agent`
					WHERE DATE(`CmsDaily`.`Day`)=DATE_ADD('{$startdate}',INTERVAL {$i} DAY)
					AND `Restaurant`.`AgentId` IN ({$descendants_set})
					AND `CmsDaily`.`RestaurantID`=`Restaurant`.`ID`
					AND `Agent`.`ID`={$not_close_agent_id}
					AND `Restaurant`.`Hide`=0 ";					
			$db->query($sql);
		}
		
		//更新或插入昨天的数据
		$yesterday = date('Y-m-d', time()-24*60*60);
		$sql = "SELECT SUM(`CmsDaily`.`Sale`), SUM(`CmsDaily`.`Commission`) " .
				"FROM `CmsDaily`, `Restaurant`, `Agent` " .
				"WHERE `CmsDaily`.`Day`='{$yesterday}' " .
				"AND `Restaurant`.`AgentId` IN ({$descendants_set}) " .
				"AND `CmsDaily`.`RestaurantID`=`Restaurant`.`ID` " .
				"AND `Agent`.`ID`={$not_close_agent_id} " .
				"AND `Restaurant`.`Hide`=0";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total_sale = $total_row[0] + 0;
		$total_cms = $total_row[1] + 0;
		
		$sql = "SELECT `ID` FROM `AgentCmsDaily` " .
				"WHERE `Day`='{$yesterday}' AND `AgentID`={$not_close_agent_id}";
		$yesterday_rs = $db->query($sql);
		if($yesterday_row = $yesterday_rs->fetch_row()) {
			$sql = "UPDATE `AgentCmsDaily` SET `Sale`='{$total_sale}', `Commission`='{$total_cms}'" .
					"WHERE `ID`='{$yesterday_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `AgentCmsDaily`(`AgentID`,`Day`,`Sale`,`Commission`,`Status`) " .
					"VALUES('{$not_close_agent_id}','{$yesterday}','{$total_sale}','{$total_cms}','未结算') ";
		}
		$db->query($sql);
		
		
		//更新或插入今天的数据
		$today = date('Y-m-d');
		$sql = "SELECT SUM(`CmsDaily`.`Sale`), SUM(`CmsDaily`.`Commission`) " .
				"FROM `CmsDaily`, `Restaurant`, `Agent`  " .
				"WHERE `CmsDaily`.`Day`='{$today}' " .
				"AND `Restaurant`.`AgentId` IN ({$descendants_set}) " .
				"AND `CmsDaily`.`RestaurantID`=`Restaurant`.`ID` " .
				"AND `Agent`.`ID`={$not_close_agent_id} " .
				"AND `Restaurant`.`Hide`=0 ";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total_sale = $total_row[0] + 0;
		$total_cms = $total_row[1] + 0;
		
		$sql = "SELECT `ID` FROM `AgentCmsDaily` " .
				"WHERE `Day`='{$today}' AND `AgentID`={$not_close_agent_id}";
		$today_rs = $db->query($sql);
		if($today_row = $today_rs->fetch_row()) {
			$sql = "UPDATE `AgentCmsDaily` SET `Sale`='{$total_sale}', `Commission`='{$total_cms}'" .
					"WHERE `ID`='{$today_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `AgentCmsDaily`(`AgentID`,`Day`,`Sale`,`Commission`,`Status`) " .
					"VALUES('{$not_close_agent_id}','{$today}','{$total_sale}','{$total_cms}','未结算') ";
		}
		$db->query($sql);
	}
	$db->close();
}

/**
 * 计算日结
 * 根据$_SESSION计算下属机构的各餐馆的日结
 */
function close_daily_commission() {
	date_default_timezone_set('PRC');
	$db = db_connect();
	$sql = "SELECT `Restaurant`.`ID`, `Restaurant`.`AddTime`, " .
			"`Restaurant`.`Commission`, MAX(`CmsDaily`.`Day`) AS LASTDAY " .
			"FROM `Restaurant` LEFT JOIN `CmsDaily` " .
			"ON `Restaurant`.`ID`=`CmsDaily`.`RestaurantID` " .
			"WHERE " .
			(!isset($_SESSION['admin_is_restaurant']) ? 
				"`Restaurant`.`AgentId` IN ({$_SESSION['admin_descendants']}) "
				: "`Restaurant`.`ID`='{$_SESSION['admin_restaurant_id']}' "
			) .
			"AND (`CmsDaily`.`Day` IS NULL OR `CmsDaily`.`Day`<=DATE(NOW())) " .
			"AND `Restaurant`.`Hide`=0 " .
			"GROUP BY  `Restaurant`.`ID` ";
//	echo "\nSQL:[$sql]\n\n";
	$rs = $db->query($sql);
	while($row = $rs->fetch_assoc()){
		$startdate = empty($row['LASTDAY']) ? $row['AddTime'] : $row['LASTDAY'];
		$rate = $row['Commission'] + 0;
		$restaurantid = $row['ID'];
		
		//计算并插入昨天以前的数据
		$df = floor(datediff($startdate));
		for($i=0; $i<($df-1); $i++) {
			$sql = "INSERT INTO `CmsDaily`(`ID`,`RestaurantID`,`Day`,`Sale`,`Rate`,`Commission`,`Status`,`CloseTime`)
					SELECT NULL,{$restaurantid}, DATE_ADD('{$startdate}',INTERVAL {$i} DAY), 
					SUM(`Total`), {$rate}, SUM(`Total`)*{$rate}/100,'未结算',NULL
					FROM `Order` 
					WHERE DATE(`CreateTime`)=DATE_ADD('{$startdate}',INTERVAL {$i} DAY)
					AND `RestaurantID`={$restaurantid}
					";
			$db->query($sql);
		}
		
		//更新或插入昨天的数据
		$yesterday = date('Y-m-d', time()-24*60*60);
		$sql = "SELECT SUM(`Total`) FROM `Order` " .
				"WHERE DATE(`CreateTime`)='{$yesterday}' " .
				"AND `RestaurantID`={$restaurantid}";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total = $total_row[0] + 0;
		$commission = $total * $rate / 100;
		
		$sql = "SELECT `ID` FROM `CmsDaily` " .
				"WHERE `Day`='{$yesterday}' AND `RestaurantID`={$restaurantid}";
		$yesterday_rs = $db->query($sql);
		if($yesterday_row = $yesterday_rs->fetch_row()) {
			$sql = "UPDATE `CmsDaily` SET `Sale`='{$total}', `Commission`='{$commission}'" .
					"WHERE `ID`='{$yesterday_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `CmsDaily`(`RestaurantID`,`Day`,`Sale`,`Rate`,`Commission`,`Status`) " .
					"VALUES('{$restaurantid}','{$yesterday}','{$total}','{$rate}','{$commission}','未结算') ";
		}
		$db->query($sql);
		
		
		//更新或插入今天的数据
		$today = date('Y-m-d');
		$sql = "SELECT SUM(`Total`) FROM `Order` " .
				"WHERE DATE(`CreateTime`)='{$today}' " .
				"AND `RestaurantID`={$restaurantid}";
		$total_rs = $db->query($sql);
		$total_row =  $total_rs->fetch_row();
		$total = $total_row[0] + 0;
		$commission = $total * $rate / 100;
		
		$sql = "SELECT `ID` FROM `CmsDaily` " .
				"WHERE `Day`='{$today}' AND `RestaurantID`={$restaurantid}";
		$today_rs = $db->query($sql);
		if($today_row = $today_rs->fetch_row()) {
			$sql = "UPDATE `CmsDaily` SET `Sale`='{$total}', `Commission`='{$commission}'" .
					"WHERE `ID`='{$today_row[0]}'";
		}
		else {
			$sql = "INSERT INTO `CmsDaily`(`RestaurantID`,`Day`,`Sale`,`Rate`,`Commission`,`Status`) " .
					"VALUES('{$restaurantid}','{$today}','{$total}','{$rate}','{$commission}','未结算') ";
		}
		$db->query($sql);
	}
	$db->close();
}


function get_settings_json() {
	if(!check_privilege('系统设置')){
		agent_log("系统设置", "获取系统设置失败：没有系统设置的权限。");
		die( error_json ( "获取系统设置失败：没有系统设置的权限。" ) );
	}
	
	$re = "";
	$db = db_connect();
	$sql = "SELECT `Property`, `Value` FROM `Setting`;";
	$rs = $db->query($sql);
	$settings = array();
	while($setting = $rs->fetch_assoc()){
		$settings[] = '"'.$setting['Property'].'":"'.$setting['Value'].'"';
	}
	$re = '{"settings": [{' .implode(",", $settings). '}]}';
	$db->close();
	return $re;
}

function save_settings() {
	if(!check_privilege('系统设置')){
		agent_log("系统设置", "失败：没有系统设置的权限。");
		die( error_json ( "失败：没有系统设置的权限。" ) );
	}
	
	$site_name = addslashes(trim($_REQUEST['SITE_NAME']));
	$site_master_email = addslashes(trim($_REQUEST['SITE_MASTER_EMAIL']));
	$time_for_long_confirm = addslashes(trim($_REQUEST['TIME_FOR_LONG_CONFIRM'])) + 0;
	$time_for_long_noreceive = addslashes(trim($_REQUEST['TIME_FOR_LONG_NORECEIVE'])) + 0;
	
	if(empty($site_name)) {
		agent_log("系统设置", "失败：网站名称为空。");
		die( error_json ( "网站名称为空" ) );
	}
	if(empty($site_master_email)) {
		agent_log("系统设置", "失败：网站Email为空。");
		die( error_json ( "网站Email为空" ) );
	}
	if(!is_email_well_form($site_master_email)) {
		agent_log("系统设置", "失败：网站Email不是有效的email：" . $site_master_email);
		die( error_json ( "网站Email不是有效的email" ) );
	}
	if(empty($time_for_long_confirm)) {
		agent_log("系统设置", "失败：验证等待时间为空或为0。");
		die( error_json ( "验证等待时间为空或为0" ) );
	}
	if(empty($time_for_long_noreceive)) {
		agent_log("系统设置", "失败：收餐等待时间为空或为0。");
		die( error_json ( "收餐等待时间为空或为0" ) );
	}
	
	$db = db_connect();
	
	$sql = "UPDATE `Setting` SET `Value`= '{$site_name}' WHERE `Property`='SITE_NAME' ;";
	$db->query($sql);
	if($db->affected_rows) agent_log("系统设置", "成功：修改网站名称为：" . $site_name);
	
	$sql = "UPDATE `Setting` SET `Value`= '{$site_master_email}' WHERE `Property`='SITE_MASTER_EMAIL' ;";
	$db->query($sql);
	if($db->affected_rows) agent_log("系统设置", "成功：修改网站Email为：" . $site_master_email);
	
	$sql = "UPDATE `Setting` SET `Value`= '{$time_for_long_confirm}' WHERE `Property`='TIME_FOR_LONG_CONFIRM' ;";
	$db->query($sql);
	if($db->affected_rows) agent_log("系统设置", "成功：修改验证等待时间为：" . $time_for_long_confirm . "分钟");
	
	$sql = "UPDATE `Setting` SET `Value`= '{$time_for_long_noreceive}' WHERE `Property`='TIME_FOR_LONG_NORECEIVE' ;";
	$db->query($sql);
	if($db->affected_rows) agent_log("系统设置", "成功：修改收餐等待时间为：" . $time_for_long_noreceive. "分钟");
	
	$db->close();
	return success_json_no_data();
	
}

function get_page_settings_json() {
	if(!check_privilege('网站设置')){
		agent_log("主页设置", "获取网站设置失败：没有网站设置的权限。");
		die( error_json ( "获取网站设置失败：没有网站设置的权限。" ) );
	}
	
	$re = "";
	$db = db_connect();
	$sql = "SELECT * FROM `PageSetting`;";
	$rs = $db->query($sql);
	$settings = array();
	if($setting = $rs->fetch_assoc()){
		$re = json_encode($setting);
	}
	$re = '{"settings": ['.$re.']}';
	$db->close();
	return $re;
}

function page_settings_save() {
	if(!check_privilege('网站设置')){
		agent_log("主页设置", "保存网站设置失败：没有网站设置的权限。");
		die( error_json ( "保存网站设置失败：没有网站设置的权限。" ) );
	}
	
	if(empty($_POST)) return;
	
	$settings = array();
	foreach ( $_POST as $key => $value ) {
		$settings[] = empty($value) ? " `{$key}`=NULL " : " `{$key}`='$value' ";
	}
	
	$db = db_connect();
	$sql = "UPDATE `PageSetting` SET ".implode(",", $settings).";";
	$db->query($sql);
	
	$db->close();
	return success_json_no_data();
}

////////////////////以下为私有函数/////////////////////

/**
 * 获取某个代理的下级代理
 * @param string/int $agent_id 代理的id
 * @param boolean $direct 是否只取直接下级，默认：false
 * @param boolean $self_included 是否包括自己，true：包括自己，否则不包括自己，默认：true
 */
function get_agent_descendants_set ($agent_id, $direct=false, $self_included=true) {
	$db = db_connect();
	$sql = "SELECT `ID` FROM `Agent` " .
    			"WHERE (1=0 " .
    			($self_included ?  "OR `ID`='{$agent_id}' " : "" ) .
    			($direct ? "OR `HeadID`='{$agent_id}' " :
	    			("OR `Ancestors`='{$agent_id}' " .
	    			"OR `Ancestors` LIKE '{$agent_id},%' " .
	    			"OR `Ancestors` LIKE '%,{$agent_id}' " .
	    			"OR `Ancestors` LIKE '%,{$agent_id},%' ")) .
    			") AND `Hide`=0 " .
    			"ORDER BY `Level` ASC, `HeadID` ASC, `ID` ASC ";
	$descendants_rs = $db->query($sql);
	$descendants = array();
	while($d = $descendants_rs->fetch_assoc()) {
		$descendants[] =$d['ID']; 
	}
	$descendants_set = implode(",", $descendants);
	$db->close();
	return $descendants_set;
}

function get_days($year, $month) {
	return $month."月1日-".$month."月".days_in_month($year, $month).'日';
}

function days_in_month($year, $month) {
	date_default_timezone_set('PRC');
	return date('t', strtotime($year . '-' . $month . '-01'));
}

/**
 * date2 - date1的时间差
 */
function datediff($date1, $date2="", $unit = "") {
	date_default_timezone_set('PRC');
	switch ($unit) {
		case 's':
			$dividend = 1;
			break;
		case 'i':
			$dividend = 60;
			break;
		case 'h':
			$dividend = 3600;
			break;
		case 'd':
			$dividend = 86400;
			break;
		default:
			$dividend = 86400;
	}
	$time1 = strtotime($date1);
	$time2 = empty($date2) ? time() : strtotime($date2);
	if ($time1 && $time2)
		return (float)($time2 - $time1) / $dividend;
	
	return false;
}

/**
 * 处理长时间没有响应的订单
 */
function process_long_time() {
	check_login();
	$db = db_connect();
	
	if(//!isset($_SESSION['admin_setting_TIME_FOR_LONG_RESPONSE']) ||
	!isset($_SESSION['admin_setting_TIME_FOR_LONG_CONFIRM']) ||
	!isset($_SESSION['admin_setting_TIME_FOR_LONG_NORECEIVE']) ) {
		read_setting();
	}
	
	$sql = "SELECT `ID` FROM `Order` WHERE (`Status`='等待手机验证' OR `Status`='创建') AND " .
			"UNIX_TIMESTAMP('".get_datetime()."')-UNIX_TIMESTAMP(`CreateTime`)>".($_SESSION['admin_setting_TIME_FOR_LONG_CONFIRM']+0)."*60 " . //
			"AND `CTime` IS NULL ";
	$rs = $db->query($sql);
	$ids = array();
	while($row = $rs->fetch_row()) {
		array_push($ids, $row[0]);
	}
	
	if(!empty($ids)){
		$idset = implode(",", $ids);
		$sql = "UPDATE `Order` SET `Status`='自动删除',`EndTime`='".get_datetime()."' ,`LastUpdate`='".get_datetime()."'  WHERE `ID` IN (".$idset.")";
		$db->query($sql);
	}
	foreach( $ids as $id ) {
		order_process($id, 9);
	}
	
//	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='等待餐馆确认' AND " .
//			"UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(`CTime`)>".($_SESSION['admin_setting_TIME_FOR_LONG_RESPONSE']+0)."*60 " . //
//			"AND  `RTime` IS NULL " .
//			"AND `CustomID`='{$_SESSION['customid']}'";
//	$rs = $db->query($sql);
//	$ids = array();
//	while($row = $rs->fetch_row()) {
//		array_push($ids, $row[0]);
//	}
//	
//	if(!empty($ids)){
//		$idset = implode(",", $ids);
//		$sql = "UPDATE `Order` SET `Status`='无法完成' WHERE `ID` IN (".$idset.")";
//		$db->query($sql);
//	}
//	foreach( $ids as $id ) {
//		order_process($id, 10);
//		custom_log('取消订单', '订单由于餐馆长时间没有确认而自动取消：订单ID：'.$id);
//	}
//
	//处理长时间没有确认送餐的“正在送餐”订单
	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='正在送餐' AND ". //"`COperation`='确认' AND " .
			"UNIX_TIMESTAMP('".get_datetime()."')-UNIX_TIMESTAMP(`CTime`)>".($_SESSION['admin_setting_TIME_FOR_LONG_NORECEIVE']+0)."*60 "; //正在送餐的订单，如果超过TIME_FOR_LONG_NORECEIVE分钟，则自动转为成功结束;
	$rs = $db->query($sql);
	$ids = array();
	while($row = $rs->fetch_row()) {
		array_push($ids, $row[0]);
	}
	
	if(!empty($ids)){
		$idset = implode(",", $ids);
		$sql = "UPDATE `Order` SET `Status`='成功结束',`EndTime`='".get_datetime()."',`LastUpdate`='".get_datetime()."'   WHERE `ID` IN (".$idset.")";
		$db->query($sql);
	}
	
	foreach( $ids as $id ) {
		order_process($id, 12);
	}
	
	//处理长时间“自动删除”订单，将其变成已取消
	$sql = "SELECT `ID` FROM `Order` WHERE `Status`='自动删除' AND " .
			"UNIX_TIMESTAMP('".get_datetime()."')-UNIX_TIMESTAMP(`LastUpdate`)>24*60*60 " . //自动删除的订单，如果超过24小时，则自动转为已取消
			"AND  `RTime` IS NULL ";
	$rs = $db->query($sql);
	$ids = array();
	while($row = $rs->fetch_row()) {
		array_push($ids, $row[0]);
	}
	
	if(!empty($ids)){
		$idset = implode(",", $ids);
		$sql = "UPDATE `Order` SET `Status`='已取消',`EndTime`='".get_datetime()."' ,`LastUpdate`='".get_datetime()."'  WHERE `ID` IN (".$idset.")";
		$db->query($sql);
	}
	foreach( $ids as $id ) {
		order_process($id, 8, "自动删除的订单由于过期超过24小时，自动转为已取消状态。");
	}
	
	$db->close();
}


function read_setting() {
	$db = db_connect();
	$sql = "SELECT `Property`, `Value` FROM `Setting`;";
	$rs = $db->query($sql);
	while($setting = $rs->fetch_assoc()){
		$_SESSION['admin_setting_' . $setting['Property']] = $setting['Value'];
	}
	$db->close();
}

function order_process($orderid, $type, $text = null) {
	if($type>12 || $type<1) return;
	$activity = array(
		"",
		"订单创建",
		"订单确认",
		"已通知餐馆",
		"餐馆已确认",
		"餐馆正在处理您的订单…",
		"已收到餐",
		"成功结束",
		"已取消",
		"（自动）很抱歉，由于长时间未验证手机号码，本单已自动删除",
		"（自动）很抱歉，由于餐馆长时间未确认订单，本单已自动删除",
		"很抱歉，由于餐馆无法处理您的订餐，本单已自动删除",
		"（自动）由于送餐后长时间没有确认收到送餐，本单已自动成功结束"
	);
	$at = $activity[$type] . (empty($text) ? "" : "：".$text);
	$db = db_connect();
	$sql = "INSERT INTO `OrderProcess`(`OrderID`, `Type`, `Activity`,`Time`) " .
			"VALUES('{$orderid}', '{$type}', '{$at}', '".get_datetime()."')";
	$db->query($sql);
	$db->close();
}

/**
 * 发送短信，并将有关结果写入数据库中
 * @return mix 如果根本就没有发送，则返回false，如果已经发送，但是发送失败，则返回失败原因，否则返回短信的数据库id号的数组
 */
function send_sms($receivers,$content, $customIds=null){
	if(!is_array($receivers)) $receivers = array($receivers);
	if(!empty($customIds) && !is_array($customIds)) $customIds = array($customIds);
	
	if(!empty($customIds) && count($customIds)!=count($receivers)) return false;
	
	if(!isset($content)) return false;
	
	if(empty($_SESSION['session_Setting_SITE_NAME'])) {
		read_setting();
	}
	$content .= "【".$_SESSION['session_Setting_SITE_NAME']."】";
		
	//创建数据库记录
	$db = db_connect();
	$ids = array();
	$delete_indexes = array();
	foreach($receivers as $index => $receiver) {
		if(is_mobile_number($receiver)) {
			$sql = "INSERT INTO `Sms`(`Receiver`, `Content`, `CustomID`, `SentTime`) " .
					"VALUES('{$receiver}', '{$content}', " .
					((empty($customIds) || empty($customIds[$index])) ? "NULL" : "'{$customIds[$index]}'") .
					", '".get_datetime()."')";
			$db->query($sql);
			if($db->result!==false){
				array_push($ids, $db->insert_id());
			}
			else { //插入数据库失败，将有关记录删除
				array_unshift($delete_indexes, $index);
			}
		}
		else {//不是有效的手机号码，将有关记录删除
			array_unshift($delete_indexes, $index);
		}
	}
	
	foreach($delete_indexes as $delete_index) {
		array_splice($receivers, $delete_index, 1);
		if(!empty($customIds)){
			array_splice($customIds, $delete_index, 1);
		}
	}
	
	if(empty($receivers)){
		$db->close();
		return false;
	}
	
	if(!isset($_SESSION['admin_setting_SMS_platform'])) {
		$sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) {
			$_SESSION['admin_setting_'.$row['Property']] = $row['Value'];
		}
	}
	$db->close();
	
	if($_SESSION['admin_setting_SMS_platform']=='企信') {
		return send_qixin_sms($receivers, $content, $ids);
	}
	else {
		return send_emay_sms($receivers, $content, $ids);
	}
}

function send_emay_sms($receivers, $content, $ids) {
	$db = db_connect();
	if(!isset($_SESSION['admin_setting_SMS_EMY_softwareSerialNo'])
			|| !isset($_SESSION['admin_setting_SMS_EMY_password'])
			|| !isset($_SESSION['admin_setting_SMS_EMY_sessionkey']) )
	{
		$sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) {
			$_SESSION['admin_setting_'.$row['Property']] = $row['Value'];
		}
	}
	
	$client = get_emay_client();
	$statusCode = $client->sendSMS($receivers, $content);
	
	if ($statusCode!=null && $statusCode=="0"){
		//更新数据库中的有关记录
		$remain = $client->getBalance();
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=1, " .
					"`ReturnStatus`='{$statusCode}', `Result`='发送成功', " .
					"`ReferenceID`='', `Status`='已发送',`Remain`='{$remain}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $ids;
	}
	else {
		$msg = get_emay_error($statusCode);
		$remain = $client->getBalance();
		//更新数据库中的有关记录
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='{$statusCode}', `Result`='{$msg}', " .
					"`ReferenceID`='', `Status`='失败',`Remain`='{$remain}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $msg;
	}
}

function get_emay_error($code) {
	switch($code + 0) {
		case 0	: return "";
		case 17	: return "发送信息失败";
		case 18	: return "发送定时信息失败";
		case 101: return "客户端网络故障";
		case 305: return "服务器端返回错误，错误的返回值（返回值不是数字字符串）";
		case 307: return "目标电话号码不符合规则，电话号码必须是以0、1开头";
		case 997: return "平台返回找不到超时的短信，该信息是否成功无法确定";
		case 998: return "由于客户端网络问题导致信息发送超时，该信息是否成功下发无法确定";
		default	: return "未知错误，错误号：" . $code;
	}
}

function send_qixin_sms($receivers, $content, $ids) {
	$db = db_connect();
	if(!isset($_SESSION['admin_setting_SMS_url'])
			|| !isset($_SESSION['admin_setting_SMS_userid'])
			|| !isset($_SESSION['admin_setting_SMS_account'])
			|| !isset($_SESSION['admin_setting_SMS_password']) )
	{
		$sql = "SELECT `Property`,`Value` FROM `Setting` WHERE `Property` LIKE 'SMS_%'";
		$rs = $db->query($sql);
		while( $row = $rs->fetch_assoc() ) {
			$_SESSION['admin_setting_'.$row['Property']] = $row['Value'];
		}
	}
	
	$strReceivers = implode(",", $receivers);
	$url=$_SESSION['admin_setting_SMS_url'];
	$id = urlencode($_SESSION['admin_setting_SMS_userid']);
	$account = urlencode($_SESSION['admin_setting_SMS_account']);
	$pwd = urlencode($_SESSION['admin_setting_SMS_password']);
	$to = urlencode($strReceivers);
	$postFields = "action=send&userid=".$id."&account=".$account."&password=".$pwd."&mobile=".$strReceivers."&content=".$content."&sendTime=";
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
	curl_setopt($ch, CURLOPT_TIMEOUT, 29*60);
	
	//	//proxy for test
	//	curl_setopt($ch, CURLOPT_PROXYTYPE, 'HTTP');
	//	curl_setopt($ch, CURLOPT_PROXY, '174.139.255.194');
	//	curl_setopt($ch, CURLOPT_PROXYPORT, 80);
	
	$response = curl_exec($ch);
	curl_close($ch);
	
	if(empty($response) || curl_errno($ch)!=0) {
		//更新数据库中的有关记录
		$msg = curl_error($ch);
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='连接失败', `Result`='连接失败：{$msg}', " .
					"`ReferenceID`='', `Status`='失败',`Remain`='' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $msg;
	}
	
	//分析返回结果
	$result = @simplexml_load_string($response);
	
	if($result === FALSE){//返回结果不能分析成为XML文件
		//更新数据库中的有关记录
		$msg = "短信平台的返回不是一个有效xml文件。";
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='短信平台返回格式有误。', `Result`='".substr($response,0,200)."', " .
					"`ReferenceID`='', `Status`='失败',`Remain`='' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$db->close();
		return $msg;
	}
	
	$re = null;
	if($result->returnstatus=='Success'){//发送成功
		//更新数据库中的有关记录
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=1, " .
					"`ReturnStatus`='{$result->returnstatus}', `Result`='发送成功', " .
					"`ReferenceID`='{$result->taskID}', `Status`='已发送',`Remain`='{$result->remainpoint}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$re = $ids;
	}
	else {
		$msg = $result->message;
		//更新数据库中的有关记录
		foreach($ids as $id){
			$sql = "UPDATE `Sms` SET `RecvTime`='".get_datetime()."', `Success`=0, " .
					"`ReturnStatus`='{$result->returnstatus}', `Result`='{$msg}', " .
					"`ReferenceID`='{$result->taskID}', `Status`='失败',`Remain`='{$result->remainpoint}' " .
					"WHERE `ID`='{$id}'";
			$db->query($sql);
		}
		$re = $msg;
	}
	
	$db->close();
	return $re;
}

function is_email_well_form ( $email ) {
	return eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$", $email);
}

function is_mobile_number( $str ) {
	return  preg_match("/^((\+86)?|(86)?)(13[0-9]{9}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|5|6|7|8|9]\d{8})$/", $str);
}

function get_privileges_of_adding_agent () {
	$array = array();
	
	$a1= array();
	if( isset( $_POST["customlist"] ) && $_POST["customlist"]=="on" ) array_push($a1, "客户列表");
	if( isset( $_POST["customhide"] ) && $_POST["customhide"]=="on" ) array_push($a1, "屏蔽客户");
	if( isset( $_POST["customdelete"] ) && $_POST["customdelete"]=="on" ) array_push($a1, "删除客户");
	if( isset( $_POST["customupdate"] ) && $_POST["customupdate"]=="on" ) array_push($a1, "修改客户资料");
	if( !empty($a1) ){
		array_unshift($a1, "客户管理");
		array_push($array, implode(",", $a1));
	}
	
	$a2= array();
	if( isset( $_POST["restaurantlist"] ) && $_POST["restaurantlist"]=="on" ) array_push($a2, "餐馆列表");
	if( isset( $_POST["restaurantadd"] ) && $_POST["restaurantadd"]=="on" ) array_push($a2, "添加餐馆");
	if( isset( $_POST["restaurantdelete"] ) && $_POST["restaurantdelete"]=="on" ) array_push($a2, "删除餐馆");
	if( isset( $_POST["restaurantupdate"] ) && $_POST["restaurantupdate"]=="on" ) array_push($a2, "修改餐馆资料");
	if( isset( $_POST["dishadd"] ) && $_POST["dishadd"]=="on" ) array_push($a2, "添加餐品");
	if( isset( $_POST["dishdelete"] ) && $_POST["dishdelete"]=="on" ) array_push($a2, "删除餐品");
	if( isset( $_POST["dishupdate"] ) && $_POST["dishupdate"]=="on" ) array_push($a2, "修改餐品资料");
	if( !empty($a2) ){
		array_unshift($a2, "餐馆管理");
		array_push($array, implode(",", $a2));
	}
	
	$a3= array();
	if( isset( $_POST["ordercurrent"] ) && $_POST["ordercurrent"]=="on" ) array_push($a3, "查看当前订单");
	if( isset( $_POST["orderhistory"] ) && $_POST["orderhistory"]=="on" ) array_push($a3, "查看历史订单");
	if( isset( $_POST["orderdrop"] ) && $_POST["orderdrop"]=="on" ) array_push($a3, "手工下单");
	if( !empty($a3) ){
		array_unshift($a3, "订单管理");
		array_push($array, implode(",", $a3));
	}
	
	$a4= array();
	if( isset( $_POST["reportdaily"] ) && $_POST["reportdaily"]=="on" ) array_push($a4, "按日查询");
	if( isset( $_POST["reportmonthly"] ) && $_POST["reportmonthly"]=="on" ) array_push($a4, "按月查询");
	if( isset( $_POST["reportcustom"] ) && $_POST["reportcustom"]=="on" ) array_push($a4, "自定义查询");
	if( !empty($a4) ){
		array_unshift($a4, "财务管理");
		array_push($array, implode(",", $a4));
	}
	
	$a5= array();
	if( isset( $_POST["citylist"] ) && $_POST["citylist"]=="on" ) array_push($a5, "城市列表");
	if( isset( $_POST["cityadd"] ) && $_POST["cityadd"]=="on" ) array_push($a5, "添加城市");
	if( isset( $_POST["citydelete"] ) && $_POST["citydelete"]=="on" ) array_push($a5, "删除城市");
	if( isset( $_POST["cityupdate"] ) && $_POST["cityupdate"]=="on" ) array_push($a5, "修改城市信息");
	if( isset( $_POST["regionadd"] ) && $_POST["regionadd"]=="on" ) array_push($a5, "添加区域");
	if( isset( $_POST["regiondelete"] ) && $_POST["regiondelete"]=="on" ) array_push($a5, "删除区域");
	if( isset( $_POST["regionupdate"] ) && $_POST["regionupdate"]=="on" ) array_push($a5, "修改区域信息");
	if( !empty($a5) ){
		array_unshift($a5, "城市管理");
		array_push($array, implode(",", $a5));
	}
	
	$a6= array();
	if( isset( $_POST["agentlist"] ) && $_POST["agentlist"]=="on" ) array_push($a6, "代理列表");
	if( isset( $_POST["agentadd"] ) && $_POST["agentadd"]=="on" ) array_push($a6, "添加代理");
	if( isset( $_POST["agentdelete"] ) && $_POST["agentdelete"]=="on" ) array_push($a6, "删除代理");
	if( isset( $_POST["agentupdate"] ) && $_POST["agentupdate"]=="on" ) array_push($a6, "修改代理信息");
	if( !empty($a6) ){
		array_unshift($a6, "代理管理");
		array_push($array, implode(",", $a6));
	}
	
	$a7= array();
	if( isset( $_POST["smssetting"] ) && $_POST["smssetting"]=="on" ) array_push($a7, "短信平台设置");
	if( isset( $_POST["smslist"] ) && $_POST["smslist"]=="on" ) array_push($a7, "短信记录");
	if( isset( $_POST["smsgroupsend"] ) && $_POST["smsgroupsend"]=="on" ) array_push($a7, "短信群发");
	if( isset( $_POST["smssinglesend"] ) && $_POST["smssinglesend"]=="on" ) array_push($a7, "短信单发");
	if( isset( $_POST["smsdelete"] ) && $_POST["smsdelete"]=="on" ) array_push($a7, "删除短信记录");
	if( !empty($a7) ){
		array_unshift($a7, "短信管理");
		array_push($array, implode(",", $a7));
	}
	
	$a8= array();
	if( isset( $_POST["qalist"] ) && $_POST["qalist"]=="on" ) array_push($a8, "留言列表");
	if( isset( $_POST["qareply"] ) && $_POST["qareply"]=="on" ) array_push($a8, "留言回复");
	if( isset( $_POST["qahide"] ) && $_POST["qahide"]=="on" ) array_push($a8, "留言屏蔽");
	if( isset( $_POST["qadelete"] ) && $_POST["qadelete"]=="on" ) array_push($a8, "留言删除");
	if( !empty($a8) ){
		array_unshift($a8, "留言管理");
		array_push($array, implode(",", $a8));
	}
	
	$a9= array();
	if( isset( $_POST["pagehome"] ) && $_POST["pagehome"]=="on" ) array_push($a9, "主页设置");
	if( isset( $_POST["pagehelp"] ) && $_POST["pagehelp"]=="on" ) array_push($a9, "用户帮助页");
	if( isset( $_POST["pagecontact"] ) && $_POST["pagecontact"]=="on" ) array_push($a9, "联系我们页");
	if( isset( $_POST["pageabout"] ) && $_POST["pageabout"]=="on" ) array_push($a9, "关于我们页");
	if( isset( $_POST["pageright"] ) && $_POST["pageright"]=="on" ) array_push($a9, "功能页面右侧");
	if( !empty($a9) ){
		array_unshift($a9, "网站设置");
		array_push($array, implode(",", $a9));
	}
	
	$a10= array();
	if( isset( $_POST["systemsetting"] ) && $_POST["systemsetting"]=="on" ) array_push($a10, "系统设置");
	if( isset( $_POST["customlog"] ) && $_POST["customlog"]=="on" ) array_push($a10, "客户操作日志");
	if( isset( $_POST["agentlog"] ) && $_POST["agentlog"]=="on" ) array_push($a10, "代理操作日志");
	if( !empty($a10) ){
		array_unshift($a10, "系统管理");
		array_push($array, implode(",", $a10));
	}
	
	return implode(",", $array);
}

/**
 * 餐馆log
 */
function restaurant_log( $operation, $data=null ) {
	check_login();
	
	$db = db_connect();
	$sql = "INSERT INTO `RestaurantLog`(`RestaurantID`, `Name`, `CityID`, " .
			"`City`, `AgentID`, `Agent`, `IP`, `Operation` " .
			( empty($data) ? "" : ", `Data` ") . ",`OpTime`) " .
			"VALUES('{$_SESSION['admin_restaurant_id']}','{$_SESSION['admin_restaurant_name']}','{$_SESSION['admin_city_id']}'," .
			"'{$_SESSION['admin_city']}','{$_SESSION['admin_ragent_id']}','{$_SESSION['admin_ragent_name']}'," .
			"'".get_client_ip()."','{$operation}'" .
			( empty($data) ? "" : ", '{$data}' ") . ",'".get_datetime()."')";
	$db->query($sql);		
	
	$db->close();
}

/**
 * 写log
 */
function agent_log( $operation, $data=null ) {
	check_login();
	
	if(isset($_SESSION['admin_is_restaurant'])){
		return restaurant_log($operation,$data);
	}
	
	$db = db_connect();
	$sql = "INSERT INTO `AgentLog`(`AgentID`, `Name`, `CityID`, " .
			"`City`, `Realname`, `Username`, `IP`, `Operation` " .
			( empty($data) ? "" : ", `Data` ") . ",`OpTime`) " .
			"VALUES('{$_SESSION['admin_agent_id']}','{$_SESSION['admin_agent_name']}','{$_SESSION['admin_city_id']}'," .
			"'{$_SESSION['admin_city']}','{$_SESSION['admin_real_name']}'," .
			"'{$_SESSION['admin_username']}','".get_client_ip()."','{$operation}'" .
			( empty($data) ? "" : ", '{$data}' ") . ",'".get_datetime()."')";
	$db->query($sql);		
	
	$db->close();
}
/**
 * 组装一个错误json
 * @param string $msg 错误信息
 * @param string $url 跳转url，如果不提供，结果中将不包含跳转URL
 */
function error_json( $msg, $url=null ) {
	return '{"success":false, "msg":"'.$msg.'"'.(isset($url) ? ',"url": "'.$url.'"':'').'}';
}

function success_json_no_data() {
	return '{"success":true}';
}

function getRestarautCount(){
	$re="";
	$db = dao();
	$sql = "select * from `restaurant` where `Hide`=0"; 
	$query = $db->query($sql);
	$rs=$db->query($sql);
	if($row=$rs->fetch_assoc()){
		$re=$row;
	}
	return count($re);
}

function save_scoreReg(){
	$dingcanscore = addslashes(trim($_POST["dingcanscore"]));
	$pinglunscore = 0;
	$tip1 = "温馨提示1";
	$tip2 = "温馨提示1";
	//数据库操作
    $db = db_connect();
    $sql = "UPDATE `Scorereg` SET `dingcanscore`='{$dingcanscore}',`pinglun`='评论',`pinglunscore`='{$pinglunscore}'," .
    		"`tip1`='{$tip1}',`tip2`='{$tip2}' " .
    		"WHERE `DINGCAN`='DINGCAN'";
    $db->query($sql);
    
    //返回结果
    $re = "";
    if( $db->affected_rows>-1 ) {
    	$re = '{"success":true}';
    }
    else {
    	$re = error_json("积分配置参数修改失败！" );
    }
    
    $db->close();
    return $re;
	
}

function  delete_custom()
{
	$CustomID = addslashes(trim($_POST["CustomID"])) + 0;
	$db=db_connect();
	$sql="update `custom` set `hide`=1 where `id`='{$CustomID}'";
	$db->query($sql);
	$re = "";
    if( $db->affected_rows>-1 ) {
    	$re = '{"success":true, "id": '.$db->insert_id().'}';
    }
    else {
    	$re = error_json("删除失败！" );
    }
    
    $db->close();
    return $re;
}

function delete_customs(){
	$re="";
	$db = dao();
	$ids = "";
	$ids = $_POST['ids'];
	$db->autocommit(false);
	$sql = "update `custom` set `hide`=1 where `id` in (".$ids.")"; 
	$query = $db->query($sql);
	if(!$query)
	{
		$db->rollback();
		$re = error_json("批量删除失败！" );	
	}else{
		$db->commit();	
		$re = '{"success":true, "id": 1}';
	}
	return $re;
}


function delete_customs1(){
	$re="";
	$db = dao();
	$ids = array();
	$ids = $_POST['ids'];
	$db->autocommit(false);	
	$result = true;
	foreach($ids as $id){
		$sql="update `custom` set `hide`=1 where `id`='{$id}'";
		$result = $db->query($sql);
		if($result==false)
		{
			break;
		}
	}
	if($result==false){
		$db->rollback(); 
		$re = success_json_no_data();
	}else{
		$db->commit();
		$re = error_json("批量删除失败！" );
	}
}

function  sms_queue_addmore(){
	$re="";
	$db=dao();
	$ins_id="";
	$ids=$_POST['ids'];
	$tels=$_POST['tels'];
	$id_arr=explode(',',$ids);
	$tel_arr=explode(',',$tels);
	$db->autocommit(false);	
	$query;
	for($i=0; $i<count($id_arr); $i++){
		$Receiver = $tel_arr[$i];
		$Content = "添加到短信队列";
		$CustomID = $id_arr[$i];
		if(empty($Receiver)){
			agent_log("短信群发", "添加一个手机号码失败，短信内容：[".$Content."]，失败：手机号码为空。");
			return error_json("手机号码为空");
		}
		if(empty($CustomID) && empty($Content)){
			agent_log("短信群发", "添加一个手机号码失败，手机号码：".$Receiver."，失败：短信内容为空。");
			return error_json("短信内容为空");
		}
		if(!is_mobile_number($Receiver)){
			agent_log("短信群发", "添加一个手机号码失败，手机号码不是有效的手机号码，手机号码：".$Receiver."，短信内容：[".$Content."]。");
	    	$re = error_json( "请填写有效的手机号码。" );
		}
		$sql = "INSERT INTO `SmsQueue`(`Receiver`, `Content`, `CustomID`) " .
    		"VALUES('{$Receiver}', '{$Content}', " .
    		(empty($CustomID) ? "NULL" : "'{$CustomID}'") . 
    		")";
    	$query = $db->query($sql);
    	if($query!=1){
    		break;
    	}
	}
	if($query!=1){
		$db->rollback(); 
		$re = error_json("批量删除失败！" );
	}else{
		$db->commit();
		$re = '{"success":true, "id": '.$query.'}';
	}
	return $re;
}


/**
 * 连接数据库
 */
function db_connect() {
    global $dbhost;
    global $dbuser;
    global $dbpass;
    global $dbname;
    
    $db = new Database($dbhost, $dbuser, $dbpass, $dbname);
    return $db;
}

/**
 * 生成6位UUID
 */
function uuid6($prefix = '') {
	$chars = md5(uniqid(mt_rand(), true));
	$uuid  = substr($chars,0,6);
	return $prefix . $uuid;
}

/**
 * 获取服务器当前的时间
 * @return string 时间字符串，格式: YYYY-mm-dd HH:ii:ss
 */
function get_datetime() {
	date_default_timezone_set('PRC');
	return date('Y-m-d H:i:s');
}

/**
 * 得到中文首字母
 * Enter description here ...
 * @param $s0
 */
function getfirstchar($s0){
	$fchar = ord($s0{0});
	if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
	$s1 = iconv("UTF-8","gb2312", $s0);
	$s2 = iconv("gb2312","UTF-8", $s1);
	if($s2 == $s0){$s = $s1;}else{$s = $s0;}
	$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;

	if($asc >= -20319 and $asc <= -20284) return "A";
	if($asc >= -20283 and $asc <= -19776) return "B";
	if($asc >= -19775 and $asc <= -19219) return "C";
	if($asc >= -19218 and $asc <= -18711) return "D";
	if($asc >= -18710 and $asc <= -18527) return "E";
	if($asc >= -18526 and $asc <= -18240) return "F";
	if($asc >= -18239 and $asc <= -17923) return "G";
	if($asc >= -17922 and $asc <= -17418) return "H";
	if($asc >= -17417 and $asc <= -16475) return "J";
	if($asc >= -16474 and $asc <= -16213) return "K";
	if($asc >= -16212 and $asc <= -15641) return "L";
	if($asc >= -15640 and $asc <= -15166) return "M";
	if($asc >= -15165 and $asc <= -14923) return "N";
	if($asc >= -14922 and $asc <= -14915) return "O";
	if($asc >= -14914 and $asc <= -14631) return "P";
	if($asc >= -14630 and $asc <= -14150) return "Q";
	if($asc >= -14149 and $asc <= -14091) return "R";
	if($asc >= -14090 and $asc <= -13319) return "S";
	if($asc >= -13318 and $asc <= -12839) return "T";
	if($asc >= -12838 and $asc <= -12557) return "W";
	if($asc >= -12556 and $asc <= -11848) return "X";
	if($asc >= -11847 and $asc <= -11056) return "Y";
	if($asc >= -11055 and $asc <= -10247) return "Z";
	return null;
}

/**
 * 截取中文首字母
 * Enter description here ...
 * @param $str
 * @param $from
 * @param $len
 */
function utf8Substr($str, $from, $len)
{
	return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
}
/**
 * 获取客户端的真实IP
 */
function get_client_ip() {
	$unknown = 'unknown';  
	if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) 
		&& $_SERVER['HTTP_X_FORWARDED_FOR'] 
		&& strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) 
	{  
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
	}
	elseif ( isset($_SERVER['REMOTE_ADDR']) 
		&& $_SERVER['REMOTE_ADDR'] 
		&& strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) )
	{  
		$ip = $_SERVER['REMOTE_ADDR'];  
	}  
	/*
	处理多层代理的情况  
	或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;  
	*/  
	if (false !== strpos($ip, ','))  
		$ip = reset(explode(',', $ip));  
	
	return $ip;
}

// mysqli 数据访问对象
function dao() {
	global $dbhost;
	global $dbuser;
	global $dbpass;
	global $dbname;
	$db = new mysqli ( $dbhost, $dbuser, $dbpass, $dbname );
	$db->query ( "set names 'utf8';" );
	$db->query ( "SET CHARACTER_SET_CLIENT=UTF8;" );
	$db->query ( "SET CHARACTER_SET_RESULTS=UTF8;" );
	$db->query ( "SET time_zone = '+8:00';" );
	return $db;
}
/**
 * 以下为公共执行内容
 */
//注意：所有函数、cookie都没有了反斜杠
if (get_magic_quotes_gpc ()) {
 	function stripslashes_deep ($value){
		$value = (is_array ($value) ? array_map ('stripslashes_deep', $value) : stripslashes ($value));
		return $value;
	}

	$_POST = array_map ('stripslashes_deep', $_POST);
	$_GET = array_map ('stripslashes_deep', $_GET);
	$_COOKIE = array_map ('stripslashes_deep', $_COOKIE);
	$_REQUEST = array_map ('stripslashes_deep', $_REQUEST);
}

if (get_magic_quotes_runtime ()) {
	set_magic_quotes_runtime (0);
}
  
session_start ();

?>