<template>
  <div>
    <div class="mb-xs flex-row justify-end">
      <c-button type="primary" @click="handleSubmit">保存</c-button>
    </div>
    <a-scrollbar style="height: 74vh; overflow: auto">
      <a-tree
        v-if="menuTree.length > 0"
        :field-names="{
          key: 'id',
          title: 'name',
          icon: 'iconRender'
        }"
        :default-expand-all="true"
        :block-node="true"
        v-model:checked-keys="checkedIds"
        :checkable="true"
        :show-line="true"
        :data="menuTree"
      />
      <a-empty v-else></a-empty>
    </a-scrollbar>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { getMenuTreeByRoleId, editRoleMenus } from '@/api/upms/menu'

const props = defineProps<{
  record: any
}>()

// permission
const menuTree = ref([])
const roleIds = ref('')
const checkedIds = ref([])
const loading = ref(false)
const handlePermission = () => {
  menuTree.value = []
  checkedIds.value = []
  roleIds.value = props.record.id
  getMenuTreeByRoleId(props.record.id).then((res: any) => {
    menuTree.value = res.tree.map((item: any) => {
      return {
        ...item,
        key: item.id
      }
    })
    setTimeout(() => {
      checkedIds.value = res.checkedIds
    }, 0)
  })
}
watch(
  () => props.record.id,
  () => {
    handlePermission()
  },
  {
    immediate: true
  }
)

const handleSubmit = (done: Function) => {
  loading.value = true
  editRoleMenus(roleIds.value, checkedIds.value)
    .then(() => {
      Message.success('保存成功')
    })
    .finally(() => {
      done()
      loading.value = false
    })
}
</script>
