<template>
    <el-dialog :modelValue="modelValue" @close="$emit('update:modelValue', false)" title="编辑权限">
        <el-tree-v2 ref="tree" :data="codes" :props="treeProps" :default-checked-keys="role.codes" show-checkbox :height="500">
            <template #default="{ node }">
                <span>{{ node.data.lable }}</span>
            </template>
        </el-tree-v2>
        <template #footer>
            <el-button type="default" @click="$emit('update:modelValue', false)">取消</el-button>
            <el-button v-loading="submitLoading" type="primary" @click="submitForm()">提交</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { update, codes as getCodes } from '/@/api/role'
import type { Role } from '/@/api/role'
import { ref, onMounted, inject } from 'vue';
import { ElMessage } from 'element-plus'
import { throttle } from 'lodash'
import { codes as symbolCode } from '/@/types/di';
import { CodeTree } from '/@/api/role';

const { modelValue, role } = defineProps<{
    modelValue: boolean,
    role: Role
}>()
console.log(role)
const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'submit', result: any): void
}>()

const codes = ref<CodeTree[]>([])

const tree = ref()

const submitLoading = ref(false)

const treeProps = {
    value: 'id',
    label: 'label',
    children: 'children',
}

onMounted(async () => {
    codes.value = await inject(symbolCode, () => getCodes().then(res => res.data))
})

const submitForm = throttle(async () => {
    const checkedCodes = tree.value?.getCheckedNodes(true).map(node => node.lable)
    const checkedKeys = tree.value?.getCheckedKeys()

    role.codes = checkedKeys
    role.codes_cn = checkedCodes

    submitLoading.value = true
    const result = await update(role)
    if (result.code != 0) {
        return  
    }
    submitLoading.value = false
    ElMessage({ message: '更新成功' })

    emit('update:modelValue', false)
    emit('submit', result)
})

</script>
