<template>
	<div class="pages-base-layout role-page">
		<div class="tool-bar">
			<div class="left-panel">
				<a-space>
					<a-input v-model:value="searchForm.keyword" placeholder="角色名称" allow-clear style="width: 180px" />
					<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="handleBatchCopy"> <CopyOutlined />批量复制 </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 #status="{ record }">
					<a-tag :color="record.status === 1 ? 'success' : 'error'">
						{{ record.status === 1 ? '正常' : '禁用' }}
					</a-tag>
				</template>
				<template #action="{ record }">
					<a-space>
						<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
						<a-button type="link" size="small" @click="handleCopy(record)">复制</a-button>
						<a-dropdown>
							<a-button type="link" size="small">
								更多
								<DownOutlined />
							</a-button>
							<template #overlay>
								<a-menu>
									<a-menu-item @click="handleView(record)"> <SearchOutlined />查看 </a-menu-item>
									<a-menu-item @click="handlePermission(record)"> <ImportOutlined />权限 </a-menu-item>
									<a-menu-divider />
									<a-menu-item @click="handleDelete(record)" danger> <DeleteOutlined />删除 </a-menu-item>
								</a-menu>
							</template>
						</a-dropdown>
					</a-space>
				</template>
			</scTable>
		</div>
	</div>

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

	<!-- 权限设置弹窗 -->
	<permission-dialog v-if="dialog.permission" ref="permissionDialogRef" @success="permissionSuccess" @closed="dialog.permission = false" />

	<!-- 导入角色弹窗 -->
	<sc-import v-model:open="dialog.import" title="导入角色" :api="authApi.role.import.post" :template-api="authApi.role.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" />

	<!-- 复制角色弹窗 -->
	<copy-dialog v-if="dialog.copy" ref="copyDialogRef" @success="handleCopySuccess" @closed="dialog.copy = false" />
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined, RedoOutlined, PlusOutlined, DownOutlined, CheckCircleOutlined, CopyOutlined, DeleteOutlined, ImportOutlined, ExportOutlined, DownloadOutlined } 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 permissionDialog from './components/PermissionDialog.vue'
import copyDialog from './components/CopyDialog.vue'
import authApi from '@/api/auth'
import { useTable } from '@/hooks/useTable'

defineOptions({
	name: 'authRole',
})

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

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

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

// 行key
const rowKey = 'id'

// 表格列配置
const columns = [
	{ title: 'ID', dataIndex: 'id', key: 'id', width: 80, align: 'center' },
	{ title: '角色名称', dataIndex: 'name', key: 'name', width: 200 },
	{ title: '角色编码', dataIndex: 'code', key: 'code', width: 200 },
	{
		title: '描述',
		dataIndex: 'description',
		key: 'description',
		ellipsis: true,
	},
	{
		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: 180,
		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 = (record) => {
	Modal.confirm({
		title: '确认删除',
		content: '确定删除该角色吗？',
		okText: '确定',
		cancelText: '取消',
		okType: 'danger',
		onOk: async () => {
			try {
				const res = await authApi.role.delete.delete(record.id)
				if (res.code === 200) {
					message.success('删除成功')
					refreshTable()
				} else {
					message.error(res.message || '删除失败')
				}
			} catch (error) {
				console.error('删除角色失败:', error)
				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.role.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.role.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 handleCopy = (record) => {
	dialog.copy = true
	setTimeout(() => {
		copyDialogRef.value?.open(record)
	}, 0)
}

// 批量复制角色
const handleBatchCopy = () => {
	if (selectedRows.value.length === 0) {
		message.warning('请选择要复制的角色')
		return
	}

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

// 复制成功回调
const handleCopySuccess = () => {
	refreshTable()
}

// 权限设置
const handlePermission = (record) => {
	if (!record && selectedRows.value.length !== 1) {
		message.error('请选择一个角色进行权限设置')
		return
	}
	const roleData = record || selectedRows.value[0]
	dialog.permission = true
	setTimeout(() => {
		permissionDialogRef.value?.open().setData(roleData)
	}, 0)
}

// 重置
const handleUserReset = () => {
	searchForm.keyword = ''
	searchForm.status = null
	handleSearch()
}

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

// 权限设置成功回调
const permissionSuccess = () => {
	refreshTable()
}

// 导出角色
const handleExport = async () => {
	dialog.export = true
}

// 导出API封装
const handleExportApi = async () => {
	const ids = selectedRows.value.map((item) => item.id)
	return await authApi.role.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.role.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('下载失败')
	}
}
</script>
