<template>
  <TreeStructure
    v-if="config?.datasourceType == 'tree'"
    :treeConfig="config?.treeConfig"
    @select="handleSelectTree"
  />
  <BasicTree
    v-else
    :title="config?.menuName"
    toolbar
    search
    switcher
    :clickRowToExpand="true"
    :treeData="treeData"
    :fieldNames="fieldNames()"
    @select="handleSelect"
  >
    <template #title="item">
      <template v-if="item.renderIcon === 'parentIcon'">
        <Icon :icon="config?.parentIcon" />
      </template>
      <template v-if="item.renderIcon === 'childIcon'">
        <Icon :icon="config?.childIcon" />
      </template>
      {{ treeTitle(item) }}
    </template>
  </BasicTree>
</template>
<script setup lang="ts">
  import { BasicTree } from '/@/components/Tree';
  import { TreeStructure } from '/@/components/TreeStructure';

  const props = defineProps({
    config: Object,
    treeData: Array,
  });

  const emits = defineEmits(['handleSelectTree', 'handleSelect']);

  const fieldNames = () => {
    return {
      key: props.config?.datasourceType === 'static' ? 'key' : 'value',
      title:
        props.config?.datasourceType === 'dic'
          ? 'name'
          : props.config?.datasourceType === 'api'
          ? 'label'
          : props.config?.showFieldName || 'title',
    };
  };

  const treeTitle = (item) => {
    switch (props.config?.datasourceType) {
      case 'dic':
        return item.name;
      case 'api':
        return item.label;
      default:
        return item[props.config?.showFieldName || 'title'];
    }
  };

  const handleSelectTree = (info) => {
    emits('handleSelectTree', info);
  };

  const handleSelect = (info) => {
    emits('handleSelect', info);
  };
</script>
<style lang="less" scoped></style>
