<script setup lang="ts">
import { ElTreeSelect } from 'element-plus'
import { getTreeApi } from '@/api/system/menu'
import { StrAnyObjArr } from '@/typings'

interface LoadConfigType {
  // 过滤节点
  filterNodeKey?: string
  // 查询节点类型
  selectType?: Array<number>
  // 禁用节点类型
  disabledType?: Array<number>
}

const props = withDefaults(
  defineProps<{
    modelValue?: string
  }>(),
  {}
)

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

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

const treeSelectRef = ref<InstanceType<typeof ElTreeSelect>>()

const loadConfig = ref<LoadConfigType>()

const treeData = ref<StrAnyObjArr>([])

async function load(config?: LoadConfigType) {
  loadConfig.value = config

  return getTreeApi({ types: config?.selectType ?? [1, 2] }).then((resp) => {
    treeData.value = [{ id: '0', title: '顶级菜单', type: 1, children: resp }]

    if (config?.filterNodeKey) {
      nextTick(() =>
        treeSelectRef.value?.remove(treeSelectRef.value?.getNode(config.filterNodeKey))
      )
    }
  })
}

function disabledObj(data: any) {
  return loadConfig.value?.disabledType?.includes(data.type)
}

defineExpose({ load })
</script>

<template>
  <el-tree-select
    ref="treeSelectRef"
    v-model="computedModelValue"
    :data="treeData"
    :props="{ label: 'title', disabled: disabledObj }"
    default-expand-all
    node-key="id"
    placeholder="请选择菜单"
    filterable
    clearable
    accordion
    check-strictly
  />
</template>
