<template>
	<!-- 查看他人的分享时，保存文件到个人网盘 -->
	<a-modal
		title="保存文件到网盘"
		:visible="internalVisible"
		:confirm-loading="sureBtnLoading"
		@ok="handleDialogSure"
		@cancel="handleDialogClose"
		:afterClose="handleDialogClose"
		:maskClosable="false"
	>
		<div class="dialog-div-custom">
			<!-- 选择的目标路径 -->
			<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)"
					node-key="id"
					@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>
		<template #footer>
			<a-button @click="handleDialogClose">取 消</a-button>
			<a-button type="primary" :loading="sureBtnLoading" @click="handleDialogSure"> 确 定 </a-button>
		</template>
	</a-modal>
</template>

<script setup>
	import { ref, getCurrentInstance, watch } from 'vue'
	import { getFoldTree, saveShareFile } from '@/api/myResource/file'
	import { message } from 'ant-design-vue'
	const { proxy } = getCurrentInstance()

	const props = defineProps({
		visible: {
			type: Boolean,
			default: false
		},
		userFileIds: {
			type: String,
			default: ''
		},
		shareBatchNum: {
			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) // 如果父组件需要 .sync 修饰符或者 v-model:visible
		props.callback('cancel')
	}

	/**
	 * 对话框打开的回调
	 */
	const handleDialogOpen = () => {
		initFileTree()
		targetPath.value = '/' // 重置目标路径
	}

	/**
	 * 初始化文件目录树
	 */
	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 = async () => {
		sureBtnLoading.value = true
		try {
			const res = await saveShareFile({
				filePath: targetPath.value,
				userFileIds: props.userFileIds,
				shareBatchNum: props.shareBatchNum
			})

			if (res.success) {
				message.success('保存成功')
				internalVisible.value = false
				emit('update:visible', false)
				props.callback('confirm')
			} else {
				message.error(res.message)
			}
		} catch (error) {
			message.error('保存文件失败')
			console.error(error)
		} finally {
			sureBtnLoading.value = false
		}
	}

	// 暴露给模板或者父组件（如果需要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; // antd 默认就是 flex，可能不需要
		}

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

			.dialog-div-custom {
				// 修改类名以避免与 antd 内部类名冲突
				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; // 或者 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; // 给按钮一些左边距
							}
						}
					}
				}
			}
		}
	}
	: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: #29175b !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>
