var app = {
	loading : function(is, position) {
		app.isLoading = is;
		toastr.clear();
		$('#loading').css('display', is ? 'block' : 'none');
		is && position && ($('#loading').addClass(position));
	},
	info : function(message, title, position) {
		toastr.clear();
		toastr.info(message, title, {
			positionClass : 'toast-' + (position || 'top-center'),
			timeOut : 5000
		});
	},
	error : function(message, title, position) {
		toastr.clear();
		toastr.error(message, title, {
			positionClass : 'toast-' + (position || 'top-center')
		});
	},
	alertDialog: function (title, content, btn, callback, fun) {
		var dialog = $('#alertDialog');
		title && dialog.find('.weui_dialog_title').text(title);
		content && dialog.find('.weui_dialog_bd').text(content);
		btn && dialog.find('.weui_btn_dialog').text(btn);
		callback && dialog.find('.weui_btn_dialog').click(function (e) {
			callback.call(null);
			dialog.hide();
		});
		dialog.show();
		/*倒计时*/
		var count = 3;
		var interval = app.checkcodeInterval = setInterval(function () {
			if (count == 0) {
				window.location.href = "https://account.ubtob.com/sso/login";
				clearInterval(intervalid);
			}
			document.getElementById("count").innerHTML = count;
			count--;
		}, 1000);
	},
	postFileAndData: function(formData) {
		if (app.isLoading)
			return;
		app.loading(true);
		var btn = $('.x-btn-submit');
		btn.attr('disabled', 'disabled');
		$.ajax({
			type: 'POST',
			url: 'sso/mobile/userspace/register',
			data: formData,
			dataType: 'json',
			success: function (data){
				if(typeof data === 'string') {
					data = JSON.parse(data);
				}
				app.loading(false);
				if(data.success) {
					window.location.href = 'sso/register';
				} else if (data.errMsg) {
					btn.attr('disabled', null);
					app.error(data.errMsg);
				} else if (data.errDetail) {
					btn.attr('disabled', null);
					app.error('填写信息有误');
				}
				if(data.pageToken) {
					$('input[name=pageToken]').val(data.pageToken);
				}
			},
			error: function (){
				btn.attr('disabled', null);
				app.loading(false);
				app.error('出现错误');
			}
		});
	},
	/**
	 * 禁用/启用发送验证码按钮
	 * @param el
	 * @param value
	 */
	enableCheckcode: function () {
		var telInput = $('[name=adminTel]'), emailInput = $('[name=adminEmail]'), checkcodeBtn = $('.x-btn-checkcode');
		function updateEnable() {
			var timeout = localStorage.getItem('checkcodeTimeOut');
			if(!(timeout && timeout > 0) && telInput.val() && checkPattern(telInput) && emailInput.val() && checkPattern(emailInput)) {
				checkcodeBtn.removeAttr('disabled');
			} else {
				checkcodeBtn.attr('disabled', 'disabled');
			}
		};
		telInput.bind('input propertychange', function (event) {
			updateEnable();
		});
		emailInput.bind('input propertychange', function (event) {
			updateEnable();
		});
	},
	initForm: function() {
		$('.x-form').validation({
			// 允许没校验过的情况下点击按钮，这样可以提示错误在哪
			disable: false,
			success: function(form, data) {
				if (!data.agree) {
					app.error('您还未同意优软平台服务协议');
				} else {
					$.extend(data, app.cityData);
					app.postFileAndData(data);
				}
			},
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'name': app.checkName,
				'businessCode': app.checkBusCode,
				'file': app.showLocalFile,
				'checkcode': app.checkCheckcode
			}
		});
		app.enableCheckcode();// 监听获取验证码的按钮状态
		$('.x-btn-checkcode').click(app.getCheckcode);
		app.checkcodeTimeout();
	},
	checkName: function(el, name) {
		$.get('sso/userspace/valid', {
			name: name
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				el.addClass('x-error');
			}
		});
	},
	checkBusCode: function(el, busCode) {
		$.get('sso/userspace/valid', {
			businessCode: busCode
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				el.addClass('x-error');
			}
		});
	},
	/**
	 * 验证验证码是否正确
	 * @param el
	 * @param val
	 */
	checkCheckcode: function (el, code) {
		var token = el.data('token');
		if(token) {
			$.post('sso/userspace/checkcode', {
				token: token,
				code: code
			}, function (res) {
				if (res.success) {
					app.info('验证码正确');
				} else {
					app.error(res.errMsg);
					el.addClass('x-error');
				}
			});
		} else {
			app.error('请先获取验证码');
			el.addClass('x-error');
		}
	},
	initApps: function() {
		var form = $('.x-form');
		form.validation({
			disable: false,
			success: app.applyApps,
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'oldPassword': function(el, password) {
					$.get('api/user', {
						_operate: 'fuzzyCheck',
						password: password,
						uid: form.find('input[name=adminTel]').val()
					}, function(data) {
						if(data.success) {
							// app.info("密码正确");
							$('#password').val(password);
							$('#passwordConfirm').val(password);
							$('#passwordvalid_err').hide();
						} else if(data.errMsg) {
							el.addClass('x-error');
//							 app.error(data.errMsg);
							toggleError(el, false, data.errMsg);
							$('#password').val('');
							$('#passwordConfirm').val('');
						}
					}) 
				},
				'password': function(el, val){
					var oth = form.find('#passwordConfirm');
					if (oth.val() && val != oth.val()) {
						app.error('密码不一致');
					}
				},
				'passwordConfirm': function(el, val){
					var oth = form.find('#password');
					if (val != oth.val()) {
						el.addClass('x-error');
						app.error('密码不一致');
					}
				},
				'domain': app.checkDomain,
				'file': app.showLocalFile
			}
		});
		form.find('input[name=applyApps]').change(function(){
			var that = $(this), val = that.val(),
				oth = val == 'saas' ? form.find('input[value=uas]') : form.find('input[value=saas]');
			if (that.is(':checked')) {
				if(oth.is(':checked')) {
					oth.attr('checked', null);
					form.find('#' + oth.attr('x-detail')).hide();
				}
				form.find('#' + that.attr('x-detail')).fadeIn();
			} else {
				form.find('#' + that.attr('x-detail')).hide();
			}
		});
	},
	checkDomain: function(el, domain) {
		$.get('sso/userspace/valid', {
			domain: domain
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				el.addClass('x-error');
			}
		});
	},
	applyApps: function(form, formData) {
		console.log(formData);
		if(formData.password != formData.passwordConfirm){
			app.error('密码不一致');
		} 
		else {
			if (formData.users) {
				var users = [], chkObjs = {}, err = false;
				$.each(formData.users, function(){
					if(!err && this.name && (this.mobile || this.email)) {
						var ch1 = (this.mobile ? this.name + this.email : null),
							ch2 = (this.email ? this.name + this.mobile : null),
							ex1 = (this.mobile ? chkObjs[this.mobile] : null),
							ex2 = (this.email ? chkObjs[this.email] : null);
						if((ex1 && ex1 != ch1) || (ex2 && ex2 != ch2)) {
							err = true;
							app.error(this.name + ' 的信息不正确，请核对填写的手机号和邮箱地址');
						} else {
							users.push(this);
							this.mobile && (chkObjs[this.mobile] = ch1);
							this.email && (chkObjs[this.email] = ch2);
						}
					}
				});
				if (err)
					return;
				formData.users = JSON.stringify(users);
			}
			var applySaas = (formData.applyApps && formData.applyApps.indexOf('saas') > -1);
			if (!applySaas) {
				formData.domain = null;
			}
			app.loading(true);
			$.ajaxFileUpload({
				url: 'sso/register/applyApp',
				secureuri: false,
				fileElementId: 'logoImage',
				data: formData,
				dataType: 'json',
				success: function (data){
					app.loading(false);
					if(typeof data === 'string') {
						data = JSON.parse(data);
					}
					if (data && data.errMsg) {
						app.error(data.errMsg, '操作失败');
					} else {
						app.alertDialog();
					}
				},
				error: function (){
					app.loading(false);
					app.error('出现错误');
				}
			});
		}
	},
	/**
	 * 获取验证码
	 * @param e
	 */
	getCheckcode: function (e) {
		var me = $(this);
		app.loading(true);
		var checkcodeTimeout = function () {
			setInterval()
		};
		$.get('sso/userspace/checkcode', {
			tel: $('[name=adminTel]').val(),
			email: $('[name=adminEmail]').val(),
			pageToken: $('[name=pageToken]').val()
		}, function (res) {
			app.loading(false);
			if(res && res.success) {
				me.attr('disabled', 'disabled');
				$('[name=checkcode]').data('token', res.content.token);
				$('[name=checkcodeToken]').val(res.content.token);
				app.checkcodeTimeout(60);
				app.info('验证码已经发送到您的手机和邮箱');
			}
		});
	},
	/**
	 * 获取验证码倒计时
	 * @param time
	 */
	checkcodeTimeout: function (time) {
		var localStorageKey = 'checkcodeTimeOut';
		time = time || localStorage.getItem(localStorageKey);
		if(time > 0) {
			$('.x-timeout-word').show().siblings().hide();
			var interval = setInterval(function () {
				$('.x-timeout-num').text(time);
				time --;
				localStorage.setItem(localStorageKey, time);
				if(time < 0) {
					$('.x-timeout-word').hide().siblings().show();
					clearInterval(interval);
					var telInput = $('[name=adminTel]'), emailInput = $('[name=adminEmail]'), checkcodeBtn = $('.x-btn-checkcode');
					if(telInput.val() && checkPattern(telInput) && emailInput.val() && checkPattern(emailInput)) {
						checkcodeBtn.removeAttr('disabled');
					}
				}
			}, 1000);
		}
	},
	init : function() {
		new Router({
			'#/valid': function() {
				app.initApps();
				// 滚动到密码框
//				$('input[name=password]').scrollTo();
			}
		}, function(){
			var pageStep = $('input[name=pageStep]').val();
			if(pageStep == 1) {
				app.initForm();
			} else {
				app.initApps();
			}

		}).start();
		app.loading(false);
	}
};
$(document).ready(function() {
	app.init();
});
