<template>
  <div class="module-ten">
    <!-- <div class="module-title">模块十</div> -->
    <div class="module-body">
      <div class="video-wrapper">
        <video class="video-ats" controls autoplay muted playsinline loop></video>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, nextTick, onBeforeUnmount } from 'vue'
import HLS from 'hls.js'

let hlsInstance = null

const initVideo = async () => {
  await nextTick()
  setTimeout(() => {
    const video = document.querySelector('.video-ats')
    if (!video) return
    
    if (hlsInstance) {
      hlsInstance.destroy()
      hlsInstance = null
    }
    
    const videoUrl = `http://10.107.7.19:8100/main.m3u8`
    
    if (HLS.isSupported()) {
      const hls = new HLS({
        debug: true,
        liveSyncDuration: 3, 
        maxBufferLength: 30
      })
      hlsInstance = hls
      
      hls.on(HLS.Events.MANIFEST_PARSED, () => {
        console.log('视频 manifest 解析完成')
      })
      
      hls.on(HLS.Events.LEVEL_LOADED, () => {
        console.log('视频级别加载完成')
      })
      
      hls.on(HLS.Events.FRAME_LOADED, () => {
        console.log('视频帧加载完成')
      })
      
      hls.on(HLS.Events.ERROR, (event, data) => {
        console.error('视频 HLS 错误:', event, data)
        if (data.fatal) {
          hls.destroy()
        }
      })
      
      hls.on(HLS.Events.MEDIA_PLAYING, () => {
        console.log('视频开始播放')
      })
      
      hls.loadSource(videoUrl)
      hls.attachMedia(video)
      
      video.play().then(() => {
        console.log('视频开始播放')
      }).catch(err => {
        console.error('视频播放失败:', err)
      })
    } else if (video.canPlayType('application/x-mpegURL')) {
      video.src = videoUrl
      video.load()
      video.play().then(() => {
        console.log('视频开始播放')
      }).catch(err => {
        console.error('视频播放失败:', err)
      })
    } else {
      console.error('浏览器不支持 HLS')
    }
  }, 500)
}

onMounted(() => {
  initVideo()
})

onBeforeUnmount(() => {
  if (hlsInstance) {
    hlsInstance.destroy()
    hlsInstance = null
  }
})
</script>

<style lang="scss" scoped>
.module-ten {
  width: 2923px;
  height: 535px;
  position: absolute;
  left: 17px;
  top: 957px;
  display: flex;
  flex-direction: column;
  background: url('/imgs/mtenbg.png') no-repeat center center;
  background-size: cover;

  .module-title {
    height: 40px;
    line-height: 40px;
    padding: 0 16px;
    font-size: 16px;
    font-weight: 600;
    color: #00d4ff;
    background: rgba(0, 212, 255, 0.1);
    border-bottom: 1px solid rgba(0, 212, 255, 0.2);
  }

  .module-body {
    flex: 1;
    position: relative;

    .video-wrapper {
      position: absolute;
      left: 35px;
      top: 35px;
      width: 2851px;
      height: 455px;
      opacity: 1;

      .video-ats {
        width: 100%;
        height: 100%;
        object-fit: fill;
        display: block;
      }
    }
  }
}
</style>
