<template>
	<a-drawer
		v-model:visible="visible"
		title="选择组织"
		placement="right"
		width="50%"
		:footer="null"
		@close="handleCancel"
	>
		<!-- 左侧：树状结构成员列表 -->
		<div class="left-panel">
			<a-input-search
				v-model:value="searchValue"
				placeholder="输入组织名称"
				style="margin-bottom: 16px"
				@search="onSearch"
			/>
			<div style="padding: 15px"><InsertRowRightOutlined style="margin-right: 8px; color: #1890ff" />组织架构</div>
			<a-tree
				:tree-data="filteredTreeData"
				:field-names="{ key: 'id', title: 'name', children: 'children' }"
				:checked-keys="checkedKeys"
				:expanded-keys="expandedKeys"
				:auto-expand-parent="autoExpandParent"
				checkable
				show-icon
				:selectable="false"
				@check="onCheck"
				@expand="onExpand"
			>
				<template #title="{ name }">
					<span style="display: inline-flex; align-items: center">
						<HomeOutlined style="margin-right: 8px; color: #1890ff" />
						{{ name }}
					</span>
				</template>
				<template #switcherIcon="{ expanded }">
					<caret-down-outlined v-if="expanded" />
					<caret-right-outlined v-else />
				</template>
			</a-tree>
		</div>

		<!-- 右侧：已选择成员列表 -->
		<div class="right-panel">
			<div class="header">
				<span>已选 {{ selectedUsers.length }} / 30</span>
				<a-button type="link" @click="clearSelection">清空</a-button>
			</div>
			<a-list item-layout="horizontal" :data-source="selectedUsers">
				<template #renderItem="{ item }">
					<a-list-item>
						<a-list-item-meta>
							<!-- <template #avatar>
								<a-avatar :src="item.avatar" />
							</template> -->
							<template #title>
								<a>{{ item.name }}</a>
							</template>
							<template #description>
								<span>{{ item.department }}</span>
							</template>
						</a-list-item-meta>
						<template #actions>
							<a @click="removeUser(item)">删除</a>
						</template>
					</a-list-item>
				</template>
			</a-list>
		</div>

		<!-- 底部按钮 -->
		<template #footer>
			<a-space>
				<a-button @click="handleCancel">取消</a-button>
				<a-button type="primary" @click="handleOk">确定</a-button>
			</a-space>
		</template>
	</a-drawer>
</template>

<script setup>
	import { ref, reactive, computed, watch } from 'vue'
	// import { HomeOutlined } from 'ant-design-vue'
	const emit = defineEmits(['close', 'confirm'])
	const visible = ref(true)
	const searchValue = ref('')
	const treeData = ref([
		{
			id: '1',
			name: '一级组织1',
			children: [
				{
					id: '1-1',
					name: '二级组织1',
					// avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
					isLeaf: true
				},
				{
					id: '1-2',
					name: '二级组织2',
					// avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
					isLeaf: true
				}
			]
		},
		{
			id: '2',
			name: '一级组织2',
			children: [
				{
					id: '2-1',
					name: '二级组织1',
					children: [
						{
							id: '2-1-1',
							name: '三级组织1',
							// avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
							isLeaf: true
						}
					]
				}
			]
		}
	])
	const selectedKeys = ref([])
	const selectedUsers = ref([])
	const checkedKeys = ref([])
	const expandedKeys = ref(['1']) // 默认展开第一层
	const autoExpandParent = ref(true)
	const filteredTreeData = computed(() => {
		const filterFn = (node) => {
			if (node.name.includes(searchValue.value)) {
				return true
			}
			if (node.children && node.children.some(filterFn)) {
				return true
			}
			return false
		}
		return treeData.value.filter(filterFn)
	})

	// 替换原来的onSelect方法
	const onCheck = (checkedKeysValue, { checked, node, checkedNodes }) => {
		checkedKeys.value = checkedKeysValue
		selectedUsers.value = checkedNodes.map((node) => ({
			id: node.id,
			name: node.name,
			avatar: node.avatar || '',
			department: findDepartmentName(node.id, treeData.value)
		}))
	}
	// 查找部门名称的辅助函数
	const findDepartmentName = (id, nodes) => {
		// 如果是顶级节点，返回空字符串
		if (nodes.some((node) => node.id === id)) return ''
		for (const node of nodes) {
			if (node.children) {
				const found = node.children.find((child) => child.id === id)
				if (found) return node.name
				const result = findDepartmentName(id, node.children)
				if (result) return result
			}
		}
		return ''
	}
	const onExpand = (keys) => {
		expandedKeys.value = keys
		autoExpandParent.value = false
	}

	const onSearch = (value) => {
		searchValue.value = value
	}

	const clearSelection = () => {
		selectedKeys.value = []
		selectedUsers.value = []
		checkedKeys.value = []
	}

	const removeUser = (user) => {
		const index = selectedUsers.value.findIndex((u) => u.id === user.id)
		if (index !== -1) {
			selectedUsers.value.splice(index, 1)
			selectedKeys.value = selectedUsers.value.map((u) => u.id)
			checkedKeys.value = selectedUsers.value.map((u) => u.id)
		}
		// selectedUsers.value = selectedUsers.value.filter((u) => u.id !== user.id)
		// checkedKeys.value = selectedUsers.value.map((u) => u.id)
	}

	const showModal = () => {
		visible.value = true
	}

	const handleOk = () => {
		console.log('Selected Users:', selectedUsers.value)
	}

	const handleCancel = () => {
		emit('close')
	}
</script>

<style scoped>
	.left-panel,
	.right-panel {
		display: inline-block;
		vertical-align: top;
		width: 48%;
		height: calc(100vh - 200px);
		overflow-y: auto;
		padding: 0 10px;
	}

	.right-panel {
		border-left: 1px solid #f0f0f0;
	}

	.header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 16px;
	}

	.ant-tree-switcher {
		width: 24px;
		height: 24px;
		line-height: 24px;
	}

	.ant-tree-switcher-icon {
		font-size: 12px;
		transition: transform 0.3s;
	}

	.ant-tree-switcher_close .ant-tree-switcher-icon {
		transform: rotate(-90deg);
	}
	.ant-tree-checkbox + .ant-tree-switcher {
		margin-left: 8px;
	}
</style>
