<template>
  <div class="video-component">
    <video v-if="isM3U8" ref="videoRef" class="video" :controls="controls">
      您的浏览器不支持播放此视频。
    </video>
    <video
      v-else-if="isMP4"
      class="video"
      :autoplay="autoplay"
      :controls="controls"
    >
      <source :src="videoSrc" type="video/mp4" />
    </video>
    <iframe v-else class="video" :src="videoSrc" frameborder="0" />
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onMounted,
  PropType,
  ref,
  nextTick,
} from 'vue'
declare const Hls: any

export default defineComponent({
  name: 'VideoComponent',
  props: {
    videoSrc: {
      type: String as PropType<string>,
      required: true,
    },
    autoplay: {
      type: String as PropType<string>,
      default: 'autoplay',
    },
    controls: {
      type: Boolean as PropType<boolean>,
      default: true,
    },
  },
  setup(props) {
    const videoRef = ref<any | null>(null)
    const isM3U8 = computed(
      () => props.videoSrc && props.videoSrc.indexOf('m3u8') >= 0
    )
    const isMP4 = computed(
      () =>
        props.videoSrc &&
        (props.videoSrc.indexOf('mp4') >= 0 ||
          props.videoSrc.indexOf('mov') >= 0)
    )
    const init = () => {
      if (!videoRef.value) return

      if (Hls.isSupported()) {
        const hls = new Hls()
        hls.loadSource(props.videoSrc)
        hls.attachMedia(videoRef.value)
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          if (props.autoplay === 'autoplay') {
            videoRef.value.play()
          }
        })
      } else if (videoRef.value.canPlayType('application/vnd.apple.mpegurl')) {
        videoRef.value.src = props.videoSrc
        videoRef.value.addEventListener('canplay', () => {
          if (props.autoplay === 'autoplay') {
            videoRef.value.play()
          }
        })
      }
    }
    onMounted(async () => {
      if (!isM3U8.value) return
      await nextTick()
      init()
    })
    return {
      videoRef,
      isM3U8,
      isMP4,
    }
  },
})
</script>

<style lang="stylus" scoped>
.video-component
  width 100%
  height 100%
  .video
    width 100%
</style>
