<template>
  <Tabs
    class="vtj-workspace"
    :items="tabs"
    v-model="currentTab"
    :more="moreItems"
    @tab-remove="onClose"
    @more="onClickMore"
    checkable>
    <WidgetRenderer
      v-for="item in workspace"
      :key="item.name"
      v-bind="{ ...item }"
      :visible="item.name === currentTab"></WidgetRenderer>
  </Tabs>
</template>
<script lang="ts" setup>
import { ref, watch, computed } from 'vue';
import WidgetRenderer from '../renderer/WidgetRenderer';
import Tabs, { TabItem, MoreItem } from '../parts/Tabs.vue';
import useCore from '../hooks/useCore';
import { EVENT_DESIGNER_ACTIVE_CHANGE } from '@vtj/engine';

const { region, emitter } = useCore();
const { workspace = [] } = region || {};

const designer = workspace
  .filter((n) => n.name === 'designer')
  .map((n) => {
    return {
      name: n.name,
      label: n.trigger?.label || n.name
    };
  });

const moreItems = ref<MoreItem[]>(
  workspace
    .filter((n) => !n.disabled && n.name !== 'designer')
    .map((item) => {
      return {
        name: item.name,
        label: item.trigger?.label || item.name,
        checked: false,
        closable: true
      };
    })
);

const tabs = computed<TabItem[]>(() => {
  const items = moreItems.value.filter((n) => !!n.checked);
  items.unshift(designer[0]);
  return items;
});

const currentTab = ref(tabs.value[0]?.name);

watch(currentTab, (name: string) => {
  emitter.emit(EVENT_DESIGNER_ACTIVE_CHANGE, name === 'designer');
});

const onClose = (name: string) => {
  const tab = moreItems.value.find((n) => n.name === name);
  if (tab) {
    tab.checked = false;
  }
  if (name === currentTab.value) {
    currentTab.value = tabs.value[0].name;
  }
};

const openTab = (name: string, props: Record<string, any>) => {};

const onClickMore = (command: any) => {
  command.checked = !command.checked;
};
</script>
