<template>
    <el-drawer v-model="visible" :size="600" append-to-body @closed="$emit('closed')">
        <template #header="{ titleId, titleClass }">
            <span :id="titleId" :class="titleClass">【{{ form.name }}】菜单分配</span>
        </template>

        <el-tree ref="formRef" v-loading="loading" node-key="id" :data="menuTree" :default-checked-keys="form.menuIdList" expand-on-click-node show-checkbox check-strictly>
            <template #default="{ data }">
                <vxe-text-ellipsis :id="data.id" :title="data.title" class="custom-tree-node" :content="data.title"></vxe-text-ellipsis>
            </template>
        </el-tree>

        <template #footer>
            <el-button auto-insert-space @click="visible = false">取消</el-button>
            <el-button :loading="isSaving" type="primary" auto-insert-space @click="submit">保存</el-button>
        </template>
	</el-drawer>
</template>

<script setup>
import XEUtils from "xe-utils";

import API from "@/api";
import TOOL from "@/utils/tool";
const $emit = defineEmits(["success", "closed"]);
const visible = ref(false);
const loading = ref(false);
const isSaving = ref(false);

const menuTree = ref([]);
const form = ref({
    id: null,
    name: null,
    menuIdList: []
});

const setData = data => {
    visible.value = true;
    XEUtils.objectEach(form.value, (_, key) => XEUtils.set(form.value, key, XEUtils.get(data, key)));
    fetchBindMenu();
}

const fetchBindMenu = () => {
    const mode = TOOL.data.get("USER_INFO").tenantId === "0" ? "get" : "build";

    loading.value = true;
    Promise.all([
        API.system.menu[mode](),
        API.system.roleMenu.get({ roleId: form.value.id })
    ]).then(res => {
        loading.value = false;
        menuTree.value = XEUtils.toArrayTree(XEUtils.first(res), { parentKey: "pid", sortKey: "menuSort" });
        form.value.menuIdList = XEUtils.map(XEUtils.last(res), item => item.menuId);
    }).catch(() => {
        loading.value = false;
        menuTree.value = [];
        form.value.menuIdList = [];
    });
}

const formRef = ref();
const submit = () => {
    const data = {
        roleId: form.value.id,
        menuIdList: formRef.value.getCheckedKeys()
    }
    
    isSaving.value = true;
    API.system.roleMenu.edit(data).then(res => {
        isSaving.value = false;
        ElMessage.success("操作成功");
        visible.value = false;
    }).catch(() => isSaving.value = false);
}

defineExpose({
    setData
});
</script>

<style scoped>
.el-tree {width: calc(100% - 40px);margin: auto;}
.el-tree :deep(.el-tree-node.is-current > .el-tree-node__content) {color: var(--el-text-color-primary);}
</style>