<template>
  <template v-if="loaded" style="height: 100%">
    <Header></Header>
    <GlobalSearch :enable="fuseModels.length === 0 ? 'map-' : undefined" />
    <template v-if="fuseModels.length">
      <router-view v-slot="{ Component }">
        <!-- <keep-alive> -->
        <component :is="Component" />
        <!-- </keep-alive> -->
      </router-view>
    </template>

    <SelectModel v-else>
      <ui-button type="primary" class="add-fuse-model">
        <ui-icon type="add" />添加数据
      </ui-button>
    </SelectModel>
  </template>
</template>

<script lang="ts" setup>
import { ref, watch, watchEffect, nextTick } from "vue";
import { back, currentMeta, router, RoutesName } from "@/router";
import { showLeftPanoStack, showRightPanoStack } from "@/env";
import { asyncTimeout, togetherCallback } from "@/utils";
import { loadModel, fuseModel } from "@/model";
import GlobalSearch from "@/components/global-search/index.vue";
import {
  enterEdit,
  isOld,
  save,
  fuseModels,
  initialFuseModels,
  initialScenes,
  initialTaggingStyles,
  initialTaggings,
  initialGuides,
  initialMeasures,
  fuseModelsLoaded,
  initialPaths,
  initMonitors,
} from "@/store";

import Header from "./header/index.vue";
import SelectModel from "./scene-select.vue";
import { initialAnimationModels } from "@/store/animation";

const loaded = ref(false);
const initialSys = async () => {
  await Promise.all([initialFuseModels(), initialScenes()]);
  await Promise.all([
    initialTaggingStyles(),
    initialTaggings(),
    initialGuides(),
    initialPaths(),
    initialMeasures(),
    initMonitors(),
    initialAnimationModels(),
  ]);
  await loadModel(fuseModel);
  const stop = watchEffect(() => {
    if (fuseModelsLoaded.value) {
      loaded.value = true;
      nextTick(() => stop());
    }
  });
};
initialSys();

router.beforeEach(async (to, from, next) => {
  if (to.params.save && isOld.value) {
    await save();
  }
  next();
});

const routes: any[] = [];
watch(
  router.currentRoute,
  (_n, _, onClean) => {
    const meta = currentMeta.value;
    if (meta && "full" in meta && (meta as any).full) {
      enterEdit(() => {
        back();
      });
      onClean(
        togetherCallback([
          showLeftPanoStack.push(ref(false)),
          showRightPanoStack.push(ref(false)),
        ])
      );
    }
  },
  { flush: "post", immediate: true }
);

watchEffect((onCleanup) => {
  if (!fuseModels.value.length) {
    onCleanup(showRightPanoStack.push(ref(false)));
  }
});
</script>

<style lang="scss" scoped>
.add-fuse-model {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 160px;
  z-index: 3;
  bottom: 10px;

  .icon {
    margin-right: 4px;
  }
}
</style>
