<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 } from 'vue'
import type { ElTreeV2 } from 'element-plus'
import { clone } from 'lodash'
import { ElMessage } from 'element-plus'

const { modelValue, role } = defineProps<{
    modelValue: boolean,
    role?: Role
}>()
const emit = defineEmits(['update:modelValue'])

const codes = ref()

const tree = ref()

const submitLoading = ref(false)

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

onMounted(async () => {
    codes.value = (await getCodes()).data
})

const submitForm = async () => {
    const checkedCodes = tree.value?.getCheckedNodes(true).map(node => node.lable)
    console.log("🚀 ~ file: edit.vue:43 ~ submitForm ~ checkedCodes:", checkedCodes)
    const checkedKeys = tree.value?.getCheckedKeys()

    const updateRole = clone(role) as Role
    updateRole.codes = checkedKeys
    updateRole.codes_cn = checkedCodes

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

    emit('update:modelValue', false)
}

</script>
