<template>
	<div class="pages-sidebar-layout user-page">
		<div class="left-box">
			<div class="header">
				<a-input v-model:value="departmentKeyword" placeholder="搜索部门..." allow-clear @change="handleDeptSearch">
					<template #prefix>
						<SearchOutlined style="color: rgba(0, 0, 0, 0.45)" />
					</template>
				</a-input>
			</div>
			<div class="body">
				<a-tree
					v-if="filteredDepartmentTree.length > 0"
					v-model:selectedKeys="selectedDeptKeys"
					v-model:expandedKeys="expandedDeptKeys"
					:tree-data="filteredDepartmentTree"
					:field-names="{
						title: 'name',
						key: 'id',
						children: 'children',
					}"
					show-line
					@select="onDeptSelect"
				>
					<template #icon="{ dataRef }">
						<ApartmentOutlined v-if="dataRef.children && dataRef.children.length > 0" />
						<UserOutlined v-else />
					</template>
				</a-tree>
				<a-empty v-else description="暂无部门数据" />
			</div>
		</div>
		<div class="right-box">
			<div class="tool-bar">
				<div class="left-panel">
					<a-space>
						<a-input v-model:value="searchForm.username" placeholder="用户名" allow-clear style="width: 140px" />
						<a-button type="primary" @click="handleSearch">
							<template #icon><SearchOutlined /></template>
							搜索
						</a-button>
						<a-button @click="handleUserReset">
							<template #icon><RedoOutlined /></template>
							重置
						</a-button>
					</a-space>
				</div>
				<div class="right-panel">
					<a-dropdown :disabled="selectedRows.length === 0">
						<a-button :disabled="selectedRows.length === 0">
							批量操作
							<DownOutlined />
						</a-button>
						<template #overlay>
							<a-menu>
								<a-menu-item @click="handleBatchStatus"> <CheckCircleOutlined />批量启用/禁用 </a-menu-item>
								<a-menu-item @click="handleBatchDepartment"> <ApartmentOutlined />批量分配部门 </a-menu-item>
								<a-menu-item @click="handleBatchRoles"> <TeamOutlined />批量分配角色 </a-menu-item>
								<a-menu-divider />
								<a-menu-item @click="handleBatchDelete" danger> <DeleteOutlined />批量删除 </a-menu-item>
							</a-menu>
						</template>
					</a-dropdown>
					<a-dropdown>
						<a-button>
							更多
							<DownOutlined />
						</a-button>
						<template #overlay>
							<a-menu>
								<a-menu-item @click="handleImport"> <ImportOutlined />导入用户 </a-menu-item>
								<a-menu-item @click="handleExport"> <ExportOutlined />导出用户 </a-menu-item>
								<a-menu-item @click="handleDownloadTemplate"> <DownloadOutlined />下载模板 </a-menu-item>
							</a-menu>
						</template>
					</a-dropdown>
					<a-button type="primary" @click="handleAdd">
						<template #icon><PlusOutlined /></template>
						新增
					</a-button>
				</div>
			</div>
			<div class="table-content">
				<scTable
					ref="tableRef"
					:columns="columns"
					:data-source="tableData"
					:loading="loading"
					:pagination="pagination"
					:row-key="rowKey"
					:row-selection="rowSelection"
					@refresh="refreshTable"
					@paginationChange="handlePaginationChange"
					@select="handleSelectChange"
					@selectAll="handleSelectAll"
				>
					<template #avatar="{ record }">
						<a-avatar :src="record.avatar" :size="32">
							<template #icon><UserOutlined /></template>
						</a-avatar>
					</template>
					<template #status="{ record }">
						<a-tag :color="record.status === 1 ? 'success' : 'error'">
							{{ record.status === 1 ? '正常' : '禁用' }}
						</a-tag>
					</template>
					<template #department="{ record }">
						{{ record.department?.name || '-' }}
					</template>
					<template #roles="{ record }">
						<a-tag v-for="role in record.roles" :key="role.id" color="blue">
							{{ role.name }}
						</a-tag>
					</template>
					<template #action="{ record }">
						<a-space>
							<a-button type="link" size="small" @click="handleView(record)">查看</a-button>
							<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
							<a-button type="link" size="small" @click="handleRole(record)">角色</a-button>
							<a-button type="link" size="small" @click="handleResetPassword(record)">重置密码</a-button>
							<a-popconfirm title="确定删除该用户吗？" @confirm="handleDelete(record)">
								<a-button type="link" size="small" danger>删除</a-button>
							</a-popconfirm>
						</a-space>
					</template>
				</scTable>
			</div>
		</div>
	</div>

	<!-- 新增/编辑用户弹窗 -->
	<save-dialog v-if="dialog.save" ref="saveDialogRef" @success="handleSaveSuccess" @closed="dialog.save = false" />

	<!-- 角色设置弹窗 -->
	<role-dialog v-if="dialog.role" ref="roleDialogRef" @success="handleRoleSuccess" @closed="dialog.role = false" />

	<!-- 批量分配部门弹窗 -->
	<department-dialog v-if="dialog.department" ref="departmentDialogRef" @success="handleDepartmentSuccess" @closed="dialog.department = false" />

	<!-- 批量分配角色弹窗 -->
	<batch-role-dialog v-if="dialog.batchRole" ref="batchRoleDialogRef" @success="handleBatchRoleSuccess" @closed="dialog.batchRole = false" />

	<!-- 导入用户弹窗 -->
	<sc-import v-model:open="dialog.import" title="导入用户" :api="authApi.user.import.post" :template-api="authApi.user.downloadTemplate.get" filename="用户" @success="handleImportSuccess" />

	<!-- 导出用户弹窗 -->
	<sc-export v-model:open="dialog.export" title="导出用户" :api="handleExportApi" :default-filename="`用户列表_${Date.now()}`" :show-options="false" tip="导出当前选中或所有用户数据" @success="handleExportSuccess" />
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined, RedoOutlined, PlusOutlined, DeleteOutlined, CheckCircleOutlined, ApartmentOutlined, TeamOutlined, DownOutlined, ImportOutlined, ExportOutlined, DownloadOutlined, UserOutlined } from '@ant-design/icons-vue'
import scTable from '@/components/scTable/index.vue'
import scImport from '@/components/scImport/index.vue'
import scExport from '@/components/scExport/index.vue'
import saveDialog from './components/SaveDialog.vue'
import roleDialog from './components/RoleDialog.vue'
import departmentDialog from './components/DepartmentDialog.vue'
import batchRoleDialog from './components/BatchRoleDialog.vue'
import authApi from '@/api/auth'
import { useTable } from '@/hooks/useTable'

defineOptions({
	name: 'authUser',
})

// 使用useTable hooks
const { tableRef, searchForm, tableData, loading, pagination, selectedRows, rowSelection, handleSearch, handleReset, handlePaginationChange, handleSelectChange, handleSelectAll, refreshTable } = useTable({
	api: authApi.user.list.get,
	searchForm: {
		username: '',
		real_name: '',
		email: '',
		phone: '',
		department_id: null,
		status: null,
	},
	columns: [],
	needPagination: true,
	needSelection: true,
})

// 对话框状态
const dialog = reactive({
	save: false,
	role: false,
	department: false,
	batchRole: false,
	import: false,
	export: false,
})

// 弹窗引用
const saveDialogRef = ref(null)
const roleDialogRef = ref(null)
const departmentDialogRef = ref(null)
const batchRoleDialogRef = ref(null)

// 部门树数据
const departmentTree = ref([])
const filteredDepartmentTree = ref([])
const selectedDeptKeys = ref([])
const departmentKeyword = ref('')
const expandedDeptKeys = ref([])

// 行key
const rowKey = 'id'

// 递归获取所有部门节点的key
const getAllDepartmentKeys = (nodes) => {
	const keys = []
	const traverse = (list) => {
		list.forEach((node) => {
			// 如果节点有children且不为空，则该节点需要展开
			if (node.children && node.children.length > 0) {
				keys.push(node.id)
				traverse(node.children)
			}
		})
	}
	traverse(nodes)
	return keys
}

// 监听部门树数据变化，自动展开所有节点
watch(
	() => filteredDepartmentTree.value,
	(newData) => {
		if (newData && newData.length > 0) {
			expandedDeptKeys.value = getAllDepartmentKeys(newData)
		} else {
			expandedDeptKeys.value = []
		}
	},
	{ immediate: true, deep: true },
)

// 表格列配置
const columns = [
	{
		title: '头像',
		dataIndex: 'avatar',
		key: 'avatar',
		width: 80,
		align: 'center',
		slot: 'avatar',
	},
	{ title: '用户名', dataIndex: 'username', key: 'username', width: 150 },
	{ title: '姓名', dataIndex: 'real_name', key: 'real_name', width: 150 },
	{
		title: '邮箱',
		dataIndex: 'email',
		key: 'email',
		width: 180,
		ellipsis: true,
	},
	{ title: '手机号', dataIndex: 'phone', key: 'phone', width: 130 },
	{
		title: '部门',
		dataIndex: 'department',
		key: 'department',
		slot: 'department',
		width: 150,
		ellipsis: true,
	},
	{
		title: '角色',
		dataIndex: 'roles',
		key: 'roles',
		width: 200,
		slot: 'roles',
		ellipsis: true,
	},
	{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
		width: 100,
		align: 'center',
		slot: 'status',
	},
	{
		title: '最后登录',
		dataIndex: 'last_login_at',
		key: 'last_login_at',
		width: 180,
	},
	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 280,
		align: 'center',
		slot: 'action',
		fixed: 'right',
	},
]

// 加载部门树
const loadDepartmentTree = async () => {
	try {
		const res = await authApi.department.tree.get()
		if (res.code === 200) {
			departmentTree.value = res.data || []
			filteredDepartmentTree.value = res.data || []
		}
	} catch (error) {
		console.error('加载部门树失败:', error)
	}
}

// 部门搜索
const handleDeptSearch = (e) => {
	const keyword = e.target?.value || ''
	departmentKeyword.value = keyword
	if (!keyword) {
		filteredDepartmentTree.value = departmentTree.value
		return
	}

	// 递归过滤部门树
	const filterTree = (nodes) => {
		return nodes.reduce((acc, node) => {
			const isMatch = node.name && node.name.toLowerCase().includes(keyword.toLowerCase())
			const filteredChildren = node.children ? filterTree(node.children) : []

			if (isMatch || filteredChildren.length > 0) {
				acc.push({
					...node,
					children: filteredChildren.length > 0 ? filteredChildren : undefined,
				})
			}
			return acc
		}, [])
	}

	filteredDepartmentTree.value = filterTree(departmentTree.value)
}

// 重置 - 覆盖useTable的handleReset以添加额外逻辑
const handleUserReset = () => {
	searchForm.username = ''
	searchForm.real_name = ''
	searchForm.email = ''
	searchForm.phone = ''
	searchForm.status = null
	searchForm.department_id = null
	selectedDeptKeys.value = []
	departmentKeyword.value = ''
	filteredDepartmentTree.value = departmentTree.value
	handleSearch()
}

// 部门选择事件
const onDeptSelect = (selectedKeys) => {
	if (selectedKeys && selectedKeys.length > 0) {
		searchForm.department_id = selectedKeys[0]
	} else {
		searchForm.department_id = null
	}
	handleSearch()
}

// 批量删除
const handleBatchDelete = () => {
	if (selectedRows.value.length === 0) {
		message.warning('请选择要删除的用户')
		return
	}

	Modal.confirm({
		title: '确认删除',
		content: `确定删除选中的 ${selectedRows.value.length} 个用户吗？`,
		okText: '删除',
		okType: 'danger',
		cancelText: '取消',
		onOk: async () => {
			try {
				const ids = selectedRows.value.map((item) => item.id)
				const res = await authApi.user.batchDelete.post({ ids })
				if (res.code === 200) {
					message.success('删除成功')
					selectedRows.value = []
					refreshTable()
				} else {
					message.error(res.message || '删除失败')
				}
			} catch (error) {
				console.error('批量删除用户失败:', error)
				message.error('删除失败')
			}
		},
	})
}

// 批量更新状态
const handleBatchStatus = () => {
	if (selectedRows.value.length === 0) {
		message.warning('请选择要操作的用户')
		return
	}

	Modal.confirm({
		title: '确认操作',
		content: '确定要批量启用/禁用选中的用户吗？',
		okText: '确定',
		cancelText: '取消',
		onOk: async () => {
			try {
				const ids = selectedRows.value.map((item) => item.id)
				const status = selectedRows.value[0].status === 1 ? 0 : 1
				const res = await authApi.user.batchStatus.post({
					ids,
					status,
				})
				if (res.code === 200) {
					message.success('操作成功')
					selectedRows.value = []
					refreshTable()
				} else {
					message.error(res.message || '操作失败')
				}
			} catch (error) {
				console.error('批量更新状态失败:', error)
				message.error('操作失败')
			}
		},
	})
}

// 批量分配部门
const handleBatchDepartment = () => {
	if (selectedRows.value.length === 0) {
		message.warning('请选择要分配部门的用户')
		return
	}
	dialog.department = true
	setTimeout(() => {
		departmentDialogRef.value?.open(selectedRows.value.map((item) => item.id))
	}, 0)
}

// 批量分配角色
const handleBatchRoles = () => {
	if (selectedRows.value.length === 0) {
		message.warning('请选择要分配角色的用户')
		return
	}
	dialog.batchRole = true
	setTimeout(() => {
		batchRoleDialogRef.value?.open(selectedRows.value.map((item) => item.id))
	}, 0)
}

// 导出数据
const handleExport = () => {
	dialog.export = true
}

// 导出API封装
const handleExportApi = async () => {
	const ids = selectedRows.value.map((item) => item.id)
	return await authApi.user.export.post({
		ids: ids.length > 0 ? ids : undefined,
	})
}

// 导出成功回调
const handleExportSuccess = () => {
	selectedRows.value = []
}

// 导入用户
const handleImport = () => {
	dialog.import = true
}

// 导入成功回调
const handleImportSuccess = () => {
	refreshTable()
}

// 下载模板
const handleDownloadTemplate = async () => {
	try {
		const blob = await authApi.user.downloadTemplate.get()
		const url = window.URL.createObjectURL(blob)
		const link = document.createElement('a')
		link.href = url
		link.download = '用户导入模板.xlsx'
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)
		window.URL.revokeObjectURL(url)
		message.success('下载成功')
	} catch (error) {
		console.error('下载模板失败:', error)
		message.error('下载失败')
	}
}

// 重置密码
const handleResetPassword = (record) => {
	Modal.confirm({
		title: '重置密码',
		content: '确定要重置该用户的密码吗？重置后密码为: 123456',
		okText: '确定',
		cancelText: '取消',
		onOk: async () => {
			try {
				// TODO: 实现重置密码接口
				message.success('密码重置成功')
			} catch (error) {
				console.error('重置密码失败:', error)
				message.error('重置密码失败')
			}
		},
	})
}

// 新增用户
const handleAdd = () => {
	dialog.save = true
	setTimeout(() => {
		saveDialogRef.value?.open('add')
	}, 0)
}

// 查看用户
const handleView = (record) => {
	dialog.save = true
	setTimeout(() => {
		saveDialogRef.value?.open('show').setData(record)
	}, 0)
}

// 编辑用户
const handleEdit = (record) => {
	dialog.save = true
	setTimeout(() => {
		saveDialogRef.value?.open('edit').setData(record)
	}, 0)
}

// 设置角色
const handleRole = (record) => {
	dialog.role = true
	setTimeout(() => {
		if (roleDialogRef.value) {
			roleDialogRef.value.open()
			roleDialogRef.value.setData(record)
		}
	}, 0)
}

// 删除用户
const handleDelete = async (record) => {
	try {
		const res = await authApi.user.delete.delete(record.id)
		if (res.code === 200) {
			message.success('删除成功')
			refreshTable()
		} else {
			message.error(res.message || '删除失败')
		}
	} catch (error) {
		console.error('删除用户失败:', error)
		message.error('删除失败')
	}
}

// 保存成功回调
const handleSaveSuccess = () => {
	refreshTable()
}

// 角色设置成功回调
const handleRoleSuccess = () => {
	refreshTable()
}

// 批量分配部门成功回调
const handleDepartmentSuccess = () => {
	selectedRows.value = []
	refreshTable()
}

// 批量分配角色成功回调
const handleBatchRoleSuccess = () => {
	selectedRows.value = []
	refreshTable()
}

// 初始化
onMounted(() => {
	loadDepartmentTree()
})
</script>
