<script lang="ts">
const DEFAULT_OPTIONS = {
  controls: true,
  autoplay: false,
  controlBar: {
    pictureInPictureToggle: false
  },
  // fluid: true,
  responsive: true,
  playbackRates: [0.5, 1, 1.5, 2]
}
const DEFAULT_EVENTS = [
  'abort',
  'canplay',
  'canplaythrough',
  'durationchange',
  'emptied',
  'ended',
  'error',
  'loadeddata',
  'loadedmetadata',
  'pause',
  'play',
  'playing',
  'progress',
  'ratechange',
  'resize',
  'seeked',
  'seeking',
  'stalled',
  'suspend',
  'timeupdate',
  'volumechange',
  'waiting'
]
</script>

<script setup lang="ts">
import videojs from 'video.js'
import type { VideoJsPlayerOptions, VideoJsPlayer } from 'video.js'
import 'video.js/dist/video-js.css'

interface Props {
  src: string | { src: string; type?: string }
  options?: VideoJsPlayerOptions
}
const props = defineProps<Props>()
const emit = defineEmits(['ready', ...DEFAULT_EVENTS])

let player = $ref<VideoJsPlayer | null>()
const videoRef = $ref<HTMLVideoElement>()

const videoOptions = $computed<VideoJsPlayerOptions>(() => {
  return Object.assign({}, DEFAULT_OPTIONS, props.options)
})

watch(
  () => props.src,
  src => {
    changeSrc(src)
  },
  { deep: true, immediate: true }
)

// 初始化播放器
function initPlayer() {
  if (!videoRef) return
  if (player) {
    player.dispose()
    player = null
  }
  player = videojs(videoRef, videoOptions, function onPlayerReady() {
    changeSrc(props.src)
    // 注册事件
    DEFAULT_EVENTS.forEach(eventName => {
      this.on(eventName, (...arg) => {
        // console.log(eventName, ...arg)
        emit(eventName, ...arg)
      })
    })
    emit('ready', this)
  })
  return player
}
function changeSrc(src: string | { src: string; type?: string }) {
  if (!player || !src) return

  // if (!player.paused()) {
  //   console.log(2)
  //   player.pause()
  // }
  player.src(src)
  // player.load()
  // player.play()
}
onMounted(() => {
  initPlayer()
})
onUnmounted(() => {
  player && player.dispose()
})
</script>

<template>
  <video class="video-js vjs-default-skin vjs-big-play-centered" ref="videoRef"></video>
</template>

<style>
.video-js {
  font-size: 12px;
}
</style>
