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

// 获取链接中的filePath参数，如果存在，则表示进入指定的绝对路径
var filePathParameter = getParameter("filePath");
// 是否显示上传按钮（默认显示）
// var showUpload = getParameter("showUpload");
var showUpload = true;
// 是否显示删除按钮
var showDelete = getParameter("showDelete");
var currentPath = new Object();
// 如果不存在filePath参数，表示进入相对路径（相对于所配置的本地资源根路径）
currentPath.value = filePathParameter || "/";

listFiles(currentPath.value);

$("#parentPath").click(function() {
	var parent = currentPath.parent;
	if (parent) {
		currentPath = parent;
		listFiles(currentPath.value);
	}
});

$("#uploadButton").click(function() {
	var uploadUrl = "file/upload";
	var params = new Object();
	// 传递参数
	params.filePath = currentPath.value;
	if (filePathParameter) {
		params.isAbsolutePath = true;
	}
	var fileInvalid = upload({
		url : uploadUrl,
		multiple : true,// 是否上传多个文件
		maxSize : 1000,// 单个文件大小的上限（MB）
		params : params,// 其他参数
		success : function(data) {
			console.log(data);
			spinner = hideLoading(spinner);
			alert(spinnerContainer, "上传成功");
			listFiles(currentPath.value);
		},
		error : function(xhr) {
			console.log(xhr);
			spinner = hideLoading(spinner);
			alert(spinnerContainer, "上传失败");
			// 此时可能上传的多个文件中，有部分上传成功，所以需要重新加载
			listFiles(currentPath.value);
		},
		showLoading : function() {
			spinner = showLoading(spinner, spinnerContainer);
		},
		onprogress : function(progress) {
			$("#uploadProgress").removeAttr("hidden");
			$("#uploadProgress").text(progress + "%");
		}
	});
});

/**
 * 请求文件信息
 * 
 * @param path
 *            文件路径
 */
function listFiles(path) {
	console.log("listFiles... " + JSON.stringify(currentPath));
	$("#errorMessageContainer").attr("hidden", "true");
	$("#uploadProgress").attr("hidden", "true");
	$("#currentPath").text(currentPath.value);
	if (!currentPath.parent) {
		$("#parentPathContainer").attr("hidden", "true");
	} else {
		$("#parentPathContainer").removeAttr("hidden");
	}
	var listFilesUrl = "file/listFiles";
	if (path) {
		listFilesUrl += "?filePath=" + path;
	}
	// 如果链接中指定路径，则表示请求的绝对路径
	if (filePathParameter) {
		listFilesUrl += "&isAbsolutePath=true";
	}
	$.ajax({
		type : "get",
		url : listFilesUrl,
		success : function(data) {
			$(".listItem").remove();
			if (!data.length) {
				showErrorMessage("文件数量为0");
			} else {
				// 如果在参数中指定显示上传按钮，则不再隐藏
				if (showUpload) {
					$("#uploadContainer").removeAttr("hidden");
				}
				for (var i = 0; i < data.length; i++) {
					addList(data[i].name, data[i].size, data[i].lastModified,
							data[i].filePath, data[i].isDirectory);
				}
			}
		},
		error : function(XMLHttpRequest) {
			showErrorMessageByXMLHttpRequest(XMLHttpRequest);
		}
	});
}

/**
 * 文件列表增加一行
 * 
 * @param name
 *            文件名称
 * @param size
 *            文件大小
 * @param lastModified
 *            文件最近修改时间
 * @param filePath
 *            文件相对路径
 * @param isDirectory
 *            是否为文件夹
 */
function addList(name, size, lastModified, filePath, isDirectory) {
	if (size && size >= 0) {
		if (size < 1024) {
			size += " B";
		} else if (size < 1024 * 1024) {
			size = (size / 1024).toFixed(2) + " KB";
		} else if (size < 1024 * 1024 * 1024) {
			size = (size / 1024 / 1024).toFixed(2) + " MB";
		} else {
			size = (size / 1024 / 1024 / 1024).toFixed(2) + " GB";
		}
	} else {
		size = "...";
	}
	// 显示文件、文件夹图标
	var fileIcon;
	if (isDirectory) {
		fileIcon = "fa fa-folder-open-o";
	} else {
		fileIcon = "fa fa-file-o";
	}

	var listItemDiv = $("<div class='listItem'></div>");
	var nameDiv = $("<div class='columnName overflowHidden'><i class='"
			+ fileIcon
			+ "' aria-hidden='true'></i>&nbsp&nbsp&nbsp&nbsp<span class='likeHref'>"
			+ name + "</span></div>");
	var sizeDiv = $("<div class='columnSize overflowHidden'><span>" + size
			+ "</span></div>");
	var lastModifiedDiv = $("<div class='columnLastModified overflowHidden'><span>"
			+ lastModified + "</span></div>");

	var downloadButton = $("<button id='downloadButton' title='下载'><i class='fa fa-cloud-download fa-lg' aria-hidden='true'></i></button>");
	var deleteButton = $("<button id='deleteButton' title='删除'><i class='fa fa-trash fa-lg' aria-hidden='true'></i>");
	var operationDiv = $("<div class='columnOperation' overflowHidden></div>");
	operationDiv.append(downloadButton);

	listItemDiv.append(nameDiv);
	listItemDiv.append(sizeDiv);
	listItemDiv.append(lastModifiedDiv);
	listItemDiv.append(operationDiv);
	$('#listContentContainer').append(listItemDiv);

	nameDiv.click(function() {
		if (isDirectory) {
			// 记录父目录
			var pathCopy = currentPath;
			currentPath = new Object();
			currentPath.value = filePath;
			currentPath.parent = pathCopy;
			listFiles(currentPath.value);
		} else {
			download(filePath);
		}
	});

	downloadButton.click(function() {
		download(filePath);
	});

	if (showDelete) {
		operationDiv.append(deleteButton);
		deleteButton.click(function() {
			deleteFile(filePath, listItemDiv);
		});
	}
}

/**
 * 下载文件（夹）
 * 
 * @param path
 *            文件（夹）路径
 */
function download(path) {
	var downloadUrl = "file/download?filePath=" + path;
	// 如果链接中指定路径，则表示请求的绝对路径
	if (filePathParameter) {
		downloadUrl += "&isAbsolutePath=true";
	}
	window.open(downloadUrl);
}

/**
 * 删除文件
 * 
 * @param path
 */
function deleteFile(path, listItemDiv) {
	spinner = showLoading(spinner, spinnerContainer);
	var deleteUrl = "file/delete?filePath=" + path;
	// 如果链接中指定路径，则表示请求的绝对路径
	if (filePathParameter) {
		deleteUrl += "&isAbsolutePath=true";
	}
	$.ajax({
		type : "get",
		url : deleteUrl,
		success : function(data) {
			listItemDiv.remove();
			spinner = hideLoading(spinner);
			alert(spinnerContainer, "删除成功");
		},
		error : function(XMLHttpRequest) {
			if (XMLHttpRequest.status == 403) {
				alert(spinnerContainer,
						JSON.parse(XMLHttpRequest.responseText).message);
			} else {
				showErrorMessageByXMLHttpRequest(XMLHttpRequest);
			}
			spinner = hideLoading(spinner);
		}
	});
}

/**
 * 显示请求返回的错误信息
 * 
 * @param XMLHttpRequest
 */
function showErrorMessageByXMLHttpRequest(XMLHttpRequest) {
	// 处理后台传输的自定义的换行标志
	var result = JSON.parse(XMLHttpRequest.responseText);
	var message = result.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");
	});
}
