<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import type { EventDataNode } from 'ant-design-vue/es/tree'
import { BasicTree } from '@/components/Tree'
import { lazyGetDeptList } from '@/api/system/dept'
import type { Department, LazyGetDeptListParams } from '@/api/system/dept/types'

defineOptions({ name: 'SystemDeptTree' })
defineProps<{ dept?: string }>()
const emit = defineEmits(['update:dept'])

const departmentList = ref<Department[]>([])

async function requestDeptList(params?: LazyGetDeptListParams) {
  return lazyGetDeptList(params)
    .then((res) => {
      return res.map((item) => {
        return {
          ...item,
          isLeaf: !item.hasChildren,
        }
      })
    })
}

const basicTreeRef = ref<InstanceType<typeof BasicTree>>()
async function onLoadDeptList(treeNode: EventDataNode) {
  try {
    return await requestDeptList({ parentId: treeNode.id })
  }
  catch {
  }
}

onMounted(() => {
  requestDeptList()
    .then((res) => {
      departmentList.value = res
    })
})

function onSelect(value: string[]) {
  emit('update:dept', value[0] || '')
}
</script>

<template>
  <div class="box-border h-full py-12px pl-12px" v-bind="$attrs">
    <BasicTree
      ref="basicTreeRef"
      title="部门列表"
      :click-row-to-expand="false"
      :tree-data="departmentList"
      :field-names="{ key: 'id', title: 'deptName' }"
      :load-data="onLoadDeptList"
      @select="onSelect"
    >
      <template #icon>
        <span class="i-ant-design:deployment-unit-outlined" />
      </template>
    </BasicTree>
  </div>
</template>