<template>
  <header>
    <Header/>
    <Navbar/>
  </header>
  <main>
    <Loading v-if="loadingStore.isLoading" />
    <router-view>
    </router-view>
  </main>
</template>

<script>
import { storeToRefs } from 'pinia';
import LoginStore from '@/stores/login.js';
import LoadingStore from '@/stores/loading.js';
import AllMapDataStore from '@/stores/allMapData.js';
import Header from "@/components/Header.vue";
import Navbar from "@/components/Navbar.vue";
import Loading from '@/components/Loading.vue';

export default {
  name: 'MainContainer',
  setup() {
    const loginStore = LoginStore();
    const loadingStore = LoadingStore();
    const allMapDataStore = AllMapDataStore();
    const { checkLogin } = loginStore;
    const { tempFilterId, temporaryData, postRuleData } = storeToRefs(allMapDataStore);

    return { checkLogin, loadingStore, temporaryData, tempFilterId, postRuleData };
  },
  watch: {
    $route: function(to, from) {
      if(to.name !== 'Discover') {
        this.tempFilterId = null;
        this.temporaryData = []
        this.postRuleData = []
      }
      // console.log(to, from);
      // if(to.name === 'Discover'){
      //   this.$swal({
      //       title: '請問是否要離開頁面?',
      //       showCancelButton: true,
      //       confirmButtonText: '是',
      //       cancelButtonText: '否',
      //     }).then((result) => {
      //       if (result.isConfirmed) {
      //         window.history.back() // 或 window.close()
      //       } else {
      //         console.log('no')
      //       }
      //     })
      // }
    }
  },
  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}`;
    /**
     * check login for 'my-account' api
     */
    this.checkLogin();
  },
  beforeRouteUpdate(to, from, next) {
    if (from.name === 'Discover') {
      this.$swal({
        title: '請問是否要離開頁面?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '是',
        cancelButtonText: '否',
      }).then((result) => {
        if (result.isConfirmed) {
          console.log('yes')
          next()
        } else {
          console.log('no')
          next(false)
        }
      })
    } else {
      next()
    }
  },
};
</script>
