<template>
  <div class="vtj-apps">
    <div class="vtj-apps__header">
      <div class="vtj-apps__top">
        <IconItem
          v-for="panel in panelApps"
          :key="`trigger-${panel.name}`"
          :icon="panel.trigger?.icon"
          :label="panel.trigger?.label"
          :active="active === panel"
          :open="open === panel"
          @click="handleClickItem(panel)"></IconItem>
      </div>
      <div class="vtj-apps__bottom">
        <IconItem
          v-for="panel in otherApps"
          :key="`trigger-${panel.name}`"
          :icon="panel.trigger?.icon"
          :label="panel.trigger?.label"
          @click="handleClickOtherItem(panel)"></IconItem>
      </div>
    </div>
    <div class="vtj-apps__panels" v-show="!!open">
      <template v-for="item in panelApps" :key="item.name">
        <WidgetRenderer
          v-if="active === item"
          v-bind="{ ...item }"></WidgetRenderer>
      </template>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { inject, computed, ref, watch, onMounted } from 'vue';
import {
  RegionWidgets,
  Widget,
  EVENT_SKELETON_LEFT_COLLAPSED_CHANGE,
  Engine
} from '../../core';
import WidgetRenderer from '../renderer/WidgetRenderer';
import IconItem from '../parts/IconItem.vue';
import useCore from '../hooks/useCore';

const { region, engine } = useCore();

const { apps = [] } = region || {};
const active = ref<Widget | null>(null);
const open = ref<Widget | null>(null);

const panelApps = computed(() => {
  return apps.filter(
    (item: Widget) => !item.disabled && item.trigger?.type === 'panel'
  );
});

const otherApps = computed(() => {
  return apps.filter(
    (item: Widget) => !item.disabled && item.trigger?.type !== 'panel'
  );
});

function setCurrentWidget(name: string) {
  const widget = apps.find((item: Widget) => item.name === name);
  if (widget) {
    active.value = widget;
    open.value = widget;
  }
}

const handleClickItem = (item: Widget) => {
  active.value = item;
  open.value = open.value === item ? null : item;
};

const handleClickOtherItem = (item: Widget) => {
  if (item.type === 'Link' && item.trigger?.type === 'link') {
    window.open(item.props?.url);
    return;
  }
  if (item.type === 'Dialog') {
    // todo: 弹窗
  }
  console.log(item);
};

watch(open, (v) => {
  engine?.emitter.emit(EVENT_SKELETON_LEFT_COLLAPSED_CHANGE, !!v);
});

defineExpose({
  setCurrentWidget
});

// onMounted(() => {
//   console.log(engine.project.documents.length);
//   setCurrentWidget('documents');
// });
</script>
