<template>
  <BasicTree
    search
    :clickRowToExpand="true"
    :treeData="treeData"
    :selectedKeys="selectedKeys"
    expandOnSearch
    :fieldNames="{ key: 'id', title: 'name' }"
    @select="handleSelect"
  />
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { getBomTree } from '/@/api/erp/bom/product';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  const emit = defineEmits(['select']);
  const treeData = ref<TreeItem[]>([]);
  const selectedKeys = ref<string[]>([]);

  onMounted(() => {
    fetch();
  });

  async function fetch() {
    treeData.value = (await getBomTree()) as unknown as TreeItem[];
    let id = treeData.value.length ? treeData.value[0].id : '';
    selectedKeys.value = [id];
    emit('select', id);
  }

  function handleSelect(keys: string, e) {
    if (!keys.length) selectedKeys.value = [e.node.dataRef.id];
    emit('select', keys[0] || selectedKeys.value[0]);
  }

  defineExpose({
    fetch,
  });
</script>
<style lang="less" scoped>
  :deep(.vben-tree-header) {
    display: none;
  }
</style>
