<template>
  <template v-if="slides.length">
    <Screen v-if="screening" />
    <Student v-else-if="viewMode === 'student'" :courseid="urlParams.courseid" :type="urlParams.type" />
    <Editor v-else-if="_isPC" />
    <Mobile v-else />
  </template>
  <FullscreenSpin tip="数据初始化中，请稍等 ..." v-else  loading :mask="false" />
</template>



<script lang="ts" setup>
import { onMounted, ref, provide } from 'vue'
import { storeToRefs } from 'pinia'
import { useScreenStore, useMainStore, useSnapshotStore, useSlidesStore } from '@/store'
import { LOCALSTORAGE_KEY_DISCARDED_DB } from '@/configs/storage'
import { deleteDiscardedDB } from '@/utils/database'
import { isPC } from '@/utils/common'
import api from '@/services'

import Editor from './views/Editor/index.vue'
import Screen from './views/Screen/index.vue'
import Mobile from './views/Mobile/index.vue'
import Student from './views/Student/index.vue'
import FullscreenSpin from '@/components/FullscreenSpin.vue'

const _isPC = isPC()

const mainStore = useMainStore()
const slidesStore = useSlidesStore()
const snapshotStore = useSnapshotStore()
const { databaseId } = storeToRefs(mainStore)
const { slides } = storeToRefs(slidesStore)
const { screening } = storeToRefs(useScreenStore())

// 视图模式：'editor', 'student', 'screen'
// 支持通过URL参数直接访问学生模式
const getInitialViewMode = () => {
  // 检查URL参数
  const urlParams = new URLSearchParams(window.location.search)
  const modeFromUrl = urlParams.get('mode')
  
  if (modeFromUrl === 'student') {
    return 'student'
  }
  
  // 检查localStorage
  const modeFromStorage = localStorage.getItem('viewMode')
  if (modeFromStorage) {
    return modeFromStorage
  }
  
  // 默认返回编辑模式
  return 'editor'
}

// 获取URL参数中的courseid和type
const getUrlParams = () => {
  const urlParams = new URLSearchParams(window.location.search)
  return {
    courseid: urlParams.get('courseid'),
    type: urlParams.get('type')
  }
}

const urlParams = getUrlParams()

const viewMode = ref(getInitialViewMode())

// 全局切换视图模式的函数
const switchViewMode = (mode: string) => {
  viewMode.value = mode
  localStorage.setItem('viewMode', mode)
  
  // 更新URL参数
  const url = new URL(window.location.href)
  if (mode === 'student') {
    url.searchParams.set('mode', 'student')
  }
  else {
    url.searchParams.delete('mode')
  }
  
  // 使用 history.pushState 更新URL，不刷新页面
  window.history.pushState({}, '', url.toString())
}

// 使用provide提供切换函数，供子组件调用
provide('switchViewMode', switchViewMode)

if (import.meta.env.MODE !== 'development') {
  window.onbeforeunload = () => false
}

onMounted(async () => {
  const slides = await api.getFileData('slides')
  slidesStore.setSlides(slides)

  await deleteDiscardedDB()
  snapshotStore.initSnapshotDatabase()
  
  // 监听视图模式切换事件
  window.addEventListener('viewModeChanged', (event: any) => {
    if (event.detail) {
      switchViewMode(event.detail)
    }
  })
})

// 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
window.addEventListener('beforeunload', () => {
  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>