<template>  
  <router-view/>
  <WaterMake></WaterMake>
</template>

<script lang="ts" setup>
import { onMounted, ref,provide } from 'vue';
import { deleteDiscardedDB } from './utils/database';
import { useFontStore, useMainStore, useSnapshotStore, useUserStore } from '@/store'
import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage';
import { storeToRefs } from 'pinia';
import { injectKeyTemplate } from './types/injectKey';
import UserServices from './services/UserService';
import WaterMake from './components/WaterMake/Index.vue'

const { token, userInfo } = storeToRefs(useUserStore())
const snapshotStore = useSnapshotStore()
const mainStore = useMainStore()
const { databaseId } = storeToRefs(mainStore)
const searchData = ref({} as any)
provide(injectKeyTemplate,searchData)
const autoSave = ref(0)
provide("SellTravelSave",autoSave)

onMounted(async () => {
  await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
  mainStore.setAvailableFonts()
})
// if (process.env.NODE_ENV === 'production') {
//     window.onbeforeunload = () => false
// }
// 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
window.addEventListener('unload', () => {
  const discardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  const discardedDBList: string[] = discardedDB ? JSON.parse(discardedDB) : []

  discardedDBList.push(databaseId.value)

  const newDiscardedDB = JSON.stringify(discardedDBList)
  localStorage.setItem(LOCALSTORAGE_KEY_DISCARDED_DB, newDiscardedDB)
})
useFontStore().loadAllFonts()

const healthCheckHandler = async ()=>{
  if(token.value && token.value!=''){
    await UserServices.CollectAsync()
  }
}

const vipTips = () =>{
    let Dates = new Date()
    let y = Dates.getFullYear()
    let m = Dates.getMonth()+1
    let d = Dates.getDay()
    userInfo.value.BuyvipTipsDate = y + '-' + (m>9?m:'0'+m) + '-' + (d>9?d:'0'+d)
}

setInterval(() => {
  healthCheckHandler()
}, 1000*60)

onMounted(() => {
  const rules = ['/editor/','/team_editor/','/manager_template/','/create_template/']
  window.onbeforeunload = function(event) {
    const currentUrl = window.location.pathname;
    const shouldShowWarning = rules.some(rule => currentUrl.includes(rule));
    if (shouldShowWarning) {
      event.preventDefault();
      // const confirmationMessage = "你确定要离开这个页面吗？离开前注意检查是否已经保存";
      // event.returnValue = confirmationMessage;
      return false;
    }
    return null;
  }
})

// vipTips()
</script>

<style lang="scss">
@import url('@/assets/styles/common.css');
#app {
  height: 100%;
}

</style>