<template>
	<a-modal title="角色权限设置" :open="visible" :width="600" :destroy-on-close="true" @cancel="handleCancel">
		<div class="permission-content">
			<div class="permission-tree">
				<a-tree ref="menuTreeRef" v-model:checkedKeys="checkedPermissionIds" :tree-data="permissionTree" :field-names="fieldNames" :checkable="true" :default-expand-all="true" :check-strictly="false" :selectable="false">
					<template #title="{ title }">
						{{ title }}
					</template>
				</a-tree>
			</div>
		</div>
		<template #footer>
			<a-space>
				<a-button @click="handleCancel">取 消</a-button>
				<a-button type="primary" :loading="isSaveing" @click="submit">保 存</a-button>
			</a-space>
		</template>
	</a-modal>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'

const emit = defineEmits(['success', 'closed'])

const visible = ref(false)
const isSaveing = ref(false)
const menuTreeRef = ref()

// 权限树数据
const permissionTree = ref([])
const checkedPermissionIds = ref([])

// 树字段映射
const fieldNames = {
	title: 'title',
	key: 'id',
	children: 'children',
}

// 表单数据
const form = reactive({
	role_id: '',
	permission_ids: [],
})

// 打开对话框
const open = () => {
	visible.value = true
	return {
		open,
		setData,
		close,
	}
}

// 关闭对话框
const close = () => {
	visible.value = false
}

// 处理取消
const handleCancel = () => {
	emit('closed')
	visible.value = false
}

// 提交保存
const submit = async () => {
	try {
		isSaveing.value = true

		// 获取选中的权限 ID
		form.permission_ids = checkedPermissionIds.value || []

		const res = await authApi.role.permissions.post(form.role_id, {
			permission_ids: form.permission_ids,
		})

		isSaveing.value = false
		if (res.code === 200) {
			emit('success', form)
			visible.value = false
			message.success('操作成功')
		} else {
			message.error(res.message || '操作失败')
		}
	} catch (error) {
		console.error('保存权限失败:', error)
		isSaveing.value = false
		message.error('操作失败')
	}
}

// 获取权限树
const loadPermissionTree = async () => {
	try {
		const res = await authApi.permission.tree.get()
		permissionTree.value = res.data || []
	} catch (error) {
		console.error('获取权限树失败:', error)
		message.error('获取权限树失败')
	}
}

// 获取角色已有权限
const loadRolePermissions = async (roleId) => {
	try {
		const res = await authApi.role.permissions.get(roleId)
		if (res.code === 200 && res.data) {
			checkedPermissionIds.value = res.data.map((item) => item.id)
		}
	} catch (error) {
		console.error('获取角色权限失败:', error)
	}
}

// 设置数据
const setData = async (data) => {
	form.role_id = data.id
	checkedPermissionIds.value = []

	// 加载角色已有的权限
	await loadRolePermissions(data.id)
}

// 组件挂载时加载数据
loadPermissionTree()

// 暴露方法给父组件
defineExpose({
	open,
	setData,
	close,
})
</script>

<style scoped>
.permission-content {
	padding: 20px 0;
}

.permission-tree {
	max-height: 500px;
	overflow-y: auto;
	border: 1px solid #e8e8e8;
	padding: 16px;
	border-radius: 4px;
}
</style>
