<script setup lang="ts">
import { useLog } from '@/composables/useLog'
const log = useLog({ hasKey: true })

const route = useRoute()
const courseId = $ref(route.query.course_id as string)
const resourceId = $ref(route.query.resource_id as string)
const resourceType = $ref(route.query.resource_type as string)
const url = $ref(route.query.url as string)

// 文件扩展名
const fileExtensionName = $computed(() => {
  return url?.split('.').pop() || ''
})
const officeUrl = $computed(() => {
  if (['pptx', 'doc', 'docx', 'xls', 'xlsx'].includes(fileExtensionName)) {
    return `https://view.officeapps.live.com/op/view.aspx?src=${url}`
  } else {
    return ''
  }
})

// 日志事件
const logEvent = $computed(() => {
  // 其他资料
  if (resourceType === '4') {
    return { event: 'other_infos', action: 'stu_watch_other_infos' }
  }
  // 课件
  if (resourceType === '10') {
    return { event: 'courseware_event', action: 'stu_watch_courseware_action' }
  }
  // 教案
  if (resourceType === '11') {
    return { event: 'lesson_plan_event', action: 'stu_watch_lesson_plan_action' }
  }
})
// 页面初始化完成的时间
const pageLoadedTime = Math.floor(Date.now() / 1000)

// 日志上送
function logUpload() {
  if (!logEvent) return
  console.log('logUpload')
  log.upload({
    event: logEvent.event,
    action: logEvent.action,
    data: {
      course_id: courseId,
      resource_id: resourceId,
      page_dwell_time: Math.floor(Date.now() / 1000) - pageLoadedTime,
      resource_progress: 100
    }
  })
}
let logTimer = 0
onMounted(() => {
  // 日志上送
  logUpload()
  // 10秒上送一次
  logTimer = window.setInterval(() => {
    logUpload()
  }, 1000 * 10)
})
onUnmounted(() => {
  logTimer && window.clearInterval(logTimer)
})
</script>

<template>
  <div style="width: 100%; height: 100vh; overflow: hidden">
    <iframe :src="officeUrl" frameborder="0" style="width: 100%; height: 100vh" v-if="officeUrl"></iframe>
    <object :data="url" style="width: 100%; height: 100vh; object-fit: none" v-else></object>
  </div>
</template>
