<template>
  <div>
    <el-form ref="formRef" v-loading="formLoading" label-width="0px">
      <el-form-item>
        <el-tree
          ref="treeRef"
          :data="menuOptions"
          :props="defaultProps"
          empty-text="加载中，请稍候"
          node-key="id"
          show-checkbox
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="formLoading"
          type="primary"
          @click="submitForm"
          v-hasPermi="['basic:role:update-menu']"
          >保存权限</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" name="RoleAssignMenuForm" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as MenuApi from '@/api/system/menu'
import * as PermissionApi from '@/api/system/permission'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps({
  roleId: {
    type: Number
  }
})

watch(
  () => props.roleId,
  (newValue) => {
    getCheckedMenu(newValue)
  }
)

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单 Ref
const menuOptions = ref<any[]>([]) // 菜单树形结构
const treeRef = ref() // 菜单树组件 Ref

/** 提交表单 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      roleId: props.roleId,
      menuIds: [
        ...(treeRef.value.getCheckedKeys(false) as unknown as Array<number>), // 获得当前选中节点
        ...(treeRef.value.getHalfCheckedKeys() as unknown as Array<number>) // 获得半选中的父节点
      ]
    }
    await PermissionApi.assignRoleMenu(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}

const checkedMenuIds = ref([])

async function init() {
  menuOptions.value = handleTree(await MenuApi.getSimpleMenusList())
  getCheckedMenu(props.roleId)
}

async function getCheckedMenu(id) {
  formLoading.value = true
  try {
    checkedMenuIds.value = await PermissionApi.getRoleMenuList(id)
    treeRef.value.setCheckedKeys([], false)
    // 设置选中
    checkedMenuIds.value.forEach((menuId: number) => {
      treeRef.value.setChecked(menuId, true, false)
    })
  } finally {
    formLoading.value = false
  }
}

onMounted(() => {
  init()
})
</script>
<style lang="scss" scoped></style>
