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) {
		$('#userSpaceDetailModal').showModal({
			data: content,
			tplExp: '@{([^}]*)}',
			renderer: {
				getIndustry: function(data) {
					var opts = {"make": "制造行业", "trade": "贸易行业"};
					return opts[data.industry] || "其他";
				}
			},
			shown: function(){
				var scope = $(this);
					var btn = scope.find('.btn-submit');
					btn.show();
					btn.click({form: scope.find('form'), data: content}, app.auditSpaceDetail);
					scope.find('#auditWrap').show();
					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') {
								
							}
						}
					});
			}
		});
	},
	auditSpaceDetail: function(event) {
		var form = event.data.form, content = form.serializeObject(), detail =  event.data.data, 
			data = {id: detail.id};
		app.loading(true);
		$.post('partnership/sendRequest', data, function(data) {
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '请求发送失败', 'top-right');
			} else {
				window.location.reload();
			}
		}, 'json');
	},
	sendRequest : function(data) {
		data = {id: data};
		app.loading(true);
		$.post('partnership/sendRequest', data, function(data) {
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '请求发送失败', 'top-right');
			} else {
				window.location.reload();
			}
		}, 'json');
	},
	//============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 class="x-text-muted">企业状态：#{fn:parseStatus}<span class="pull-right x-text-muted"><a class="btn btn-default btn-addCust" onclick="app.sendRequest(#{id})" title="添加合作伙伴">添加</a></span></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;
						},
						parseStatus: function(data) {
							if(data.status == 311) {
								data.status = "申请中";
							} else if(data.status == 310) {
								data.status = "未启用";
							} else if(data.status == 312) {
								data.status = "未开通";
							} else if(data.status == 313) {
								data.status = "已开通";
							}
							return data.status;
						}
					});
					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.pageNumber = 1;
		app.showSpaceDetailList(data);
		$('.x-nav-tabs .active').removeClass('active');
		target.parent().addClass('active');
		$('#searchlist').hide();
		$(":text").val ("");
	},
	getStatus: function(data) {
		return $('.x-nav-tabs .active a').data('status');
	},
	//============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);
		$('.x-btn-search').click(function() {
			$('#searchlist').toggle();
		});
		new Router({
			'#/(.+)': function(businessCode) {
				app.editSpaceDetail(null, businessCode);
			}
		}).start();
		// 监听Enter键
		$(function() { 
			var $inp=$('input');
			$inp.keypress(function(e){
		    var key=e.which;
		    if(key==13) {
		    	$('.btn-search').click();
		    }
		  }) 
		});
	}
};
$(document).ready(function() {
	app.init();
});