<template>
  <div v-if="isFinish" style="height: 100vh;background: rgb(243, 246, 251);">
    <Screen v-if="screening" />
    <Market v-else-if="market"></Market>
    <Editor v-else-if="_isPC" />
    <Mobile v-else />
  </div>
</template>

<script lang="ts" setup>
import { onMounted,ref,provide } from 'vue'
import { storeToRefs } from 'pinia'
import { useScreenStore, useMainStore, useSnapshotStore, useFontStore } from '@/store'
import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
import { deleteDiscardedDB } from '@/utils/database'
import { isPC, query } from './utils/common'
import { userStore } from './store/user'
import { injectKeyTemplate } from '@/types/injectKey'
import ConfigService from '@/services/ConfigService'

import Editor from './views/Editor/index.vue'
import Screen from './views/Screen/index.vue'
import Mobile from './views/Mobile/index.vue'
import Market from './views/Market/Index.vue'
import NewFile from './views/Market/newFile.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const searchData = ref({} as any)
provide(injectKeyTemplate,searchData)

const isFinish = ref(false)


const _isPC = isPC()


const mainStore = useMainStore()
const snapshotStore = useSnapshotStore()
const modelStore = useScreenStore()
const ConfigIdStore = useScreenStore()
const marketStore = useScreenStore()
const isModelStore = useScreenStore()
const TempIdStore = useScreenStore()
const { databaseId } = storeToRefs(mainStore)
const { screening, market, model, ConfigId } = storeToRefs(useScreenStore())
const { userInfo } = storeToRefs(userStore())

if (process.env.NODE_ENV === 'production') {
  window.onbeforeunload = () => false
}
const userLoginHandler = async ()=>{
  let param = query()
  let userId = 1
  let ConfigId = 0 // 9117
  let model = 0
  if(param.uid) userId=parseInt(param.uid)
  if(param.ConfigId) ConfigId=parseInt(param.ConfigId)
  if(param.model) model=parseInt(param.model)
  ConfigIdStore.setConfigId(ConfigId)
  modelStore.setModel(model)
  if(!userInfo.value.EmployeeId){
    try {
      await userStore().setUserLoginAsync(userId,ConfigId) 
      await useFontStore().loadAllFonts()
      if(ConfigId) await GetTripConfig(ConfigId)
    } catch (error) {}
  }else{
    if(ConfigId) await GetTripConfig(ConfigId)
  }
  isFinish.value=true
  if(!ConfigId&&!model) ElMessageBox.confirm(
    '当前没有权限进行任何操作，请联系管理员！',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {})
  .catch(() => {})
  
}

onMounted(async () => {
  await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
  mainStore.setAvailableFonts()
})

/**
 * 根据团期配置编号获取行程详情
 */
const GetTripConfig = async (ConfigId) =>{
  try {
      let queryMsg = {
          ConfigId: ConfigId
      }
      let datasRes = await ConfigService.triptemplateGetTripConfig(queryMsg);
      if (datasRes.data.resultCode == 1) {
          if(datasRes.data.data&&datasRes.data.data.length>0&&datasRes.data.data[0].TempId){
              isModelStore.setIsModel(true)
              marketStore.setMarket(!market)
              TempIdStore.setTempId(datasRes.data.data[0].TempId)
          }
      }else{
        return ElMessage({
          showClose: true,
          message: datasRes.data.message,
          type: 'warning',
        })
      }
  } catch (error) {
      console.log("triptemplate_GetTripConfig", error);
  }
}
userLoginHandler()
// 应用注销时向 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)
})
</script>

<style lang="scss">
#app {
  height: 100%;
}
</style>