<template>
  <view class="monitor-page">
    <!-- 视频播放区域 -->
    <video
      v-if="videoSrc"
      id="monitorVideo"
      class="monitor-video"
      :src="playUrl"
      autoplay
      controls
      show-center-play-btn
      object-fit="contain"
      @error="onVideoError"
    ></video>

    <!-- 加载动画 -->
    <u-loading-page
      :loading="loading"
      loading-text="视频加载中..."
    ></u-loading-page>
  </view>
</template>

<script>
export default {
  data() {
    return {
	  detailItem:null,
      videoSrc: '', // 原始视频地址
      playUrl: '', // 实际播放地址
      isPlaying: true,
      loading: true
    }
  },
  onLoad(options) {
	  // 接收传递的detailItem参数
	  if (options.detailItem) {
	  	try {
	  		this.detailItem = JSON.parse(decodeURIComponent(options.detailItem));
			this.getPlay()
	  	} catch (e) {
	  		console.error('解析detailItem参数失败', e);
	  	}
	  }
    
  },
  methods: {
	  async getPlay() {
		  let params = {
		  	videoIp: this.detailItem.deviceIp,
			factoryNo:this.detailItem.factoryNo,
			account:this.detailItem.deviceAccount,
			pwd:this.detailItem.devicePwd,
			channelId:this.detailItem.channelNo
		  }
	  	let res = await this.$u.api.getPlay(params);
	  	if (res.code == 200) {
	  		this.videoSrc = res.data.hls
			this.initPlayer()
	  	}
	  },
    async initPlayer() {
      // #ifdef H5
      if (this.videoSrc.endsWith('.m3u8')) {
        const video = document.getElementById('monitorVideo')
        const Hls = (await import('hls.js')).default
        if (Hls.isSupported()) {
          const hls = new Hls()
          hls.loadSource(this.videoSrc)
          hls.attachMedia(video)
          hls.on(Hls.Events.MANIFEST_PARSED, () => {
            this.loading = false
          })
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
          video.src = this.videoSrc
          this.loading = false
        }
      } else {
        this.playUrl = this.videoSrc
        this.loading = false
      }
      // #endif

      // #ifdef APP-PLUS
      this.playUrl = this.videoSrc
      this.loading = false
      // #endif
    },
    togglePlay() {
      const video = document.getElementById('monitorVideo')
      if (!video) return
      if (this.isPlaying) {
        video.pause()
      } else {
        video.play()
      }
      this.isPlaying = !this.isPlaying
    },
    goFullScreen() {
      const video = document.getElementById('monitorVideo')
      if (video.requestFullscreen) {
        video.requestFullscreen()
      }
    },
    onVideoError(e) {
      console.error('视频播放错误', e)
      uni.showToast({ title: '视频加载失败', icon: 'none' })
      this.loading = false
    }
  }
}
</script>

<style scoped>
.monitor-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #000;
  height: 100vh;
  position: relative;
}
.monitor-video {
  width: 100%;
  height: 70vh;
  background: #000;
}

</style>
