/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.warehouseCode = loginInfo.warehouseCode || '';
		loginInfo.userCode = loginInfo.userCode || '';
		loginInfo.password = loginInfo.password || '';
		
		if (loginInfo.warehouseCode.length < 1) {
			return callback('仓库代码最短为 1 个字符');
		}
		if (loginInfo.userCode.length < 4) {
			//return callback('用户代码最短为 4 个字符');
		}
		if (loginInfo.password.length < 6) {
			//return callback('用户密码最短为 6 个字符');
		}
		//服务器地址
		var serverUrl = localStorage.getItem('$serverUrl'); 
		if (serverUrl == null || serverUrl == '') {
			return callback('请先设置服务器');
		}
		var loginUrl = serverUrl + '/app/loginV2/loginAction';
		
		var result = null;
			
		//ajax登录		
		mui.ajax(loginUrl,{
			async: false,
		    data:{
		        warehouseCode:loginInfo.warehouseCode,
		        userCode:loginInfo.userCode,
		        password:loginInfo.password,
		        version:1
			},
	        dataType:'json',//服务器返回json格式数据
	        contentType:"application/json",
	        type:'post',//HTTP请求类型
	        timeout:10000,//超时时间设置为10秒；
	        success:function(tempResult){
	        	result = tempResult;
	        },
	        error:function(xhr,type,errorThrown){
	            //异常处理
	            console.log(type);
	            return callback('登录失败,AJAX异常');	
	        }
	    });
	    
		if (result.code != 0) {
			return callback(result.msg);			
		}
		var loginVo = result.data;
		
		//调试使用
		localStorage.setItem('$warehouseCode',loginInfo.warehouseCode); 
		localStorage.setItem('$userCode',loginInfo.userCode); 
		localStorage.setItem('$password',loginInfo.password); 			
		localStorage.setItem('$warehouseUrl', loginVo.clientUrl);
		localStorage.setItem('$loginTime',new Date().toLocaleTimeString());
		
		return owner.createState(loginInfo, callback);
	};

	owner.createState = function(loginInfo, callback) {
		var state = owner.getState();
		state.warehouseCode = loginInfo.warehouseCode;
		state.userCode = loginInfo.userCode;
		
		state.timestamp = (new Date()).getTime();
		state.localeTime = new Date().toLocaleTimeString();
		
		owner.setState(state);
		return callback();
	};

	/**
	 * 设置服务器地址
	 **/
	owner.reg = function(serverInfo, callback) {
		callback = callback || $.noop;
		serverInfo = serverInfo || {};
		
		serverInfo.ip = serverInfo.ip || '';
		serverInfo.port = serverInfo.port || '80';
		
		if (serverInfo.ip.length < 5) {
			return callback('服务器地址最短需要 5 个字符');
		}
		
		//ajax
		var url = 'http://' + serverInfo.ip + ':' + serverInfo.port;
		var testUrl = url + '/app/loginV2/test';
		var isSuccess = false;
		mui.ajax(testUrl,{
			async: false,
		    data:{
		        test:1
			},
	        dataType:'json',//服务器返回json格式数据
	        contentType:"application/json",
	        type:'post',//HTTP请求类型
	        timeout:10000,//超时时间设置为10秒；
	        success:function(data){
	        	if(data.code == 0){
	        		isSuccess  = true;
	        	}
	            //JSON.stringify()将 JSON对象转为json字符串
	            var data = JSON.stringify(data);
	            console.info(data);
	        },
	        error:function(xhr,type,errorThrown){
	            //异常处理
	            console.log(type);
	            return callback('发生异常,地址错误或网络异常!');
	        }
	    });
	    
	    if(isSuccess){
	    	//保存服务器地址
			localStorage.setItem('$serverUrl', url);
			localStorage.setItem('$serverIp', serverInfo.ip);
			localStorage.setItem('$serverPort', serverInfo.port);
			return callback();//必须留空
	    }
		return callback('设置服务器失败,地址ajax验证未返回正确状态');		
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		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.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;
			}
		}
	}
}(mui, window.app = {}));