<template>
  <div>
    <video ref="videoElement" controls autoplay></video>
  </div>
</template>

<script>
import flvjs from 'flv.js'

export default {
  name: 'FlvPlayer',
  props: {
    url: {
      type: String,
      required: true
    },
    type: {
      type: String,
      default: 'flv' // 'flv' 或 'mp4'
    },
    isLive: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      flvPlayer: null
    }
  },
  mounted() {
    this.initPlayer()
  },
  beforeDestroy() {
    this.destroyPlayer()
  },
  methods: {
    initPlayer() {
      if (flvjs.isSupported()) {
        this.flvPlayer = flvjs.createPlayer({
          type: this.type,
          url: this.url,
          isLive: this.isLive
        })
        
        this.flvPlayer.attachMediaElement(this.$refs.videoElement)
        this.flvPlayer.load()
        
        this.flvPlayer.play().catch(e => {
          console.error('播放错误:', e)
        })
      } else {
        console.error('当前浏览器不支持flv.js')
      }
    },
    destroyPlayer() {
      if (this.flvPlayer) {
        this.flvPlayer.pause()
        this.flvPlayer.unload()
        this.flvPlayer.detachMediaElement()
        this.flvPlayer.destroy()
        this.flvPlayer = null
      }
    }
  }
}
</script>