<template>
  <div class="core-video">
    <div class="title">核心景区视频</div>
    <div class="btn-all" @click="allShow = true" />
    <ul class="list">
      <li
        class="item"
        :style="{ backgroundImage: `url(${primary})` }"
        v-for="(item, index) in list"
        :key="index"
        @click="handleItem(item)"
      >
        <video
            class="item-img"
            :id="'video' + index"
            muted
            autoplay
            :controls="false"
        ></video>
        <div class="item-unfollow" @click.stop="handleUnfollow(item.cameraIndexCode, index)">取消关注</div>
      </li>
    </ul>
  </div>
  <video-dialog v-model="videoShow" :src="src" :isCollect="isCollect" :isDiy="isDiy" :cameraIndexCode="cameraIndexCode" />
  <all-list v-model="allShow" />
</template>

<script setup>
  import allList from './allList'

  import primary from '@/assets/images/item-primary.png'
  import error from '@/assets/images/item-error.png'

  import { getVideoListApi, getPreviewUrlApi,getColletListApi } from '@/api/home'
  import { postVideoCollectApi, postVideoRemainApi } from '@/api/monitor'

  import Hls from 'hls.js'
  import pubSub from 'pubsub-js'

  import { useWebSocket } from '@/hooks/socket'
  import { mode, socketBaseUrl, proSocketBaseUrl } from '@/utils/config'
  import WebRTCWhep from 'whepts'

  const { dataRes } = useWebSocket(
    `${mode == 'dev' ? socketBaseUrl : proSocketBaseUrl}/ws/securityAlerts`
  )

  watch(
    () => dataRes.value,
    (val) => {
      getPreviewUrl(val.data.cameraIndexCode)
    }
  )


let isCollect = ref(0)
  let list = ref([])
  let src = ref('')
  let cameraIndexCode = ref('')
  let videoShow = ref(false)
  let allShow = ref(false)
  let webrtcRefs = []
  let hlsRefs = []
  let timer = null
  let isDiy = ref(0)
  const handleItem = async (item) => {
    let res = await getPreviewUrlApi({
      cameraIndexCode: item.cameraIndexCode,
      type: 'hls'
    })
    src.value = res.data.url
    cameraIndexCode.value = item.cameraIndexCode
    isCollect.value = item.isCollect
    isDiy.value = item.isDiy
    videoShow.value = true
  }

  const postVideoRemain = () => {
    // timer = setInterval(() => {
		// if(!list.value.length) return false;
    //   postVideoRemainApi({
    //     cameraIndexCode: list.value.map((item) => item.cameraIndexCode)
    //   })
    // }, 1500)
  }

  const getPreviewUrl = async (code) => {
    let res = await getPreviewUrlApi({
      cameraIndexCode: code,
      type: 'hls'
    })
    src.value = res.data.url
    videoShow.value = true
  }
  const createPlayer = (cameraIndexCode,videoElement) => {
    getPreviewUrlApi({
      type: 'hls',
      cameraIndexCode: cameraIndexCode
    }).then(res=>{
      const url = res.data.url;
      if(url.startsWith('http://192.168.77.200:8050/')){
        const player = new WebRTCWhep({
          url:url, // WHEP 服务器地址
          container: videoElement, // 视频播放容器
          onError: (error) => {
            console.error('播放错误:', error)
          }
        })
        webrtcRefs.push(player)
      }
      else{
        const player = new Hls({
          maxBufferLength: 10, // 最大缓冲长度（秒）
          maxMaxBufferLength: 15, // 缓冲区长度的上限
          maxBufferSize: 30 * 1000 * 1000 // 最大缓冲大小（字节）
        })
        player.loadSource(url)
        player.attachMedia(videoElement)
        player.on(Hls.Events.MANIFEST_PARSED, () => {
          videoElement.play()
        })
        player.on(Hls.Events.ERROR, (event, data) => {
          // 根据错误类型进行处理
          if (data.fatal) {
            switch (data.type) {
              case Hls.ErrorTypes.NETWORK_ERROR:
                console.log('网络错误，尝试重新加载');
                player.startLoad();
                break;
              case Hls.ErrorTypes.MEDIA_ERROR:
                console.log('媒体错误，尝试修复');
                player.recoverMediaError();
                break;
              default:
                console.log('无法恢复的错误，销毁播放器');
                // hls.destroy();
                break;
            }
          }
        })
        hlsRefs.push(player)
      }
    })
  }
  const getVideoList = async () => {
    let res = await getColletListApi({
      pageNum: 1,
      pageSize: 5
    })
    list.value = res.data
	if (timer) clearInterval(timer)
    nextTick(() => {
      list.value.forEach(async (item, index) => {
        var videoElement = document.getElementById(`video${index}`)
        createPlayer(item.cameraIndexCode,videoElement);
      })
    })
  }
  watch(
    () => list.value,
    (val) => {
      if(val.length){
  		  postVideoRemain()
  	  }
    }
  )
  // 释放hls实例
  const clearHlsRefs = () => {
    if (hlsRefs.length > 0) {
      hlsRefs.map((item) => {
        item.destroy()
      })
      hlsRefs = []
    }
    if(webrtcRefs.length>0){
      webrtcRefs.map((item) => {
        try{
          item.close()
        }catch (e) {

        }
      })
      webrtcRefs = [];
    }
    getVideoList()
  }
  const onVideoCollect = () => {
    pubSub.subscribe('videoCollect', () => {
      clearHlsRefs()
	  getVideoList()
    })
  }

  const handleUnfollow = async (id, index) => {
    await postVideoCollectApi({
      cameraIndexCode:id,
      isCollect: 0
    })
    clearHlsRefs()
  }

  onMounted(() => {
    onVideoCollect()
    getVideoList()
	pubSub.subscribe('videoIsDiy', (msg, data) => {
		console.log(data,'收藏 ++++++++++++++')
		getVideoList()



	})
  })

  onUnmounted(() => {
    if (timer) clearInterval(timer)
  })
</script>

<style lang="scss" scoped>
  :deep(.el-loading-mask) {
    background-color: transparent !important;
  }
  .core-video {
    position: relative;
    margin: vw(8);
    width: vw(300);
    border-radius: vw(2);
    background-image: url('@/assets/images/bg-1.png');
    background-size: 100% 100%;

    .title {
      width: 100%;
      height: vh(26);
      text-align: center;
      line-height: vh(26);
      font-size: vw(16);
      font-weight: 800;
      color: #fff;
    }
    .btn-all {
      cursor: pointer;
      position: absolute;
      right: vw(0);
      top: vw(0);
      z-index: 999;
      width: vw(60);
      height: vw(24);
      background-image: url('@/assets/images/all.png');
      background-size: 100% 100%;
    }

    .list {
      overflow-y: auto;
      overflow-x: hidden;
      height: vh(1026);
      padding: vw(8);
      /* 滚动条整体样式 */
      &::-webkit-scrollbar {
        width: vw(0); /* 滚动条的宽度 */
      }

      /* 滚动条轨道 */
      &::-webkit-scrollbar-track {
        background: #f1f1f1; /* 轨道的背景色 */
      }

      /* 滚动条滑块 */
      &::-webkit-scrollbar-thumb {
        background: #888; /* 滑块的背景色 */
        border-radius: 5px; /* 滑块的圆角 */
      }

      /* 当鼠标悬停在滚动条上时滑块的样式 */
      &::-webkit-scrollbar-thumb:hover {
        background: #555; /* 滑块的背景色 */
      }
    }

    .item {
      position: relative;
      margin-bottom: vh(10);
      padding: vw(10);
      background-size: 100% 100%;
      &-unfollow {
        cursor: pointer;
        display: none;
        position: absolute;
        right: vw(4);
        top: vw(4);
        z-index: 99999;
        width: vw(64);
        height: vw(30);
        text-align: center;
        line-height: vw(30);
        font-weight: 400;
        font-size: vw(12);
        color: #ffffff;
        background-image: url('@/assets/images/unfollow.png');
        background-size: 100% 100%;
      }
      &:hover {
        .item-unfollow {
          display: block;
        }
      }
      &-title {
        position: absolute;
        bottom: 0;
        width: 100%;
        padding: vw(10);
        color: #fff;
        font-size: vw(14);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        z-index: 999;
      }
      &-title--error {
        @extend .item-title;
        background-color: rgba(226, 27, 27, 0.72);
      }
      &-title--primary {
        @extend .item-title;
        background-color: rgba(4, 30, 69, 0.72);
      }
      &-img {
        width: 100%;
        height: vh(164);
        display: block;
        object-fit: cover;
      }
    }
  }
</style>
