<script setup lang="ts">
import type { CourseChapterType, CourseSectionType, CourseResourceType, VideoRecordType, PlayItemType } from '../types'
import type { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js'
import { throttle } from 'lodash'
import { useStorage } from '@vueuse/core'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import AppVideoPlayer from '@/components/base/AppVideoPlayer.vue'
import { getCoursePlayInfo, getVideoRecords, uploadVideoRecords } from '../api'

interface Props {
  chapterList: CourseChapterType[]
}

const props = defineProps<Props>()

const options = $ref<VideoJsPlayerOptions>()

const route = useRoute()
let courseId = $ref<string>('')
let chapterId = $ref<string>('')
let sectionId = $ref<string>('')
let resourceId = $ref<string>('')
let semesterId = $ref<string>('')
watchEffect(() => {
  courseId = route.query.course_id as string
  chapterId = route.query.chapter_id as string
  sectionId = route.query.section_id as string
  resourceId = route.query.resource_id as string
  semesterId = route.query.semester_id as string
})

// 当前章
const chapter = $computed<CourseSectionType>(() => {
  return props.chapterList.find(item => item.id === chapterId)
})
// 当前节
const section = $computed<CourseSectionType>(() => {
  return chapter?.sections.find(item => item.id === sectionId)
})

// 当前节
const resource = $computed<CourseResourceType>(() => {
  return section?.resources.find(item => item.resource_id === resourceId)
})
// 资源视频列表
const videoList = $computed<CourseResourceType[]>(() => {
  const list = section?.resources ?? []
  return list.filter(item => item.resource_type === 2)
})

watchEffect(() => {
  if (videoList.length) {
    const found = videoList.find(item => item.resource_id === resourceId)
    resourceId = found ? resourceId : videoList[0]?.resource_id
  }
})

const progress = reactive<VideoRecordType>({
  cumulative_playing_time: '',
  current_playing_time: 0,
  max_playing_time: 0,
  valid_playing_time: 0,
  watchedTimePoint: []
})

let playList = $ref<PlayItemType[]>([])
const currentPlayList = $computed<PlayItemType[]>(() => {
  return playList.filter(item => item.StreamType === 'video' && item.Format === 'mp4')
})

// 获取视频信息
function fetchInfo() {
  if (!resource?.info.source_id) return
  return getCoursePlayInfo({ source_id: resource.info.source_id }).then(res => {
    playList = res.data.playing_list
    changeSrc(currentPlayList[0])
  })
}
// 获取视频记录
function fetchVideoRecords() {
  if (!resource) return
  getVideoRecords({
    chapter_id: chapterId,
    course_id: courseId,
    section_id: sectionId,
    semester_id: semesterId,
    video_id: resourceId
  }).then(res => {
    const { detail = {} } = res.data
    progress.current_playing_time = detail.current_playing_time ? parseFloat(detail.current_playing_time) : 0
    progress.max_playing_time = detail.max_playing_time ? parseFloat(detail.max_playing_time) : 0
    progress.valid_playing_time = detail.valid_playing_time ? parseFloat(detail.valid_playing_time) : 0
    progress.watchedTimePoint = []
    if (videoJsPlayer && progress.current_playing_time) {
      videoJsPlayer.currentTime(progress.current_playing_time)
    }
  })
}
watchEffect(async () => {
  await fetchInfo()
  fetchVideoRecords()
})
const throttledFn = throttle(
  () => {
    if (progress.watchedTimePoint.length < 5) return
    uploadVideoRecords({
      chapter_id: chapterId,
      course_id: courseId,
      section_id: sectionId,
      semester_id: semesterId,
      video_id: resourceId,
      valid_playing_time: progress.valid_playing_time,
      current_playing_time: progress.current_playing_time,
      max_playing_time: progress.max_playing_time,
      cumulative_playing_time: progress.watchedTimePoint.join(',')
    })
    // 清空已经上传过的观看时间点
    progress.watchedTimePoint = []
  },
  5000,
  { leading: false }
)

let watchedTime = 0
function onTimeUpdate() {
  console.log('onTimeUpdate')
  if (!videoJsPlayer) return
  const time = Math.floor(videoJsPlayer.currentTime() ?? 0)
  // 更新当前播放时间
  progress.current_playing_time = time
  // 观看的最大点
  progress.max_playing_time = Math.max(time, progress.max_playing_time)
  // 观看时间点
  const hasTimePoint = progress.watchedTimePoint.includes(time)
  if (!hasTimePoint) {
    progress.watchedTimePoint.push(time)
  }
  // 更新观看累计时长
  if (time !== watchedTime) {
    watchedTime = time
    // // 增加跳过片头时间
    // if (this.isSkip && !this.progress.pt) {
    //   this.progress.pt = this.skipTime + 20
    // }
    // 默认增加时间
    progress.valid_playing_time = progress.valid_playing_time || 20
    progress.valid_playing_time++
  }
  throttledFn()
}

/**
 * 视频播放器相关
 */
let src = $ref<{ src: string; type: string }>()
// 跳过片头
const isSkip = useStorage('isSkip', false)
// 连续播放
const isAutoPlayNext = useStorage('isAutoPlayNext', false)
// 播放器ready
let isReady = $ref<boolean>(false)
let videoJsPlayer = $ref<VideoJsPlayer | null>()
const onReady = (player: VideoJsPlayer) => {
  videoJsPlayer = player
  isReady = true
}
function changeSrc(data: PlayItemType) {
  // src = { src: data.PlayURL, type: 'application/x-mpegURL' }
  src = { src: data.PlayURL, type: 'video/mp4' }
}
function changeResource(data: CourseResourceType) {
  throttledFn && throttledFn.cancel()
  resourceId = data.resource_id
}
</script>

<template>
  <AppVideoPlayer
    :options="options"
    :src="src"
    @ready="onReady"
    @timeupdate="onTimeUpdate"
    style="width: 100%; height: 510px"
    v-if="src"
  ></AppVideoPlayer>
  <!-- 设置 -->
  <teleport to=".vjs-control-bar" v-if="isReady">
    <el-popover trigger="hover" effect="dark" placement="top" :teleported="false">
      <template #reference>
        <button class="vjs-hd-control vjs-control vjs-button" type="button">
          <span class="vjs-icon-hd"></span>
        </button>
      </template>
      <ul>
        <li v-for="(item, index) in currentPlayList" :key="index" @click="changeSrc(item)">{{ item.Definition }}</li>
      </ul>
    </el-popover>
    <el-popover trigger="hover" effect="dark" placement="top" :teleported="false">
      <template #reference>
        <button class="vjs-cog-control vjs-control vjs-button" type="button">
          <span class="vjs-icon-cog"></span>
        </button>
      </template>
      <ul>
        <li>始终跳过片头 <el-switch v-model="isSkip"></el-switch></li>
        <li>连续播放 <el-switch v-model="isAutoPlayNext"></el-switch></li>
      </ul>
    </el-popover>
  </teleport>
  <swiper :slidesPerView="'auto'" :spaceBetween="30">
    <swiper-slide
      v-for="item in videoList"
      :key="item.id"
      class="video-item"
      :class="{ 'is-active': item.resource_id === resourceId }"
      @click="changeResource(item)"
    >
      <img :src="item.info?.cover" />
      <p>{{ item.info.name }}</p>
    </swiper-slide>
  </swiper>
</template>

<style lang="scss" scoped>
.vjs-icon-hd,
.vjs-icon-cog {
  font-size: 1.8em;
}
.video-item {
  position: relative;
  margin: 20px 0;
  width: 200px;
  height: 100px;
  border-radius: 5px;
  cursor: pointer;
  overflow: hidden;
  box-sizing: border-box;
  p {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 0 10px;
    font-size: 14px;
    line-height: 30px;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    text-align: center;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  &.is-active {
    border: 2px solid var(--main-color);
  }
}
</style>
