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 userpace===============
	editSpaceDetail : function(event, bussCode) {
		bussCode = event ? $(event.target).data("id") : bussCode;
		if (bussCode) {
			$.getJSON('api/userspace/detail/id/' + bussCode, function(data){
				if(data.content && data.content.id)
					app.showSpaceDetailModal(data.content);
				else
					app.error('没有找到企业资料');
			});
		} else {
			app.error('错误!');
		}
	},
	showSpaceDetailModal: function(content) {
		var status = app.getStatus(content);
		$('#userSpaceDetailModal').showModal({
			data: content,
			tplExp: '@{([^}]*)}',
			renderer: {
				getIndustry: function(data) {
					var opts = {"make": "制造行业", "trade": "贸易行业"};
					return opts[data.industry] || "其他";
				}
			},
			shown: function(){
				var scope = $(this);
				scope.find('.x-btn-image').click(app.showImageBox);
				// 按不同状态展示
				if (status == 'UNAUDIT') {
					var btn = scope.find('.btn-submit');
					btn.show();
					btn.click({form: scope.find('form'), data: content}, app.auditSpaceDetail);
					scope.find('#auditWrap').show();
					scope.find('input[name=enable]').change(function(){
						if(0 == $(this).val()) {
							scope.find('#reasonChooseWrap').show();
							btn.addClass('x-btn-inverse');
						} else {
							scope.find('#reasonChooseWrap').hide();
							btn.removeClass('x-btn-inverse');
						}
					});
					scope.find('input[name=reason]').change(function(){
						if("other" == $(this).val()) {
							scope.find('#otherReason').show();
						} else {
							scope.find('#otherReason').hide();
						}
					});
				} else if(status == 'UNACT') {
					scope.find('.x-btn-send').click(content, app.resendMail).show();
					scope.find('.x-btn-editor').show();
					scope.find('.x-btn-editor').click(function(){
						scope.find('.x-editor-trigger').click(content, app.updateMail).show();
						scope.find('.x-form-buttom').show();
						scope.find('.x-dt').show();
					});
				} else if(status == 'UNAPPLY') {
					scope.find('#reasonWrap').show();
				} else {
					// 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 == 'userSpaceDetailModal_apps') {
								app.renderAppInfo(tab, content);
							} else if(tabId == 'userSpaceDetailModal_log') {
								
							}
						}
					});
					scope.find('.x-text-small').show();
					scope.find('#x-btn-renew').click(function() {
						// 隐藏
						scope.find('#primaryName').hide();
						scope.find('#primaryShortName').hide();
						scope.find('#primaryAdress').hide();
						scope.find('#parimaryUid').hide();
						
						// 显示
						scope.find('#renewName').show();
						scope.find('#renewShortName').show();
						scope.find('#renewAdress').show();
						scope.find('#renewUid').show();
					});
					scope.find('#x-btn-cancel').click(function() {
						// 显示
						scope.find('#primaryName').show();
						scope.find('#primaryShortName').show();
						scope.find('#primaryAdress').show();
						scope.find('#parimaryUid').show();
						
						// 隐藏
						scope.find('#renewName').hide();
						scope.find('#renewShortName').hide();
						scope.find('#renewAdress').hide();
						scope.find('#renewUid').hide();
					});
					scope.find('#x-btn-confirm').click(function() {
						var renewShortName = scope.find('input[name=renewShortName]').val();
						var renewName = scope.find('input[name=renewName]').val();
						var renewAdress = scope.find('input[name=renewAdress]').val();
						var renewUid = scope.find('input[name=renewUid]').val();
						var id = content.id;
						app.renewUserSpaceDetail(id, renewShortName, renewName, renewAdress, renewUid);
					});
				}
			}
		});
	},
	renewUserSpaceDetail: function(id, renewShortName, renewName, renewAdress, renewUid) {
		$.post('api/userspace/renewUserSpace', {
			id: id,
			renewName: renewName,
			renewShortName: renewShortName,
			renewAdress: renewAdress,
			renewUid: renewUid
		}, function(data){
			app.loading(false);
			if(data && data.errMsg) {
				app.error(data.errMsg, '修改失败', 'top-right');
			}else {
				app.info('信息修改成功，请刷新页面');
				// 显示
				scope.find('#primaryName').show();
				scope.find('#primaryShortName').show();
				scope.find('#primaryAdress').show();
				scope.find('#parimaryUid').show();
				
				//隐藏
				scope.find('#renewName').hide();
				scope.find('#renewShortName').hide();
				scope.find('#renewAdress').hide();
				scope.find('#renewUid').hide();
			}
		}, 'json');
	},
	auditSpaceDetail: function(event) {
		var form = event.data.form, content = form.serializeObject(), detail =  event.data.data, 
			data = {enable: content.enable, reason: content.reason, businessCode: detail.businessCode, id: detail.id};
		if(0 == data.enable && "other" == data.reason) {
			if(!content.otherReason) {
				app.error('请简单描述下您的理由');
				return;
			} else {
				data.reason = content.otherReason;
			}
		}
		if(1 == data.enable && !data.businessCode) {
			app.error('请先根据营业执照附件填写营业执照号');
			return;
		}
		app.loading(true);
		$.post('api/userspace/detail/audit', data, function(data){
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '审批失败', 'top-right');
			} else {
				window.location.reload();
			}
		}, 'json');
	},
	resendMail: function(event, email) {
		var data = event.data;
		email = email || data.adminEmail;
		app.loading(true);
		$.post('api/userspace/detail/send', {
			businessCode: data.businessCode,
			email: email
		}, function(data){
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '发送失败', 'top-right');
			} else {
				app.info('发送成功');
			}
		}, 'json');
	},
	updateMail: function(event, updatemail) {
		var data = event.data;
		var scope = $(this);
		var form = $(".x-form-buttom");
		var email = form.find('input[name=adEmail]').val();
		app.loading(true);
		$.post('api/userspace/detail/updateMail', {
			businessCode: data.businessCode,
			tel: data.adminTel,
			email: email
		}, function(data){
			app.loading(false);
			if(data && data.errMsg) {
				app.error(data.errMsg, '修改失败', 'top-right');
			}else {
				app.info('邮箱修改成功，请刷新页面');
			}
		}, 'json');
	},
	renderAppInfo: function(tab, detail) {
		app.getAllApps(detail, function(apps, userspaces){
			var box = tab.find("#apps");
			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">#{description}</span><span class="pull-right x-text-muted">#{uid}</span></p><div>#{fn:renderUserSpace}</div></div>', apps, {
				renderUserSpace: function(app) {
					for(var i in userspaces) {
						var us = userspaces[i];
						if(us.appId == app.uid) {
							return tmpl('<div class="x-text-muted">#{name}<span class="pull-right">#{fn:getApplyStatus}</span></div>', us, {
								getApplyStatus: function(data) {
									if (!data.dialectUID) {
										return '开通失败&nbsp;<a href="javascript:void(0);" data-app="' + app.uid + '" class="x-text-link">重新开通</a>';
									}
									return data.dialectUID;
								}
							});
						}
					}
					return '<div class="x-text-muted pull-right">未开通&nbsp;<a href="javascript:void(0);" data-app="' + app.uid + '" class="x-text-link">开通</a></div>';
				}
			});
			if(userspaces.length == 0) {
				box.next().show();
			}
			box.find('.x-text-link').click(function(){
				var appId = $(this).data('app'), businessCode = detail.businessCode;
				app.loading(true);
				if (detail.adminTel) {
					// 获取管理员信息，如果不存在，需要设置密码
					app.getUserInfo(appId, businessCode, detail.adminTel, function(data){
						if (!data) {
							var box = $('#pwd-box');
							box.show();
							box.find('.x-close-wrap').click(function(){
								app.loading(false);
								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.applyApp(appId, businessCode, f.val(), function(){
										app.renderAppInfo(tab, detail);
									});
								}
							});
						} else {
							// 开通应用
							app.applyApp(appId, businessCode, null, function(){
								app.renderAppInfo(tab, detail);
							});
						}
					});
				} else {
					// 设置管理员
				}
			});
		});
	},
	getAllApps: function(detail, callback) {
		// 获取应用开通状态
		$.getJSON('api/app/public', function(data){
			if(data.errMsg) {
				app.error(data.errMsg);
			} else {
				$.getJSON('api/userspace/' + detail.businessCode, function(data2){
					if(data2.errMsg) {
						app.error(data2.errMsg);
					} else {
						callback.call(null, data.content, data2.content);
					}
				});				
			}
		});
	},
	getUserInfo: function(appId, spaceUID, uid, callback) {
		$.getJSON('api/user/info', {
			uid: uid,
			spaceUID: spaceUID,
			appId: appId
		}, function(data){
			app.loading(false);
			if(data.errMsg) {
				app.error(data.errMsg);
			} else {
				callback.call(data.content);
			}
		});
	},
	applyApp: function(appId, businessCode, password, callback) {
		app.loading(true);
		$.getJSON('api/userspace/applyApp', {
			businessCode: businessCode,
			app: appId
		}, function(data){
			app.loading(false);
			if(data.errMsg) {
				app.error(data.errMsg);
			} else {
				callback.call(data.content);
			}
		});
	},
	//============list view===============
	showSpaceDetailList: function(params) {
		app.loading(true);
		$('.pagination').pagination({
			url: 'api/userspace/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-id="#{id}">#{fn:parseName}</a><span class="pull-right x-text-muted">#{fn:parseDate}</span></p><div class="x-text-muted">#{fn:parseBusinessCode}</div></div>', content, {
						parseName: function(data) {
							return data.name || data.shortName;
						},
						parseDate: function(data) {
							var d = data.registerDate;
							if (d) {
								return new Date(d).format('yyyy-mm-dd');
							}
							return '';
						},
						parseBusinessCode: function(data) {
							return data.businessCode || '请审批人员根据营业执照维护执照号';
						}
					});
					list.find('.x-editor-trigger').click(app.editSpaceDetail);
				}
			}
		});
	},
	searchSpaceDetail: 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.status = target.data('status');
		data.pageNumber = 1;
		app.showSpaceDetailList(data);
		$('.x-nav-tabs .active').removeClass('active');
		target.parent().addClass('active');
		$('#searchlist').hide();
		$(":text").val ("");
	},
	getStatus: function(data) {
		if (data) {
			return {310: "UNAPPLY", 311: "UNAUDIT", 312: "UNACT", 313: "ENABLED"}[data.status];
		}
		return $('.x-nav-tabs .active a').data('status');
	},
	showImageBox: function() {
		var src = $(this).data('src'), box = $('#image-box');
		if (src) {
			if (/^.*\.pdf$/i.test(src)) {
				window.open(src);
			} else {
				box.show();
				box.find('img').attr('src', src);
				box.find('a').click(function(){
					box.hide();
				});
			}
		} else {
			app.error('没有图片');
		}
	},
	//============slide-bar info===============
	showUserSpaceCount: function() {
		$.getJSON('api/userspace/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});
				});
				$('#userSpaceAppCount .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.showSpaceDetailList({
			pageNumber: 1,
			pageSize: 10, 
			status: app.getStatus()
		});
		app.showUserSpaceCount();
		$('.x-nav-tabs a').click(app.searchSpaceDetail);
		$('.btn-search').click(app.searchSpaceDetail);
		new Router({
			'#/(.+)': function(businessCode) {
				app.editSpaceDetail(null, businessCode);
			}
		}).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();
});