<template>
  <template v-if="loaded" style="height: 100%">
    <Header></Header>
    <router-view v-slot="{ Component }">
      <keep-alive>
        <component :is="Component" />
      </keep-alive>
    </router-view>
  </template>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { currentMeta, router } from '@/router'
import { showLeftPanoStack, showRightPanoStack } from '@/env'
import { togetherCallback } from '@/utils'
import { loadModel, fuseModel } from '@/model'
import { 
  enterEdit, 
  isOld, 
  save, 
  initialFuseModels,
  initialScenes,
  initialTaggingStyles, 
  initialTaggings, 
  initialGuides, 
  initialMeasures
} from '@/store'

import Header from './header/index.vue'

const loaded = ref(false)
const initialSys = async () => {
  await Promise.all([
    initialFuseModels(),
    initialScenes()
  ])
  await Promise.all([
    initialTaggingStyles(),
    initialTaggings(),
    initialGuides(),
    initialMeasures()
  ])
  await loadModel(fuseModel)
  loaded.value = true
}
initialSys()

router.beforeEach(async (to, from, next) => {
  if (to.params.save && isOld.value) {
    await save()
  }
  next()
})
watch(currentMeta, (meta, _, onClean) => {
  if (meta && 'full' in meta && meta.full) {
    enterEdit(() => router.back())
    onClean(togetherCallback([
      showLeftPanoStack.push(ref(false)),
      showRightPanoStack.push(ref(false)),
    ]))
  }
}, { flush: 'post', immediate: true })
</script>
