<script setup lang='ts'>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import { TypeMap, getFullPath } from '~/pages/detail/util'

const props = defineProps({
  d: {
    type: Object,
    required: true,
  },
  // src: {
  //   type: String,
  //   required: true,
  // },
  // poster: {
  //   type: String,
  //   required: false,
  // },
})
const _type_ = 'zbkc_ks'
const theType = TypeMap[_type_]

let currentStatus: number
if (props.d.status === 1) {
  currentStatus = 1
}
else if (props.d.status === 2) {
  currentStatus = 2
}
else if (props.d.status === 3) {
  if (!props.d.vod_mp4_address)
    currentStatus = 3
  else
    currentStatus = 4
}

// :src="getFullPath(detail[theType.video])"
const poster = getFullPath(props.d[theType.img])

const videoPlayerRef = shallowRef()
const player = ref()

function getSourceType(src: string) {
  const ext = src.split('.').pop()
  // if (ext?.includes('/'))
  //   return 'application/x-mpegURL'
  // else
  if (ext === 'm3u8')
    return 'application/x-mpegURL'
  else
    return `video/${ext}`
}

function initPlayer(src: string, controlBarChildren: string[] = [
  'PlayToggle', // 播放
  'NextBtn', // 下一个
  'CurrentTimeDisplay', // 当前时间
  'ProgressControl', // 进度条
  'DurationDisplay', // 时长
  'VolumePanel', // 音量
  'PlaybackRateMenuButton', // 倍速
  'FullscreenToggle', // 全屏
]) {
  return player.value = videojs(
    videoPlayerRef.value as HTMLVideoElement,
    {
      autoplay: false,
      controls: true,
      lang: 'zh-CN',
      playbackRates: [0.5, 1, 1.25, 1.5, 2], // 倍速数组
      controlBar: {
        children: controlBarChildren,
      },
      poster,
      sources: [
        {
          src,
          type: getSourceType(src),
        },
      ],
    },
    () => {
      console.log('player is ready')
    },
  )
}

onMounted(() => {
  if (currentStatus === 2) {
    initPlayer(getFullPath(props.d[theType.video]), [
      'PlayToggle', // 播放
      'NextBtn', // 下一个
      'CurrentTimeDisplay', // 当前时间
      'ProgressControl', // 进度条
      'DurationDisplay', // 时长
      'VolumePanel', // 音量
      'FullscreenToggle', // 全屏
    ])
  }

  else if (currentStatus === 4) {
    initPlayer(getFullPath(props.d.vod_mp4_address))
  }
})

onUnmounted(() => {
  if (player.value)
    player.value.dispose()
})
</script>

<template>
  <video
    v-if="currentStatus === 2 || currentStatus === 4" ref="videoPlayerRef" :poster="poster"
    class="video-js w-100vw h-56.25vw"
  />
  <div v-else class="w-100vw h-56.25vw flex justify-center items-center bg-dark-700 text-light-50 text-16px">
    {{ currentStatus === 1 ? '直播暂未开始，请稍后...' : '回放视频生成中，请稍后...' }}
  </div>
</template>
