<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-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="handleView(record)">查看</a-button>
						<a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
						<a-button type="link" size="small" @click="handlePermission(record)">权限</a-button>
						<a-button type="link" size="small" @click="handleCopy(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>

	<!-- 新增/编辑角色弹窗 -->
	<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" />
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
	SearchOutlined,
	RedoOutlined,
	PlusOutlined,
	DownOutlined,
	CheckCircleOutlined,
	CopyOutlined,
	DeleteOutlined
} from '@ant-design/icons-vue'
import scTable from '@/components/scTable/index.vue'
import saveDialog from './components/SaveDialog.vue'
import permissionDialog from './components/PermissionDialog.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.roles.list.get,
	searchForm: {
		keyword: '',
		status: null
	},
	columns: [],
	needPagination: true,
	needSelection: true
})

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

// 弹窗引用
const saveDialogRef = ref(null)
const permissionDialogRef = 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: 260, 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.roles.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.roles.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.roles.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) => {
	// TODO: 实现复制角色弹窗
	message.info('复制角色功能开发中...')
}

// 批量复制角色
const handleBatchCopy = () => {
	if (selectedRows.value.length === 0) {
		message.warning('请选择要复制的角色')
		return
	}
	// TODO: 实现批量复制角色弹窗
	message.info('批量复制角色功能开发中...')
}

// 权限设置
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()
}
</script>
