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('partnership/receivedRequest/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);
				// 按不同状态展示
				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 == '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') {
								
							}
						}
					});
				}
			}
		});
	},
	auditSpaceDetail: function(event) {
		var form = event.data.form, content = form.serializeObject(), detail =  event.data.data, 
			data = {enable: content.enable, reason: content.otherReason, id: detail.id};
		if(0 == data.enable) {
			if(!content.otherReason) {
				app.error('请简单描述下您的理由');
				return;
			} else {
				data.reason = content.otherReason;
			}
		}
		app.loading(true);
		$.post('partnership/receivedRequest/audit', data, function(data){
			app.loading(false);
			if (data && data.errMsg) {
				app.error(data.errMsg, '审批失败', 'top-right');
			} else {
				window.location.reload();
			}
		}, 'json');
	},
	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);
			}
		});
	},
	//============list view===============
	showSpaceDetailList: function(params) {
		app.loading(true);
		$('.pagination').pagination({
			url: 'partnership/receivedRequest/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="x-text-muted">（#{fn:parseBusinessCode}）</span><span class="pull-right x-text-muted">#{fn:parseDate}</span></p><div class="x-text-muted">#{fn:parseCustUserName} （#{fn:parseCustUserTel}）</div></div>', content, {
						parseName: function(data) {
							return data.custName;
						},
						parseDate: function(data) {
							var d = data.requestDate;
							if (d) {
								return new Date(d).format('yyyy-mm-dd');
							}
							return '';
						},
						parseBusinessCode: function(data) {
							return data.custUID;
						},
						parseCustUserName: function(data) {
							return data.custUserName;
						},
						parseCustUserTel: function(data) {
							return data.custUserTel;
						}
					});
					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", 313: "ENABLED"}[data.statusCode];
		}
		return $('.x-nav-tabs .active a').data('status');
	},
	//============slide-bar info===============
	showUserSpaceCount: function() {
		$.getJSON('partnership/receivedRequest/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();
});