<template>
    <hc-dialog v-model="isShow" is-table widths="400px" :padding="false" title="用户角色配置" is-footer-center @close="dialogClose">
        <el-tree ref="treeRef" :props="treeProps" :default-checked-keys="userRoles" show-checkbox :data="treeData" node-key="id" check-strictly default-expand-all />
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getArrValue } from 'js-fast-way'
import roleApi from '~api/system/role'
import mainApi from '~api/system/user'

const props = defineProps({
    roles: {
        type: Array,
        default: () => ([]),
    },
    users: {
        type: Array,
        default: () => ([]),
    },
})

//事件
const emit = defineEmits(['close', 'finish'])

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})

//监听内容
const userRoles = ref(props.roles)
watch(() => props.roles, (data) => {
    userRoles.value = getArrValue(data)
}, { immediate: true, deep: true })

//监听内容
const userIds = ref(props.users)
watch(() => props.users, (data) => {
    userIds.value = getArrValue(data)
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) {
        getDataApi()
    }
})

//获取数据
const treeRef = ref(null)
const treeProps = { label: 'title', children: 'children' }
const treeData = ref([])
const getDataApi = async () => {
    const { data } = await roleApi.roleTree()
    treeData.value = getArrValue(data)
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const ids = userIds.value.join(',')
    const keys = treeRef.value?.getCheckedKeys()
    const roles = keys.join(',')
    const { isRes } = await mainApi.grant({
        userIds: ids,
        roleIds: roles,
    })
    if (!isRes) return
    window.$message.success('操作成功')
    dialogClose()
    emit('finish')
}

//关闭弹窗
const dialogClose = () => {
    isShow.value = false
    submitLoading.value = false
    emit('close')
}
</script>
