<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)"
      >
        <HlsPlayer :url="item.hlsUrl" />
        <div class="item-unfollow" @click.stop="handleUnfollow(item.cameraIndexCode, index)">取消关注</div>
        <!-- <div>
          <p class="item-title--primary">
            {{ item.cameraName || item.cameraIndexCode }}
          </p>
         
          <video
            class="item-img"
            :id="'video' + index"
            muted
            autoplay
            :controls="false"
            controlsList="nodownload"
          >
            <source src="" type="application/x-mpegURL" />
          </video>
        </div> -->
      </li>
    </ul>
  </div>
  <video-dialog v-model="videoShow" :src="src" :isCollect="isCollect" :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'

  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 hlsRefs = []
  let timer = null

  const handleItem = (item) => {
    src.value = item.hlsUrl
    cameraIndexCode.value = item.cameraIndexCode
	isCollect.value = item.isCollect
    videoShow.value = true
  }

  const postVideoRemain = () => {
    timer = setInterval(() => {
      postVideoRemainApi({
        cameraIndexCode: list.value.map((item) => item.cameraIndexCode)
      })
    }, 5000)
  }

  const getPreviewUrl = async (code) => {
    let res = await getPreviewUrlApi({
      cameraIndexCode: code,
      type: 'hls'
    })
    src.value = res.data.url
    videoShow.value = true
  }
  const getVideoList = async () => {
    let res = await getColletListApi({
      pageNum: 1,
      pageSize: 5
    })
    list.value = res.data
	console.log(list.value,'list.valuelist.valuelist.valuelist.value')
    postVideoRemain()
    // nextTick(() => {
    //   list.value.forEach(async (item, index) => {
    //     var video = document.getElementById(`video${index}`)
    //     const hls = new Hls({
    //       enableWorker: false, // 禁用 Worker 来避免额外的线程
    //       enableSoftwareAES: true, // 使用软件解码器以避免硬件解码的额外请求
    //       cache: true, // 启用缓存
    //       maxBufferLength: 10, // 最大缓冲长度（秒）
    //       maxMaxBufferLength: 15, // 缓冲区长度的上限
    //       maxBufferSize: 20 * 1000 * 1000 // 最大缓冲大小（字节）
    //     })
    //     hls.loadSource(item.hlsUrl)
    //     hls.attachMedia(video)
    //     hls.on(Hls.Events.MANIFEST_PARSED, () => {
    //       video.play()
    //     })
    //     hlsRefs.push(hls)
    //   })
    // })
  }

  // 释放hls实例
  const clearHlsRefs = () => {
    if (hlsRefs.length > 0) {
      hlsRefs.map((item) => {
        item.destroy()
      })
      hlsRefs = []
    }
    getVideoList()
  }
  const onVideoCollect = () => {
    pubSub.subscribe('videoCollect', () => {
      clearHlsRefs()
    })
  }

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

  onMounted(() => {
    onVideoCollect()
    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>
