<template>
	<!-- 解压缩文件 -->
	<a-modal
		title="解压缩文件"
		:visible="internalVisible"
		:maskClosable="false"
		@ok="handleDialogSure"
		@cancel="handleDialogClose"
		:afterClose="handleDialogClose"
	>
		<div class="unzip-tree-wrapper" v-if="unzipMode === 2">
			<!-- 选择的目标路径 -->
			<div class="target-path">
				<span class="label">目标路径：</span>
				<a-input class="content" v-model:value="targetPath" readonly size="small"></a-input>
			</div>
			<!-- 文件目录树 -->
			<a-spin :spinning="loading">
				<a-tree
					:tree-data="fileTree"
					:field-names="{ children: 'children', title: 'label', key: 'id' }"
					highlight-current
					:expandedKeys="defaultExpandedKeys"
					@update:expandedKeys="(val) => (defaultExpandedKeys = val)"
					@select="handleNodeClick"
					:showLine="true"
				>
					<template #title="{ dataRef }">
						<span class="custom-tree-node">
							<span class="label">{{ dataRef.label }}</span>
							<a-button class="add-folder-btn" type="link" size="small" @click.stop="handleAddFolderBtnClick(dataRef)">
								新建文件夹
							</a-button>
						</span>
					</template>
				</a-tree>
			</a-spin>
		</div>
		<div class="unzip-text" v-else><a-spin /> 正在解压缩，请稍等片刻...</div>
		<template #footer>
			<div v-if="unzipMode === 2">
				<a-button @click="handleDialogClose">取 消</a-button>
				<a-button type="primary" :loading="sureBtnLoading" @click="handleDialogSure">确 定</a-button>
			</div>
		</template>
	</a-modal>
</template>

<script setup>
	import { ref, getCurrentInstance, watch } from 'vue'
	import { getFoldTree, unzipFile } from '@/api/myResource/file'
	import { message } from 'ant-design-vue'

	const { proxy } = getCurrentInstance()

	const props = defineProps({
		visible: {
			type: Boolean,
			default: false
		},
		unzipMode: {
			type: Number,
			default: 0
		},
		userFileId: {
			type: String,
			default: ''
		},
		callback: Function
	})

	const emit = defineEmits(['update:visible'])
	const internalVisible = ref(props.visible) // 使用 internalVisible 作为主要的响应式状态
	const targetPath = ref('/') //  目标路径
	const fileTree = ref([]) //  文件夹目录树
	const loading = ref(false) //  文件夹目录树 loading 状态
	const defaultExpandedKeys = ref([])
	const sureBtnLoading = ref(false) //  确定按钮 loading 状态

	watch(
		internalVisible, // 监听内部的 internalVisible ref
		(newVal, oldVal) => {
			if (newVal && !oldVal) {
				// 仅在从 false 变为 true 时调用，即对话框打开时
				handleDialogOpen()
			}
		}
	)

	// 如果父组件通过 prop 更新 visible，也需要同步到 internalVisible
	watch(
		() => props.visible,
		(newVal) => {
			internalVisible.value = newVal
		}
	)

	/**
	 * 取消按钮点击事件 & 对话框关闭的回调
	 */
	const handleDialogClose = () => {
		internalVisible.value = false
		emit('update:visible', false) // 更新父组件的 visible 值
		props.callback('cancel')
	}

	/**
	 * 对话框打开的回调
	 */
	const handleDialogOpen = () => {
		if (props.unzipMode === 2) {
			initFileTree()
		} else {
			handleUnzipFile()
		}
	}

	/**
	 * 初始化文件目录树
	 */
	const initFileTree = async (id) => {
		loading.value = true
		try {
			const res = await getFoldTree()
			if (res.success) {
				fileTree.value = [res.data]
				defaultExpandedKeys.value = id ? [id] : fileTree.value.length > 0 ? [fileTree.value[0].id] : []
			} else {
				message.error(res.message)
			}
		} catch (error) {
			message.error('获取文件夹树失败')
			console.error(error)
		} finally {
			loading.value = false
		}
	}

	/**
	 * 目录树节点点击回调函数
	 * @param {Array} selectedKeys 当前选中的节点的 key
	 * @param {object} e event 对象，包含 {selected: bool, selectedNodes, node, event}
	 */
	const handleNodeClick = (selectedKeys, e) => {
		if (e.node && e.node.dataRef) {
			targetPath.value = e.node.dataRef.filePath ? e.node.dataRef.filePath : '/'
		}
	}

	/**
	 * 新建文件夹按钮点击事件
	 * @description 调用新建文件夹服务，并在弹窗确认回调事件中刷新文件夹树
	 */
	const handleAddFolderBtnClick = async (data) => {
		try {
			await proxy.$openDialog.addFolder({
				filePath: data.filePath || '/'
			})
			initFileTree(data.id)
		} catch (error) {
			console.log('Add folder cancelled or failed', error)
		}
	}

	/**
	 * 确定按钮点击事件
	 * @description 调用移动文件接口
	 */
	const handleDialogSure = () => {
		sureBtnLoading.value = true
		handleUnzipFile()
	}

	/**
	 * 解压文件
	 */
	const handleUnzipFile = async () => {
		// unzipMode 解压模式 0-解压到当前文件夹， 1-自动创建该文件名目录，并解压到目录里， 2-手动选择解压目录
		let reqData = {
			unzipMode: props.unzipMode,
			userFileId: props.userFileId
		}
		if (props.unzipMode === 2) {
			reqData = {
				...reqData,
				filePath: targetPath.value //  解压的目标路径
			}
		}

		try {
			const res = await unzipFile(reqData)
			sureBtnLoading.value = false
			if (res.success) {
				message.success('解压成功')
				internalVisible.value = false
				emit('update:visible', false)
				props.callback('confirm')
			} else {
				message.error(res.message)
			}
		} catch (error) {
			sureBtnLoading.value = false
			message.error('解压失败')
			console.error(error)
		}
	}

	// 暴露给模板或者父组件（如果需要ref访问）
	defineExpose({
		visible: internalVisible // 暴露 internalVisible
	})
</script>

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

	// 使用 :deep 替代 >>>
	:deep(.ant-modal) {
		.ant-modal-header {
			display: flex;
		}

		.ant-modal-body {
			padding: 10px 30px;

			.unzip-tree-wrapper {
				height: 300px;
				overflow: auto;
				&::-webkit-scrollbar {
					width: 6px;
				}
				&::-webkit-scrollbar-thumb {
					background: #ccc; // 滚动条颜色
					border-radius: 3px;
				}
				&::-webkit-scrollbar-track {
					background: #f1f1f1; // 轨道颜色
				}

				.target-path {
					display: flex;
					align-items: center;
					margin-bottom: 10px;

					.label {
						width: 80px;
						flex-shrink: 0;
					}

					.content {
						flex: 1;
					}
				}

				.ant-tree {
					.ant-tree-treenode {
						width: 100%;
						// antd v4+ 使用 .ant-tree-treenode
						.ant-tree-node-content-wrapper {
							height: 34px;
							font-size: 16px;
							display: flex;
							align-items: center;
						}
						&:hover {
							.add-folder-btn {
								display: inline-block;
							}
						}

						.ant-tree-switcher .ant-tree-switcher-icon svg {
							font-size: 18px;
						}

						.custom-tree-node {
							flex: 1;
							display: flex;
							align-items: center;
							justify-content: space-between;
							font-size: 14px;
							padding-right: 8px;

							.add-folder-btn {
								color: #000000;
								display: none;
								margin-left: 8px;
							}
						}
					}
				}
			}
			.unzip-text {
				padding: 40px 0 64px 0;
				text-align: center;
			}
		}
	}

	:deep(.ant-tree .ant-tree-treenode .custom-tree-node) {
		display: flex;
		justify-content: space-between;
		width: 100%;
	}

	:deep(.ant-tree .ant-tree-treenode:hover .custom-tree-node .add-folder-btn) {
		color: @primary-color !important;
		display: inline-block !important;
	}

	:deep(.ant-tree .ant-tree-treenode .custom-tree-node .add-folder-btn) {
		color: #000000;
		display: none !important;
		margin-left: 8px;
	}

	:deep(.ant-tree) {
		.ant-tree-treenode,
		.ant-tree-node-content-wrapper,
		.ant-tree-title {
			width: 100%;
		}
	}
</style>
