var app = {
	loading: function(is) {
		$('#loading').css('display', is ? 'block': 'none');
	},
	info: function(message, title, position) {
		toastr.info(message, title, {positionClass: 'toast-' + (position || 'top-center'), timeOut: 1000});
	},
	error: function(message, title, position) {
		toastr.error(message, title, {positionClass: 'toast-' + (position || 'top-center')});
	},
	//============CRUD about user & userDetail===============
	editDetail : function(event, mobile, email) {
		mobile = event ? $(event.target).data("mobile") : mobile;
		email = event ? $(event.target).data("email") : email;
		if (mobile || email) {
			$.getJSON('api/user/detail', {
				mobile: mobile,
				email: email
			}, function(data){
				if(data.content && data.content.name)
					app.showDetailModal(data.content);
				else
					app.error('没有找到个人资料');
			});
		} else {
			app.error('错误!');
		}
	},
	showDetailModal: function(content) {
		$('#userDetailModal').showModal({
			data: content,
			tplExp: '@{([^}]*)}',
			renderer: {
				getSex: function(data) {
					return ['女', 'F', '0'].indexOf(data.sex) > -1 ? '女' : '男';
				}
			},
			shown: function(){
				var scope = $(this);
				// 设置密码
				scope.find('.x-btn-reset').click(content, app.showPasswordModal);
				// listen on tab's first active
				scope.find('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
					var tabId = $(e.target).attr('aria-controls'), tab = scope.find("#" + tabId),
						ready = tab.attr('viewready');
					if (!ready) {
						tab.attr('viewready', true);
						if (tabId == 'userDetailModal_apps') {
							app.renderAppInfo(tab, content);
						} else if(tabId == 'userDetailModal_log') {
							
						}
					}
				});
			}
		});
	},
	synchrodata: function(data) {
		data = {id: data};
		app.loading(true);
		$.post('synchrodataToOldPlat', data, function(data) {
			app.loading(false);
			if (data && data.error) {
				app.error(data.error, '数据同步失败', 'top-right');
			} else if(data && data.success) {
				app.info(data.success, '数据同步成功', 'top-right');
			} else {
				app.error('添加用户失败', '数据同步失败', 'top-right');
			}
		}, 'json');
	},
	userpwd: function(data) {
		data = {id: data};
		app.loading(true);
		$.getJSON('synchrodataToOldPlat', data, function(data) {
			app.loading(false);
			if (data && data.error) {
				app.error(data.error, '查询失败', 'top-right');
			} else if(data && data.success) {
				app.info(data.success, '成功', 'top-right');
			} else {
				app.error('数据查询失败', 'error', 'top-right');
			}
		}, 'json');
	},
	showPasswordModal: function(e) {
		var box = $('#pwd-box');
		box.show();
		box.find('.x-close-wrap').click(function(){
			box.hide();
		});
		box.find('.x-btn-submit').click(function(){
			var f = box.find('input[name=password]');
			if (!f.val()) {
				f.focus();
				app.error('请输入密码');
			} else {
				box.hide();
				app.loading(true);
				$.getJSON('api/user/resetPwd', {
					uid: e.data.mobile,
					secondUID: e.data.email,
					password: f.val()
				}, function(data){
					app.loading(false);
					if(data.errMsg)
						app.error(data.errMsg);
					else
						app.info('重置成功');
				});
			}
		});
	},
	renderAppInfo: function(tab, detail) {
		app.getAllUsers(detail, function(users){
			var box = tab.find("#apps");
			if(users && users.length > 0) {
				box.appendTpl('<div class="x-item"><div class="x-icon"><i class="fa fa-file-o"></i></div><p><span class="x-title text-info">#{fn:getSpaceName}</span><span class="pull-right x-text-muted">#{appId}</span></p><div class="x-text-muted">#{name}<span class="pull-right">#{fn:getApplyStatus}</span></div><div class="x-title pull-right"><a type="button" class="btn btn-blank btn-synchrodata" onclick="app.synchrodata(#{id})">同步数据</a><a type="button" class="btn btn-blank btn-userpwd" onclick="app.userpwd(#{id})">查询密码</a></div></div>', users, {
					getSpaceName: function(data) {
						return data.spaceName || '(未绑定企业)';
					},
					getApplyStatus: function(data) {
						if (!data.dialectUID) {
							return '开通失败&nbsp;<a href="javascript:void(0);" data-app="' + data.appId + '" data-space="' + data.spaceId + '" class="x-text-link">重新开通</a>';
						}
						return data.dialectUID;
					},
					userInfo: function(data) {
						var appId = $(this).data('app'), spaceId = $(this).data('space'),
						user = {uid: detail.mobile, appId: appId, spaceId: spaceId};
						return user;
					},
				});
				box.find('.x-text-link').click(function(){
					var appId = $(this).data('app'), spaceId = $(this).data('space'),
						user = {uid: detail.mobile, appId: appId, spaceId: spaceId};
					app.loading(true);
					app.applyApp(user, function(){
						app.renderAppInfo(tab, detail);
					});
				});	
			} else {
				box.next().show();
			}
		});
	},
	getAllUsers: function(detail, callback) {
		// 所有绑定关系
		$.getJSON('api/user/all', detail, function(data){
			if(data.errMsg) {
				app.error(data.errMsg);
			} else {
				callback.call(null, data.content);
			}
		});
	},
	applyApp: function(user, callback) {
		app.loading(true);
		$.getJSON('api/user/applyApp', user, function(data){
			app.loading(false);
			if(data.errMsg) {
				app.error(data.errMsg);
			} else {
				callback.call(data.content);
			}
		});
	},
	//============list view===============
	showDetailList: function(params) {
		app.loading(true);
		$('.pagination').pagination({
			url: 'api/user/detail/list',
			params: params,
			renderData: function(content){
				app.loading(false);
				var list = $('.x-data-list');
				if(content.length == 0) {
					list.empty();
					$('.x-data-list-wrap .x-empty').show();
				} else {
					$('.x-data-list-wrap .x-empty').hide();
					list.appendTpl('<div class="x-item"><div class="x-icon"><i class="fa fa-user"></i></div><p><a class="x-title x-editor-trigger" href="javascript:void(0);" data-mobile="#{mobile}" data-email="#{email}">#{name}</a></p><div class="x-text-muted">#{fn:getUID}</div></div>', content, {
						getUID: function(d) {
							return d.mobile || d.email || '*';
						}
					});
					list.find('.x-editor-trigger').click(app.editDetail);
				}
			}
		});
	},
	searchDetail: function(event) {
		var target = $(event.target), form = $('.x-nav-tabs form'), data = form.serializeObject();
		if (!target.is('a')) {
			target = $('.x-nav-tabs .active a');
		}
		data.pageNumber = 1;
		app.showDetailList(data);
		$('.x-nav-tabs .active').removeClass('active');
		target.parent().addClass('active');
		$('#searchlist').hide();
		$(":text").val ("");
	},
	//============slide-bar info===============
	showUserCount: function() {
		$.getJSON('api/user/count', function(data){
			if(data.content) {
				var datas = [], total = data.content['全部'] || 0;
				$.each(data.content, function(k, v){
					datas.push({appName: k, count: v, total: total});
				});
				$('#userAppCount .x-mod-body').appendTpl('<div class="x-progress-wrap"><div class="x-progress-title">#{appName}<span class="pull-right">#{count}</span></div><div class="progress"><div class="progress-bar progress-bar-#{fn:getProcessCss}" role="progressbar" aria-valuenow="#{count}" aria-valuemin="0" aria-valuemax="#{total}" style="width: #{fn:getProcessWidth}"><span class="sr-only"></span></div></div></div>', datas, {
					getProcessCss: function(d) {
						var k = d.count/d.total;
						if(k == 1) {
							return 'success';
						} else if(k > 0.6) {
							return 'info';
						} else if(k > 0.3) {
							return 'warning';
						}
						return 'danger';
					},
					getProcessWidth: function(d) {
						return Math.round(100*d.count/d.total) + '%';
					}
				});
			}
		});
	},
	//============document ready===============
	init : function() {
		app.showDetailList({
			pageNumber: 1,
			pageSize: 20
		});
		app.showUserCount();
		$('.btn-search').click(app.searchDetail);
		new Router({
			'#/(.+)': function(mobile) {
				app.editDetail(null, mobile);
			}
		}).start();
		$('.x-btn-search').click(function() {
			$('#searchlist').toggle();
		});
		// 点击空白处关闭下拉框
		$(document).click(function(e) {
			var target = $(e.target);
			if(target.closest('.x-btn-search').length==0 && target.closest('#searchlist').length==0) {
				$('#searchlist').hide();
			}
		});
		// 监听Enter键
		$(function() { 
			var $inp=$('input');
			$inp.keypress(function(e){
		    var key=e.which;
		    if(key==13) {
		    	$('.btn-search').click();
		    }
		  }) 
		});
	}
};
$(document).ready(function() {
	app.init();
});