<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'
        }"
        block-node
        v-model:checked-keys="checkedIds"
        :checkable="true"
        show-line
        :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 { getMenuTreeByPackageId, editPackageMenus } from '@/api/upms/menu'

const props = defineProps<{
  packageId: string
}>()

const menuTree = ref([])
const checkedIds = ref([])
const loading = ref(false)

watch(
  () => props.packageId,
  (val) => {
    if (val) {
      menuTree.value = []
      checkedIds.value = []
      getMenuTreeByPackageId(props.packageId).then((res: any) => {
        menuTree.value = res.tree.map((item: any) => {
          return {
            ...item,
            key: item.id
          }
        })
        setTimeout(() => {
          checkedIds.value = res.checkedIds
        }, 0)
      })
    }
  },
  {
    immediate: true
  }
)

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