<script lang="ts" setup>
  import { Tabs, List } from 'ant-design-vue';
  import VisualWidgetSelect from './VisualWidgetSelect.vue';
  import { getComponentDefaultConfig } from '../../components/help';
  import { frontComponentMap } from '../../components/help';
  import { computed } from 'vue';
  import {
    FrontComponent,
    FrontComponentCategory,
    FrontComponentCategoryName,
  } from '../../const/const';

  interface DataSource {
    category: string;
    categoryName: string;
    list: Recordable[];
  }
  const props = defineProps<{
    value: string;
  }>();
  const emit = defineEmits(['update:value', 'change']);

  const grid = { gutter: 10, column: 1, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 };

  const getDataSource = computed(() => {
    const _dataSource = Array.from(frontComponentMap.values());
    const category = new Map<FrontComponentCategory, DataSource>();
    for (const item of _dataSource) {
      if (category.has(item.ComponentCategory)) {
        const value = category.get(item.ComponentCategory)!;
        value.list.push(item);
        continue;
      }
      category.set(item.ComponentCategory, {
        category: item.ComponentCategory,
        categoryName: FrontComponentCategoryName[item.ComponentCategory],
        list: [item],
      });
    }
    return Array.from(category.values());
  });

  const handleCheck = (checked: FrontComponent) => {
    const defaultConfig = getComponentDefaultConfig(checked);
    emit('update:value', checked);
    emit('change', defaultConfig);
  };
</script>

<template>
  <section>
    <Tabs>
      <Tabs.TabPane
        v-for="category in getDataSource"
        :key="category.category"
        :tab="category.categoryName"
      >
        <List :grid="grid" :data-source="category.list">
          <template #renderItem="{ item }">
            <List.Item class="!flex !justify-center">
              <VisualWidgetSelect
                :checked-id="props.value"
                :control-id="item.ComponentKey"
                @change="handleCheck"
              >
                <template #default>
                  <component :is="item.Component" :random="true" :layout="item.ComponentConfig" />
                </template>
                <template #description>
                  {{ item.ComponentName || '选择' }}
                </template>
              </VisualWidgetSelect>
            </List.Item>
          </template>
        </List>
      </Tabs.TabPane>
    </Tabs>
  </section>
</template>
