/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if(loginInfo.account.length == 0) {
			return callback('账号不能为空');
		}
		if(loginInfo.password.length == 0) {
			return callback('密码不能为空');
		}
//		var users = JSON.parse(localStorage.getItem('$users') || '[]');

		var url = API.API_URL();
               
		mui.ajax(url, {
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			data: {
				'serviceId': 'eu_2013V01login',
				'params': '{userName:"' + loginInfo.account + '",password:"' + loginInfo.password + '"}'
			},
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Accept': 'application/json'
			},
			success: function(data) {
				//服务器返回响应
				if(data.returnCode == 1){
					console.log(data.returnParams);
					var user = data.returnParams;
					var token = data.returnParams.useId;
					return owner.createState(user,token, callback);
				}else{
					
					return callback(data.returnMsg);
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(xhr+"========"+type+"==========="+errorThrown);
			}
		});

		//		var authed = users.some(function(user) {
		//			return loginInfo.account == user.account && loginInfo.password == user.password;
		//		});
		//		if (authed) {
		//			return owner.createState(loginInfo.account, callback);
		//		} else {
		//			return callback('用户名或密码错误');
		//		}
	};

	owner.createState = function(user,token, callback) {
		var state = owner.getState();
		state.user = user;
		state.account = user.name;
		state.token = token;
		owner.setState(state);
		saveCid();
		return callback();
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if(regInfo.account.length < 5) {
			return callback('用户名最短需要 5 个字符');
		}
		if(regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		if(!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		users.push(regInfo);
		localStorage.setItem('$users', JSON.stringify(users));
		return callback();
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
//		var stateText = localStorage.getItem('$state') || "{}";
//		var state = JSON.parse(stateText);
//		var user = {useId:8945468387975,name:'测试2',unitId:347517153919893,groupid:84799943261843,gxId:768921704455493};
//		state.user = user;
//		return state;
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);

	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};

	owner.clearView = function(){
		var curr = plus.webview.currentWebview();
        var wvs = plus.webview.all();
        for (var i = 0, len = wvs.length; i < len; i++) {
            if (wvs[i].getURL() == curr.getURL()){
            	continue;
            }else{
            	wvs[i].close('none'); 　
            }
        }
	}

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if(!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}
	/**
	 * 获取本地是否安装客户端
	 **/
	owner.isInstalled = function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
	
	/**
	 * 
	 **/
	owner.ajax = function(serviceId,params, callback) {
		callback = callback || $.noop;	
		var url = API.API_URL();
		params = JSON.stringify(params);
		var obj = {serviceId:serviceId,params:params};
		console.log(JSON.stringify(obj));
		mui.ajax(url, {
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			data: obj,
			timeout: 30000, //超时时间设置为10秒；
			headers: {
				'Accept': 'application/json'
			},
			success: function(data) {
				//服务器返回响应
				console.log(JSON.stringify(data));
				if(data.returnCode == 0){
					return callback(data.returnParams);
				}else{
					mui.toast(data.returnMsg);
					if(mui('#pullrefresh')&&mui('#pullrefresh').pullRefresh()){
						mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
						mui('#pullrefresh').pullRefresh().endPulldown();
					}
					if(document.querySelector(".mui-btn")){
						document.querySelector(".mui-btn").removeAttribute("disabled");
					}
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(xhr+"==="+ type+"===="+ errorThrown);
//				plus.nativeUI.toast("网络异常,请稍候再试");
				if(mui('#pullrefresh')&&mui('#pullrefresh').pullRefresh()){
					mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
					if(mui('#pullrefresh').pullRefresh().endPulldown)
						mui('#pullrefresh').pullRefresh().endPulldown();
				}
			}
		});
	};
	
	
}(mui, window.app = {}));