<template>
  <ListPanel
    class="vtj-components"
    title="组件库"
    :search="search"
    :tabs="tabs"
    @search-change="handleSearch">
    <ElEmpty
      v-if="!groupComponents || groupComponents.length === 0"
      description="暂无数据"></ElEmpty>

    <template #search="{ span }">
      <ComponentList :list="searchResult" :span="span"></ComponentList>
    </template>

    <template #tab="{ tab, span }">
      <ElCollapse
        v-if="groupComponentMap[tab.name].categories.length"
        :model-value="
          getDefaultModelValue(groupComponentMap[tab.name].categories)
        ">
        <ElCollapseItem
          v-for="(category, index) in groupComponentMap[tab.name].categories"
          :key="category.category"
          :title="category.category"
          :name="index">
          <ComponentList
            :list="category.components"
            :span="span"></ComponentList>
        </ElCollapseItem>
      </ElCollapse>
      <ElEmpty v-else description="暂无数据"></ElEmpty>
    </template>
  </ListPanel>
</template>
<script lang="ts" setup>
import { computed } from 'vue';
import ListPanel from '../parts/ListPanel.vue';
import ComponentList from '../parts/ComponentList.vue';
import useComponentsSearch from '../hooks/useComponentsSearch';
import useCore from '../hooks/useCore';
import { ElCollapse, ElCollapseItem, ElEmpty } from 'element-plus';

const search = {
  placeholder: '搜索组件'
};

const { engine } = useCore();

const { groupComponents, components } = engine?.assets || {};

const groupComponentMap = computed(() => {
  const map: Record<string, any> = {};
  if (groupComponents) {
    groupComponents.forEach((group) => {
      map[group.group] = group;
    });
  }
  return map;
});

const tabs = computed(() => {
  if (!groupComponents) return [];
  return groupComponents.map(({ group, categories }) => ({
    label: group,
    name: group,
    disabled: !categories.length
  }));
});

const { searchKey, searchResult } = useComponentsSearch(components);

const handleSearch = (keyword: any) => {
  searchKey.value = keyword;
};

const getDefaultModelValue = (categories: any[]) => {
  return categories.map((n, i) => i);
};
</script>
