<script setup lang="ts">
import AppVideoPlayer from '@/components/base/AppVideoPlayer.vue'
import type { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js'
import { useStorage } from '@vueuse/core'
import { getCoursePlayInfo } from '../api'
import type { PlayItemTypes } from '../types'

const options = $ref<VideoJsPlayerOptions>()

const { query } = useRoute()
const sourceId = $ref(query.source_id as string)

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

function fetchInfo() {
  getCoursePlayInfo({ source_id: sourceId }).then(res => {
    playList = res.data.playing_list
    changeSrc(currentPlayList[0])
  })
}
onMounted(fetchInfo)

let src = $ref({ type: '', src: '' })
// 跳过片头
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
  console.log(videoJsPlayer)
}
function changeSrc(data: PlayItemTypes) {
  // src = { src: data.PlayURL, type: 'application/x-mpegURL' }
  src = { src: data.PlayURL, type: 'video/mp4' }
}
</script>

<template>
  <AppVideoPlayer :options="options" :src="src" @ready="onReady"></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>
</template>

<style lang="scss" scoped>
.vjs-icon-hd,
.vjs-icon-cog {
  font-size: 1.8em;
}
</style>
