<script setup lang="ts">
import type { KnowledgeGroup } from '@geo/shared-types'
import { useQuery } from '@tanstack/vue-query'
import { computed } from 'vue'

import { knowledgeApi } from '@/lib/api'

interface TreeNode {
  title: string
  value: number
  key: number
  children?: TreeNode[]
}

withDefaults(
  defineProps<{
    modelValue?: number[]
    placeholder?: string
    disabled?: boolean
  }>(),
  {
    modelValue: () => [],
    placeholder: '请选择知识库分组',
    disabled: false,
  },
)

const emit = defineEmits<{
  'update:modelValue': [value: number[]]
}>()

const groupsQuery = useQuery({
  queryKey: ['knowledge', 'groups', 'selector'],
  queryFn: () => knowledgeApi.listGroups(),
})

const treeData = computed(() => (groupsQuery.data.value ?? []).map((item) => toTreeNode(item)))

function toTreeNode(group: KnowledgeGroup): TreeNode {
  return {
    title: `${group.name}${group.item_count > 0 ? ` (${group.item_count})` : ''}`,
    value: group.id,
    key: group.id,
    children: (group.children ?? []).map((item) => toTreeNode(item)),
  }
}

function handleChange(values: Array<string | number>): void {
  emit(
    'update:modelValue',
    values.map((item) => Number(item)).filter((item) => Number.isFinite(item) && item > 0),
  )
}
</script>

<template>
  <a-tree-select
    :value="modelValue"
    :tree-data="treeData"
    tree-checkable
    tree-default-expand-all
    multiple
    show-search
    allow-clear
    size="large"
    style="width: 100%"
    :placeholder="placeholder"
    :disabled="disabled"
    :loading="groupsQuery.isPending.value"
    :max-tag-count="3"
    @update:value="handleChange"
  />
</template>
