app.controller('AppCtrl', function($rootScope, $scope, $http, $state, $timeout) {
	// 请求初始化信息，这里用同步模式
	$.LoadingOverlay("show");
	$.ajax({
		url : '../enrol/school/info/init.htm',
		async : false,
		type : "POST",
		dataType : "json",
		success : function(data) {
			$.LoadingOverlay("hide");
			if (data.success == false) {
				var msg = '鉴权失败，请先登录！';
				if (data.login) {
					msg = data.errorMsg;
				}
				$rootScope.msg(msg, '错误提示', function() {
					window.location = './login/login.jsp';
				});
				return;
			} else {
				$rootScope.StdSchool = data.map.StdSchool;
			}
		},
		error : function() {
			$.LoadingOverlay("hide");
			$rootScope.msg('服务器出现内部错误，请稍候重试！', '错误提示', function() {
				window.location = './login/login.jsp';
			});
			return;
		}
	});

	// 通用ajax请求
	$rootScope.ajaxRequest = function(url, param, callback, type) {
		if (param == undefined)
			param = {};
		var obj;
		if ($rootScope.GobalStdReg)
			param.std_id = $rootScope.GobalStdReg.std_id;
		if ($rootScope.GobalSchoolReg)
			param.school_id = $rootScope.GobalSchoolReg.school_id;

		$http({
			url : url,
			method : 'post',
			data : param
		}).then(function success(response) {
			var data = response.data;
			if (type == 'entity')
				obj = data.entity;
			else if (type == 'array')
				obj = data.array;
			else if (type == 'map')
				obj = data.map;
			else if (type == 'page')
				obj = data.page;
			else
				obj = data;
			if (callback != undefined) {
				callback.call(undefined, obj);
			}
		});
	}
	// $.LoadingOverlay("show");
	$rootScope.goUrl = function(url, param) {
		// 确保能刷新子路由
		// $state.reload();
		$timeout(function() {
			$state.go('app.' + url, param);
		}, 100);
	}

	$rootScope.logout = function() {
		$rootScope.ajaxRequest('../enrol/school/logout.htm', {}, function() {
			window.location = './login/login.jsp';
		});
	}

});