<template>
  <ListPanel
    class="vtj-templates"
    title="模板"
    :search="search"
    :tabs="tabs"
    @search-change="handleSearch">
    <template #search="{ span }">
      <ComponentList :list="searchResult" :span="span"></ComponentList>
    </template>
    <template #tab="{ tab, span }">
      <ElCollapse
        v-if="groupTemplatesMap[tab.name].categories.length"
        :model-value="
          getDefaultModelValue(groupTemplatesMap[tab.name].categories)
        ">
        <ElCollapseItem
          v-for="(category, index) in groupTemplatesMap[tab.name].categories"
          :key="category.category"
          :title="category.category"
          :name="index">
          <ComponentList
            removable
            @remove="onRemove"
            :list="category.components"
            :span="span"></ComponentList>
        </ElCollapseItem>
      </ElCollapse>
      <ElEmpty v-else description="暂无数据"></ElEmpty>
    </template>
  </ListPanel>
</template>
<script lang="ts" setup>
import { ListPanel, useCore, TemplateDescription } from '@vtj/engine';
import ComponentList from '../parts/ComponentList.vue';
import useComponentsSearch from '../hooks/useComponentsSearch';
import {
  ElEmpty,
  ElCollapse,
  ElCollapseItem,
  ElMessageBox
} from 'element-plus';
import { ref } from 'vue';

const search = {
  placeholder: '搜索模板'
};

const { engine } = useCore();

const { templates } = engine?.assets || {};

const getgroupTemplatesMap = () => {
  const map: Record<string, any> = {};
  const { groupTemplates } = engine?.assets;
  if (groupTemplates) {
    groupTemplates.forEach((group) => {
      map[group.group] = group;
    });
  }
  return map;
};

const getTab = () => {
  const { groupTemplates } = engine?.assets;
  if (!groupTemplates) return [];
  return groupTemplates.map(({ group, categories }) => ({
    label: group,
    name: group,
    disabled: !categories.length
  }));
};

const groupTemplatesMap = ref(getgroupTemplatesMap());
const tabs = ref(getTab());

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

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

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

const onRemove = (item: TemplateDescription) => {
  ElMessageBox.confirm('确定删除？', '提示', { type: 'warning' }).then(() => {
    engine.assets.removeTemplate(item.name);
    groupTemplatesMap.value = getgroupTemplatesMap();
    tabs.value = getTab();
  });
};
</script>
