//总页数
var totalPage;
// 元素总数量
var totalElement;
// 当前页的元素数量
var numberOfCurrentPage;
var dataSourceQualifier = getParameter("dataSourceQualifier");
// 当前页码
var page = getParameter("page") | 1;
// 页大小
var size = getParameter("size") | 20;
// 是否为第一页
var first;
// 是否为最后一页
var last;
// 搜索框输入的内容
var searchContent;

// 用于显示正在加载的提示
var spinner;
var spinnerContainer = document.getElementById("listContainer");

listenDetails(dataSourceQualifier, page, size, searchContent);

$("#search").bind("input", search);

// 上页
$("#prev").bind("click", prevPage);

// 下页
$("#next").bind("click", nextPage);

// 手动输入页码
$("#pageIndex").keypress(function(event) {
	// 按Enter键
	if (event.keyCode == 13) {
		var value = $("#pageIndex").val();
		// 以非0开头的整数
		var regExp = /^([1-9]+\d*)$/;
		if (regExp.test(value) && value >= 1 && value <= totalPage) {
			if (value == page) {
				return;
			}
			page = value;
			listenDetails(dataSourceQualifier, page, size, searchContent);
		} else {
			$("#pageIndex").val(page);
		}
	}
});

/**
 * 请求数据
 */
function listenDetails(dataSourceQualifier, page, size, searchContent) {
	spinner = showLoading(spinner, spinnerContainer);
	$("#errorMessageContainer").attr("hidden", "true");
	$("#uploadProgress").attr("hidden", "true");
	var listenDetailsUrl = "index/listen/details?page=" + page + "&size="
			+ size;
	if (searchContent) {
		listenDetailsUrl += "&searchContent=" + searchContent;
	}
	if (dataSourceQualifier) {
		listenDetailsUrl += "&dataSourceQualifier=" + dataSourceQualifier;
	}
	$.ajax({
		type : "get",
		url : listenDetailsUrl,
		success : function(data) {
			$(".listItem").remove();
			if (!data.totalElement) {
				showErrorMessage("数量为0");
				totalPage = 0;
				totalElement = 0;
				page = 0;
				first = true;
				last = true;
			} else {
				totalPage = data.totalPage;
				totalElement = data.totalElement;
				page = data.page;
				size = data.size;
				first = data.first;
				last = data.last;
				var content = data.content;
				numberOfCurrentPage = content.length;
				for (var i = 0; i < numberOfCurrentPage; i++) {
					addList(i, content[i].tableName, content[i].ids,
							content[i].data, content[i].method,
							content[i].modifyTime, content[i].messageId)
				}
			}
			$("#totalElement").html(totalElement);
			$("#totalPage").html(totalPage);
			$("#pageIndex").val(page);
			spinner = hideLoading(spinner);
		},
		error : function(XMLHttpRequest) {
			showErrorMessageByXMLHttpRequest(XMLHttpRequest);
			spinner = hideLoading(spinner);
		}
	});
}

/**
 * 列表增加一行
 * 
 * @param i
 *            用于计算序号
 * @param tableName
 *            表名
 * @param ids
 *            ids
 * @param data
 *            data
 * @param method
 *            更改类型，INSERT、UPDATE、DELETE
 * @param modifyTime
 *            更改时间
 * @param messageId
 *            消息的id
 */
function addList(i, tableName, ids, data, method, modifyTime, messageId) {
	var listItemDiv = $("<div class='listItem'></div>");
	var noDiv = $("<div class='minWidthColumn floatLeft overflowHidden'><span>"
			+ ((page - 1) * size + i + 1) + "</span></div>");
	var tableNameDiv = $("<div class='mediumWidthColumn floatLeft overflowHidden'><span>"
			+ tableName + "</span></div>");
	var dataDiv = $("<div class='maxWidthColumn floatLeft overflowHidden'><span>"
			+ (ids || data) + "</span></div>");
	var methodDiv = $("<div class='minWidthColumn floatLeft overflowHidden'><span>"
			+ method + "</span></div>");
	var modifyTimeDiv = $("<div class='mediumWidthColumn floatLeft overflowHidden'><span>"
			+ modifyTime + "</span></div>");
	var updateButton = $("<button id='updateButton' title='插队更新索引'><i class='fa fa-refresh fa-lg' aria-hidden='true'></i></button>");
	var operationDiv = $("<div class='minWidthColumn floatLeft overflowHidden'></div>");
	operationDiv.append(updateButton);

	if (i % 2 == 0) {
		listItemDiv.css("background-color", "#e0e0e0");
		updateButton.css("background-color", "#e0e0e0");
	}

	listItemDiv.append(noDiv);
	listItemDiv.append(tableNameDiv);
	listItemDiv.append(dataDiv);
	listItemDiv.append(methodDiv);
	listItemDiv.append(modifyTimeDiv);
	listItemDiv.append(operationDiv);
	$('#listContentContainer').append(listItemDiv);

	updateButton.click(function() {
		updateIndex(tableName, ids, data, method, messageId, listItemDiv);
	});
}

/**
 * 强制更新索引
 * 
 * @param tableName
 *            表名
 * @param ids
 *            ids
 * @param data
 *            data
 * @param method
 *            需对索引做何种更改
 * @param messageId
 *            消息的id
 * @param listItemDiv
 *            所在行
 */
function updateIndex(tableName, ids, data, method, messageId, listItemDiv) {
	spinner = showLoading(spinner, spinnerContainer);
	var params = {
		"tableName" : tableName,
		"method" : method,
	};
	if (ids) {
		params.ids = ids.substring(1, ids.length - 1);
	}
	if (data) {
		params.data = data;
	}
	$.ajax({
		type : "post",
		url : "index/maintain",
		data : params,
		success : function(result) {
			// 更新索引后，出队消息
			dequeueMessage(dataSourceQualifier, messageId, listItemDiv);
		},
		error : function(XMLHttpRequest) {
			showErrorMessageByXMLHttpRequest(XMLHttpRequest);
			spinner = hideLoading(spinner);
		}
	});
}

/**
 * 出队消息
 * 
 * @param messageId
 *            消息的id
 * @param listItemDiv
 *            所在行
 */
function dequeueMessage(dataSourceQualifier, messageId, listItemDiv) {
	var dequeueMessageUrl = "index/dequeue?messageId=" + messageId;
	if (dataSourceQualifier) {
		dequeueMessageUrl += "&dataSourceQualifier=" + dataSourceQualifier;
	}
	$.ajax({
		type : "get",
		url : dequeueMessageUrl,
		success : function(data) {
			listItemDiv.remove();
			totalElement--;
			numberOfCurrentPage--;
			$("#totalElement").html(totalElement);
			if (!numberOfCurrentPage) {
				if (last) {
					page--;
				}
				listenDetails(dataSourceQualifier, page, size, searchContent);
			}
			spinner = hideLoading(spinner);
		},
		error : function(XMLHttpRequest) {
			showErrorMessageByXMLHttpRequest(XMLHttpRequest);
			spinner = hideLoading(spinner);
		}
	});
}

/**
 * 对消息进行搜索
 */
function search() {
	console.log(this.value);
	searchContent = this.value;
	page = 1;
	listenDetails(dataSourceQualifier, page, size, searchContent);
}

/**
 * 预览前一页
 */
function prevPage() {
	if (first) {
		return;
	}
	page--;
	listenDetails(dataSourceQualifier, page, size, searchContent);
}

/**
 * 预览后一页
 */
function nextPage() {
	if (last) {
		return;
	}
	page++;
	listenDetails(dataSourceQualifier, page, size, searchContent);
}

/**
 * 显示请求返回的错误信息
 * 
 * @param XMLHttpRequest
 */
function showErrorMessageByXMLHttpRequest(XMLHttpRequest) {
	// 处理后台传输的自定义的换行标志
	var result = JSON.parse(XMLHttpRequest.responseText);
	var message = result.message;
	if (!message) {
		message = result;
	}
	console.log(message);
	var detailedMessage = result.detailedMessage;
	showErrorMessage(message, detailedMessage);
}

/**
 * 显示错误信息
 * 
 * @param message
 *            简要错误信息
 * @param detailedMessage
 *            详细错误信息
 */
function showErrorMessage(message, detailedMessage) {
	$("#errorMessageContainer").removeAttr("hidden");
	$("#message").html(message);
	if (detailedMessage) {
		$("#detailedMessageButton").removeAttr("hidden");
	}
	$("#detailedMessageButton").click(function() {
		$("#detailedMessage").html(detailedMessage);
		$("#detailedMessage").removeAttr("hidden");
	});
}
