<template>
	<div class="pages-base-layout department-page">
		<!-- 工具栏区域 -->
		<div class="tool-bar">
			<div class="left-panel">
				<a-space>
					<a-input v-model:value="searchForm.keyword" placeholder="部门名称" allow-clear style="width: 200px" />
					<a-select v-model:value="searchForm.status" placeholder="状态" allow-clear style="width: 120px">
						<a-select-option :value="1">正常</a-select-option>
						<a-select-option :value="0">禁用</a-select-option>
					</a-select>
					<a-button type="primary" @click="handleSearch">
						<template #icon><search-outlined /></template>
						搜索
					</a-button>
					<a-button @click="handleReset">
						<template #icon><redo-outlined /></template>
						重置
					</a-button>
				</a-space>
			</div>
			<div class="right-panel">
				<a-space>
					<a-button type="primary" @click="handleAdd">
						<template #icon><plus-outlined /></template>
						新增
					</a-button>
					<a-button :disabled="selectedRows.length === 0" @click="handleBatchStatus(1)">
						<template #icon><check-circle-outlined /></template>
						启用
					</a-button>
					<a-button :disabled="selectedRows.length === 0" @click="handleBatchStatus(0)">
						<template #icon><stop-outlined /></template>
						禁用
					</a-button>
					<a-dropdown>
						<a-button :disabled="selectedRows.length === 0">
							<template #icon><more-outlined /></template>
							更多
						</a-button>
						<template #overlay>
							<a-menu>
								<a-menu-item @click="handleExport">
									<template #icon><download-outlined /></template>
									导出
								</a-menu-item>
								<a-menu-item @click="handleImport">
									<template #icon><upload-outlined /></template>
									导入
								</a-menu-item>
								<a-menu-divider />
								<a-menu-item danger @click="handleBatchDelete">
									<template #icon><delete-outlined /></template>
									批量删除
								</a-menu-item>
							</a-menu>
						</template>
					</a-dropdown>
				</a-space>
			</div>
		</div>

		<!-- 表格内容区域 -->
		<div class="table-content">
			<scTable ref="tableRef" :columns="columns" :data-source="tableData" :loading="loading" :pagination="false" :row-key="rowKey" :row-selection="rowSelection" :default-expand-all="true" @refresh="refreshTable" @select="handleSelectChange" @selectAll="handleSelectAll">
				<template #status="{ record }">
					<a-tag :color="record.status === 1 ? 'green' : 'red'">
						{{ record.status === 1 ? '正常' : '禁用' }}
					</a-tag>
				</template>
				<template #action="{ record }">
					<a-space>
						<a-button type="link" size="small" @click="handleView(record)">
							<template #icon><eye-outlined /></template>
							查看
						</a-button>
						<a-button type="link" size="small" @click="handleEdit(record)">
							<template #icon><edit-outlined /></template>
							编辑
						</a-button>
						<a-popconfirm title="确定删除该部门吗？如果该部门下有子部门或用户，将无法删除" @confirm="handleDelete(record)">
							<a-button type="link" size="small" danger>
								<template #icon><delete-outlined /></template>
								删除
							</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</scTable>
		</div>
	</div>

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

	<!-- 导入部门弹窗 -->
	<sc-import v-model:open="dialog.import" title="导入部门" :api="authApi.department.import.post" :template-api="authApi.department.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 } from 'vue'
import { message, Modal } from 'ant-design-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 authApi from '@/api/auth'
import { useTable } from '@/hooks/useTable'

defineOptions({
	name: 'authDepartment',
})

// 使用useTable hooks
const { tableRef, searchForm, tableData, loading, selectedRows, rowSelection, handleSearch, handleReset, handleSelectChange, handleSelectAll, refreshTable } = useTable({
	api: authApi.department.tree.get,
	searchForm: {
		keyword: '',
		status: null,
	},
	columns: [],
	needPagination: false,
	needSelection: true,
	immediateLoad: false,
})

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

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

// 行key
const rowKey = 'id'

// 表格列配置
const columns = [
	{
		title: '#',
		dataIndex: '_index',
		key: '_index',
		width: 60,
		align: 'center',
	},
	{ title: '部门名称', dataIndex: 'name', key: 'name', width: 300 },
	{ title: '负责人', dataIndex: 'leader', key: 'leader', width: 120 },
	{ title: '联系电话', dataIndex: 'phone', key: 'phone', width: 150 },
	{
		title: '排序',
		dataIndex: 'sort',
		key: 'sort',
		width: 100,
		align: 'center',
	},
	{
		title: '状态',
		dataIndex: 'status',
		key: 'status',
		width: 100,
		align: 'center',
		slot: 'status',
	},
	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 220,
		align: 'center',
		slot: 'action',
		fixed: 'right',
	},
]

// 新增部门
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 handleDelete = async (record) => {
	try {
		const res = await authApi.department.delete.delete(record.id)
		if (res.code === 200) {
			message.success('删除成功')
			refreshTable()
		} else {
			message.error(res.message || '删除失败')
		}
	} catch (error) {
		console.error('删除部门失败:', error)
		// 如果是验证错误，显示具体错误信息
		if (error.response?.data?.message) {
			message.error(error.response.data.message)
		} else {
			message.error('删除失败')
		}
	}
}

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

	Modal.confirm({
		title: '确认删除',
		content: `确定删除选中的 ${selectedRows.value.length} 个部门吗？如果删除项中含有子集或用户，将会被一并删除`,
		okText: '确定',
		cancelText: '取消',
		okType: 'danger',
		onOk: async () => {
			try {
				const ids = selectedRows.value.map((item) => item.id)
				const res = await authApi.department.batchDelete.post({ ids })
				if (res.code === 200) {
					message.success(res.message || '删除成功')
					selectedRows.value = []
					refreshTable()
				} else {
					message.error(res.message || '删除失败')
				}
			} catch (error) {
				console.error('批量删除部门失败:', error)
				if (error.response?.data?.message) {
					message.error(error.response.data.message)
				} else {
					message.error('删除失败')
				}
			}
		},
	})
}

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

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

// 导出部门
const handleExport = () => {
	dialog.export = true
}

// 导出API封装
const handleExportApi = async () => {
	const ids = selectedRows.value.map((item) => item.id)
	return await authApi.department.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.department.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 handleSaveSuccess = () => {
	refreshTable()
}

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