<template>
	<el-dialog v-model="dialogVisible" width="30%">
		<template #header>
			<span class="el-dialog__title" style="margin-right: 50px;">授权权限</span>
			<el-checkbox v-model="toggleExpand" @change="toggleExpandChange">展开 / 折叠</el-checkbox>
			<el-checkbox v-model="toggleSelectAll" @change="toggleSelectAllChange">全选 / 全不选</el-checkbox>
		</template>
		<div style="min-height: 200px;max-height: 500px;overflow-y: auto;">
			<el-tree ref="treeRef" :props="props" :data="treeData" :default-expanded-keys="expandedKey"
							 node-key="id"
							 show-checkbox/>
		</div>
		<div style="text-align: right;margin-top: 20px;">
			<el-button class="f18" @click="dialogVisible = false">取消</el-button>
			<el-button class="f18" type="primary" @click="updateData">更新</el-button>
		</div>
	</el-dialog>
</template>

<script lang='ts' setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import * as menuApi from "@/api/menu";
import * as roleApi from "@/api/role";

const props = {
	label: 'name',
	children: 'children'
}
const treeIds: Array<string> = []
const treeRef = ref()
const dialogVisible = ref(false)
const toggleExpand = ref(false)
const toggleSelectAll = ref(false)
const treeData = ref()
const expandedKey = ref<Array<string>>([])
let roleObj: any;

defineExpose({
	open,
	close
})

function open(role: any) {
	dialogVisible.value = true
	roleObj = role;
	getMenuTree();
	getRoleMenu();
}

function close() {
	dialogVisible.value = false
}

const getMenuTree = () => {
	menuApi.getMenuTree().then((res: any) => {
		treeData.value = res.data;
		setTreeIds(res.data, treeIds);
	});
}

const getRoleMenu = () => {
	menuApi.getRoleTree(roleObj.roleId).then((res: any) => {
		treeRef.value.setCheckedKeys(res.data);
	})
}

const setTreeIds = (data: any[], container: string[]) => {
	data.forEach((menu: any) => {
		container.push(menu.id);
		if (menu.children) {
			setTreeIds(menu.children, container);
		}
	});
}

const toggleExpandChange = (e: boolean) => {
	setTreeExpand(treeRef.value.store.root, e)
}

const setTreeExpand = (node: any, status: boolean) => {
	node.expanded = status;
	if (node.childNodes) {
		node.childNodes.forEach((node: any) => {
			setTreeExpand(node, status);
		})
	}
}

const toggleSelectAllChange = (e: boolean) => {
	if (!e) treeRef.value.setCheckedNodes(treeIds)
	else treeRef.value.setCheckedKeys(treeIds)
}

const updateData = () => {
	const menuIds = treeRef.value.getCheckedKeys().join(",");
	roleApi.saveRoleMenus(roleObj.roleId, menuIds)
		.then((res: any) => {
			if (res.code == 0) {
				ElMessage.success('更新成功');
				close();
			} else {
				ElMessage.error(res.msg ? res.msg : "更新失败");
			}
		});
}
</script>

<style lang='scss' scoped></style>
