<template>
  <header class="sticky inset-x-0 top-0 w-full bg-neutral-10 z-10">
      <Header/>
      <Navbar/>
  </header>
  <main class="w-full">
    <Loading v-if="loadingStore.isLoading" />
    <router-view></router-view>
  </main>
</template>

<script>
import { storeToRefs } from 'pinia';
import LoadingStore from '@/stores/loading.js';
import AllMapDataStore from '@/stores/allMapData.js';
import ConformanceStore from '@/stores/conformance.js';
import Header from "@/components/Header.vue";
import Navbar from "@/components/Navbar.vue";
import Loading from '@/components/Loading.vue';
import { leaveFilter, leaveConformance } from '@/module/alertModal.js';

export default {
  name: 'MainContainer',
  setup() {
    const loadingStore = LoadingStore();
    const allMapDataStore = AllMapDataStore();
    const conformanceStore = ConformanceStore();
    const { tempFilterId, createFilterId,  temporaryData, postRuleData, ruleData } = storeToRefs(allMapDataStore);
    const {  conformanceLogTempCheckId, conformanceFilterTempCheckId } = storeToRefs(conformanceStore);

    return { loadingStore, temporaryData, tempFilterId, createFilterId, postRuleData, ruleData, conformanceLogTempCheckId, conformanceFilterTempCheckId, allMapDataStore, conformanceStore };
  },
  components: {
    Header,
    Navbar,
    Loading
  },
  created() {
    // Save token in Headers.
    const token = document.cookie.replace(/(?:(?:^|.*;\s*)luciaToken\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    this.$http.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  },
  beforeRouteUpdate(to, from, next) {
    // 離開 Map 頁時判斷是否有無資料和需要存檔
    if ((from.name === 'Map' || from.name === 'CheckMap') && this.tempFilterId) {
      // 傳給 Map，通知 Sidebar 要關閉。
      this.$emitter.emit('leaveFilter', false);
      leaveFilter(next, this.allMapDataStore.addFilterId, to.path)
    } else if((this.$route.name === 'Conformance' || this.$route.name === 'CheckConformance') && (this.conformanceLogTempCheckId || this.conformanceFilterTempCheckId)) {
      leaveConformance(next, this.conformanceStore.addConformanceCreateCheckId, to.path)
    } else next();
  },
};
</script>
