<template>
	<div class="file-table-wrapper">
		<!-- 文件表格 -->
		<a-table
			class="file-table"
			:class="['file-type-' + fileType, routeName === 'Share' ? 'share' : '']"
			ref="multipleTableRef"
			:loading="loading"
			:data-source="fileList"
			:columns="columns"
			:row-key="(record) => record.userFileId"
			:row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
			:pagination="false"
			:custom-row="customRow"
			@change="handleTableChange"
		>
			<template #bodyCell="{ column, record, index }">
				<template v-if="column.key === 'isDir'">
					<video
						style="width: 30px; max-height: 30px; cursor: pointer"
						v-if="$file.isVideoFile(record)"
						:src="$file.setFileImg(record)"
					></video>
					<img
						:src="$file.setFileImg(record)"
						:title="`${record.isDir || fileType == '6' ? '' : '点击预览'}`"
						style="width: 30px; max-height: 30px; cursor: pointer"
						@click="$file.handleFileNameClick(record, index, sortedFileList)"
						v-else
					/>
				</template>
				<template v-else-if="column.key === 'fileName'">
					<span @click="$file.handleFileNameClick(record, index, sortedFileList)">
						<span
							class="file-name"
							style="cursor: pointer"
							:title="`${record.isDir || fileType == '6' ? '' : '点击预览'}`"
							v-html="$file.getFileNameComplete(record, true)"
						></span>
						<div class="file-info" v-if="screenWidth <= 768">
							{{ record.uploadTime }}
							<span class="file-size">
								{{ record.isDir === 0 ? $file.calculateFileSize(record.fileSize) : '' }}
							</span>
						</div>
					</span>
				</template>
				<template v-else-if="column.key === 'filePath'">
					<span
						style="cursor: pointer"
						title="点击跳转"
						@click="
							() => {
								// router.push({
								// 	query: { filePath: record.filePath, fileType: 0 }
								// })
								myResourceStore.changeQuery({ filePath: record.filePath, fileType: 0 })
							}
						"
						>{{ record.filePath }}</span
					>
				</template>
				<template v-else-if="column.key === 'extendName'">
					<span>{{ $file.getFileType(record) }}</span>
				</template>
				<template v-else-if="column.key === 'fileSize'">
					{{ record.isDir === 0 ? $file.calculateFileSize(record.fileSize) : '' }}
				</template>
				<template v-else-if="column.key === 'shareType'">
					{{ record.shareType === 1 ? '私密' : '公共' }}
				</template>
				<template v-else-if="column.key === 'endTime'">
					<div>
						<WarningOutlined v-if="$file.getFileShareStatus(record.endTime)" />
						<ClockCircleOutlined v-else />
						{{ record.endTime }}
					</div>
				</template>
				<template v-else-if="column.key === 'operation'">
					<MoreOutlined
						class="file-operate"
						:class="`operate-more-${index}`"
						@click="handleClickMore(record, $event)"
					/>
				</template>
			</template>
		</a-table>
	</div>
</template>

<script setup>
	import { ref, computed, watch, onMounted } from 'vue'
	import { useRoute, useRouter } from 'vue-router'
	import { storeToRefs } from 'pinia'
	import { useMyResourceStore } from '@/store/myResource'
	import {
		WarningOutlined,
		ClockCircleOutlined,
		MoreOutlined,
		PlusCircleOutlined,
		MinusCircleOutlined
	} from '@ant-design/icons-vue'
	const props = defineProps({
		// 文件类型
		fileType: {
			required: true,
			type: Number
		},
		// 文件路径
		filePath: {
			required: true,
			type: String
		},
		// 文件列表
		fileList: {
			required: true,
			type: Array
		},
		// 文件加载状态
		loading: {
			required: true,
			type: Boolean
		}
	})
	const emit = defineEmits(['getTableDataByType'])

	const route = useRoute()
	const router = useRouter()
	const myResourceStore = useMyResourceStore()
	const { proxy } = getCurrentInstance()

	const multipleTableRef = ref(null)
	const officeFileType = ref(['ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'])
	const sortedFileList = ref([]) //  排序后的表格数据
	const selectedRowKeys = ref([])
	const { getSelectedColumnList } = storeToRefs(myResourceStore)
	const selectedColumnList = computed({
		get: () => getSelectedColumnList.value
	})

	// 路由名称
	const routeName = computed(() => route.name)
	// 屏幕宽度
	const screenWidth = computed(() => myResourceStore.screenWidth)

	// 定义表格列
	const columns = computed(() => {
		const cols = [
			{
				dataIndex: 'isDir',
				key: 'isDir',
				width: screenWidth.value <= 768 ? 40 : 56,
				align: 'center',
				className: 'file-icon-column'
			},
			{
				title: '文件名',
				dataIndex: 'fileName',
				key: 'fileName',
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return a.fileName.localeCompare(b.fileName)
				},
				showOverflowTooltip: true
			}
		]
		// if (![0, 8].includes(Number(route.query.fileType)) && routeName.value !== 'Share' && screenWidth.value > 768) {
		if (
			![0, 8].includes(Number(myResourceStore.getQuery.fileType ? myResourceStore.getQuery.fileType : 0)) &&
			routeName.value !== 'Share' &&
			screenWidth.value > 768
		) {
			cols.push({
				title: props.fileType === 6 ? '原路径' : '路径',
				dataIndex: 'filePath',
				key: 'filePath',
				showOverflowTooltip: true
			})
		}

		if (selectedColumnList.value.includes('extendName') && screenWidth.value > 768) {
			cols.push({
				title: '类型',
				dataIndex: 'extendName',
				key: 'extendName',
				width: 80,
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return a.extendName.localeCompare(b.extendName)
				},
				showOverflowTooltip: true
			})
		}

		if (selectedColumnList.value.includes('fileSize') && screenWidth.value > 768) {
			cols.push({
				title: '大小',
				dataIndex: 'fileSize',
				key: 'fileSize',
				width: 100,
				align: 'right',
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return a.fileSize - b.fileSize
				}
			})
		}

		if (
			selectedColumnList.value.includes('uploadTime') &&
			![7, 8].includes(props.fileType) &&
			!['Share'].includes(routeName.value) &&
			screenWidth.value > 768
		) {
			cols.push({
				title: '修改日期',
				dataIndex: 'uploadTime',
				key: 'uploadTime',
				width: 160,
				align: 'center',
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return new Date(a.uploadTime).getTime() - new Date(b.uploadTime).getTime()
				}
			})
		}

		if (props.fileType === 6 && selectedColumnList.value.includes('deleteTime') && screenWidth.value > 768) {
			cols.push({
				title: '删除日期',
				dataIndex: 'deleteTime',
				key: 'deleteTime',
				width: 160,
				align: 'center',
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return new Date(a.deleteTime).getTime() - new Date(b.deleteTime).getTime()
				}
			})
		}

		if (props.fileType === 8 && screenWidth.value > 768) {
			cols.push({
				title: '分享类型',
				dataIndex: 'shareType',
				key: 'shareType',
				width: 100,
				align: 'center'
			})
			cols.push({
				title: '分享时间',
				dataIndex: 'shareTime',
				key: 'shareTime',
				width: 160,
				showOverflowTooltip: true,
				align: 'center',
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return new Date(a.shareTime).getTime() - new Date(b.shareTime).getTime()
				}
			})
			cols.push({
				title: '过期时间',
				dataIndex: 'endTime',
				key: 'endTime',
				width: 190,
				showOverflowTooltip: true,
				align: 'center',
				sorter: (a, b) => {
					if (a.isDir !== b.isDir) return b.isDir - a.isDir
					return new Date(a.endTime).getTime() - new Date(b.endTime).getTime()
				}
			})
		}

		if (screenWidth.value <= 768) {
			cols.push({
				title: '',
				dataIndex: 'operation',
				key: 'operation',
				width: 48
			})
		}

		return cols
	})

	watch(
		() => props.filePath,
		() => {
			clearSelectedTable()
			// Ant Design Vue Table 没有 clearSort 方法，需要手动处理排序状态
			// multipleTableRef.value.clearSort();
		}
	)

	watch(
		() => props.fileType,
		() => {
			clearSelectedTable()
			// multipleTableRef.value.clearSort();
		}
	)

	watch(
		() => props.fileList,
		() => {
			clearSelectedTable()
			// multipleTableRef.value.clearSort();
			sortedFileList.value = props.fileList
		}
	)
	// 当表格的排序条件发生变化的时候会触发该事件
	const handleTableChange = (pagination, filters, sorter) => {
		// Ant Design Vue 的 sorter 返回的是当前排序的列信息，需要根据实际情况更新 sortedFileList
		// 这里简化处理，如果需要前端排序，可以根据 sorter.field 和 sorter.order 对 fileList 进行排序
		sortedFileList.value = multipleTableRef.value.tableData
	}

	// 表格某一行右键事件
	const customRow = (record, index) => {
		return {
			onContextmenu: (event) => {
				// 阻止右键事件冒泡
				event.cancelBubble = true
				// xs 以上的屏幕
				if (screenWidth.value > 768) {
					event.preventDefault()
					// Ant Design Vue Table 没有 setCurrentRow 方法，需要手动处理选中状态
					// multipleTableRef.value.setCurrentRow(record);
					proxy.$openBox
						.contextMenu({
							selectedFile: record,
							domEvent: event,
							serviceEl: proxy
						})
						.then((res) => {
							// multipleTableRef.value.setCurrentRow(); //  取消当前选中行
							if (res === 'confirm') {
								emit('getTableDataByType') //  刷新文件列表
								myResourceStore.showStorage() //  刷新存储容量
							}
						})
				}
			}
		}
	}

	// 清空表格已选行
	const clearSelectedTable = () => {
		selectedRowKeys.value = []
		myResourceStore.changeSelectedFiles([])
		myResourceStore.changeIsBatchOperation(false)
	}

	const onSelectChange = (changableRowKeys) => {
		selectedRowKeys.value = changableRowKeys
		const list = changableRowKeys.map((id) => props.fileList.find((file) => file.userFileId === id)).filter(Boolean)
		myResourceStore.changeSelectedFiles(list)
		myResourceStore.changeIsBatchOperation(changableRowKeys.length !== 0)
	}
	// 更多图标点击事件
	const handleClickMore = (record, event) => {
		// multipleTableRef.value.setCurrentRow(record); //  选中当前行
		proxy.$openBox
			.contextMenu({
				selectedFile: record,
				domEvent: event
			})
			.then((res) => {
				// multipleTableRef.value.setCurrentRow(); //  取消当前选中行
				if (res === 'confirm') {
					emit('getTableDataByType') //  刷新文件列表
					myResourceStore.showStorage() //  刷新存储容量
				}
			})
	}

	// 暴露方法给父组件
	defineExpose({
		clearSelectedTable
	})
</script>

<style lang="less" scoped>
	@import '@/style/myResource/varibles.less';
	@import '@/style/myResource/mixins.less';

	.file-table-wrapper {
		margin-top: 2px;
		.file-type-0 {
			height: calc(100vh - 206px) !important;
			:deep(.ant-table-body) {
				height: calc(100vh - 262px) !important;
			}
		}
		.file-type-6 {
			height: calc(100vh - 211px) !important;
			:deep(.ant-table-body) {
				height: calc(100vh - 263px) !important;
			}
		}
		.file-table.share {
			height: calc(100vh - 109px) !important;
			:deep(.ant-table-body) {
				height: calc(100vh - 161px) !important;
			}
		}
		.file-table {
			width: 100% !important;
			height: calc(100vh - 203px);
			:deep(.ant-table-thead) {
				th {
					// background: @tabBackColor; // 需要在 varibles.less 中定义
					padding: 4px 0;
					color: @RegularText; // 需要在 varibles.less 中定义
				}
				.anticon-plus-circle,
				.anticon-minus-circle {
					margin-left: 6px;
					cursor: pointer;
					font-size: 16px;
					&:hover {
						color: @Primary; // 需要在 varibles.less 中定义
					}
				}
			}
			:deep(.ant-table-body) {
				height: calc(100vh - 255px);
				overflow-y: auto;
				// setScrollbar(6px, transparent, #C0C4CC); // 需要在 mixins.less 中定义
				td {
					padding: 8px 0;
					.file-name {
						.keyword {
							color: @Danger; // 需要在 varibles.less 中定义
						}
					}
				}
				.anticon-warning {
					font-size: 16px;
					color: @Warning; // 需要在 varibles.less 中定义
				}
				.anticon-clock-circle {
					font-size: 16px;
					color: @Success; // 需要在 varibles.less 中定义
				}
			}
		}
	}
	.right-menu-list {
		position: fixed;
		display: flex;
		flex-direction: column;
		background: #fff;
		border: 1px solid @BorderLighter; // 需要在 varibles.less 中定义
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		z-index: 2;
		padding: 4px 0;
		color: @RegularText; // 需要在 varibles.less 中定义
		.right-menu-item,
		.unzip-item {
			padding: 0 16px;
			height: 36px;
			line-height: 36px;
			cursor: pointer;
			&:hover {
				background: @PrimaryHover; // 需要在 varibles.less 中定义
				color: @Primary; // 需要在 varibles.less 中定义
			}
			i {
				margin-right: 8px;
			}
		}
		.unzip-menu-item {
			position: relative;
			&:hover {
				.unzip-list {
					display: block;
				}
			}
			.unzip-list {
				position: absolute;
				display: none;
				.unzip-item {
					width: 200px;
					// setEllipsis(1); // 需要在 mixins.less 中定义
				}
			}
		}
	}
	.right-menu-list,
	.unzip-list {
		background: #fff;
		border: 1px solid @BorderLighter; // 需要在 varibles.less 中定义
		border-radius: 4px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		z-index: 2;
		padding: 4px 0;
		color: @RegularText; // 需要在 varibles.less 中定义
	}
</style>
