<script setup lang="ts">
import { getTreeApi } from '@/api/system/dept'
import { StrAnyObjArr } from '@/typings'

const props = withDefaults(
  defineProps<{
    modelValue?: string | Array<string>
    showTop?: boolean
    multiple?: boolean
    disabled?: boolean
  }>(),
  {
    showTop: false,
    multiple: false,
    disabled: false
  }
)

const computedModelValue = computed({
  get() {
    return props.modelValue
  },
  set(newValue) {
    emits('update:modelValue', newValue)
  }
})

const emits = defineEmits(['update:modelValue'])

const treeSelectRef = ref()
const treeData = ref<StrAnyObjArr>([])

async function load(filterNodeKey?: string) {
  return getTreeApi({}).then((resp) => {
    if (props.showTop) {
      treeData.value = [{ id: '0', name: '顶级部门', children: resp }]
    } else {
      treeData.value = resp
    }
    if (filterNodeKey) {
      nextTick(() => treeSelectRef.value.remove(treeSelectRef.value.getNode(filterNodeKey)))
    }
  })
}

defineExpose({ load })
</script>

<template>
  <el-tree-select
    ref="treeSelectRef"
    v-model="computedModelValue"
    :data="treeData"
    :props="{ label: 'name' }"
    :multiple="multiple"
    :disabled="disabled"
    node-key="id"
    placeholder="请选择部门"
    filterable
    clearable
    check-strictly
    default-expand-all
  />
</template>
