<template>
  <div class="video-component">
    <video
      v-if="isVideo"
      ref="videoRef"
      class="video"
      autoplay="autoplay"
      controls
    >
      您的浏览器不支持播放此视频。
    </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,
    },
  },
  setup(props) {
    const videoRef = ref<any | null>(null)
    const isVideo = computed(
      () =>
        props.videoSrc &&
        (props.videoSrc.indexOf('m3u8') >= 0 ||
          props.videoSrc.indexOf('mp4') >= 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, () => {
          videoRef.value.play()
        })
      } else if (videoRef.value.canPlayType('application/vnd.apple.mpegurl')) {
        videoRef.value.src = props.videoSrc
        videoRef.value.addEventListener('canplay', () => {
          videoRef.value.play()
        })
      }
    }
    onMounted(async () => {
      await nextTick()
      init()
    })
    return {
      videoRef,
      isVideo,
    }
  },
})
</script>

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