<template>
  <div class="camera-player">
    <video
      ref="videoPlayer"
      class="video-js"
      controls
      autoplay
      muted
      playsinline
      style="width: 100%; height: 100%;"
    ></video>
    <div v-if="loading" class="player-loading">
      <i class="el-icon-loading"></i> 正在加载视频流...
    </div>
    <div v-if="error" class="player-error">
      <i class="el-icon-warning"></i> {{ error }}
    </div>
  </div>
</template>

<script>
// 动态导入 hls.js（如果未安装，需要先安装：npm install hls.js --save）
let Hls = null
try {
  Hls = require('hls.js')
} catch (e) {
  console.warn('hls.js 未安装，HLS 播放功能将不可用')
}

export default {
  name: 'CameraPlayer',
  props: {
    src: {
      type: String,
      required: true
    },
    type: {
      type: String,
      default: 'hls' // 'hls' or 'flv'
    }
  },
  data() {
    return {
      hls: null,
      loading: true,
      error: null
    }
  },
  watch: {
    src: {
      handler(newSrc) {
        if (newSrc) {
          this.loadStream(newSrc)
        }
      },
      immediate: true
    }
  },
  beforeDestroy() {
    this.destroy()
  },
  methods: {
    loadStream(url) {
      this.destroy()
      this.loading = true
      this.error = null

      if (this.type === 'hls') {
        this.loadHls(url)
      } else if (this.type === 'flv') {
        // FLV support would go here (requires flv.js)
        this.error = 'FLV 播放暂未实现，请使用 HLS'
        this.loading = false
        this.$emit('error', this.error)
      } else {
        this.error = '不支持的播放类型：' + this.type
        this.loading = false
        this.$emit('error', this.error)
      }
    },
    
    loadHls(url) {
      const video = this.$refs.videoPlayer
      if (!video) return

      if (Hls && Hls.isSupported()) {
        this.hls = new Hls({
          enableWorker: true,
          lowLatencyMode: false
        })
        
        this.hls.loadSource(url)
        this.hls.attachMedia(video)
        
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          this.loading = false
          video.play().catch(err => {
            console.warn('自动播放失败，需要用户交互', err)
            this.error = '请点击播放按钮开始播放'
            this.loading = false
          })
        })
        
        this.hls.on(Hls.Events.ERROR, (event, data) => {
          if (data.fatal) {
            switch (data.type) {
              case Hls.ErrorTypes.NETWORK_ERROR:
                this.error = '网络错误，正在重试...'
                this.hls.startLoad()
                break
              case Hls.ErrorTypes.MEDIA_ERROR:
                this.error = '媒体错误，正在恢复...'
                this.hls.recoverMediaError()
                break
              default:
                this.error = '播放失败，请检查流地址'
                this.hls.destroy()
                this.loading = false
                this.$emit('error', this.error)
                break
            }
          }
        })
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // Native HLS support (Safari)
        video.src = url
        video.addEventListener('loadedmetadata', () => {
          this.loading = false
        })
        video.addEventListener('error', () => {
          this.error = '播放失败，请检查流地址'
          this.loading = false
          this.$emit('error', this.error)
        })
      } else {
        this.error = '浏览器不支持 HLS 播放，请安装 hls.js 或使用支持 HLS 的浏览器'
        this.loading = false
        this.$emit('error', this.error)
      }
    },
    
    destroy() {
      if (this.hls) {
        this.hls.destroy()
        this.hls = null
      }
      const video = this.$refs.videoPlayer
      if (video) {
        video.src = ''
        video.load()
      }
    }
  }
}
</script>

<style scoped>
.camera-player {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
}

.player-loading,
.player-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 14px;
  z-index: 10;
}

.player-error {
  color: #f56c6c;
}

.video-js {
  width: 100%;
  height: 100%;
}
</style>