<template>
  <div class="z-dialog">
    <el-dialog v-model="modelValue" align-center :modal="false" :show-close="false">
      <img class="close" src="@/assets/images/close.png" @click="handleClose" />
      <title2 title="核心景区监控" />
      <ul class="list">
        <li
          class="item"
          :style="{ backgroundImage: `url(${primary})` }"
          v-for="(item, index) in list"
          :key="index"
          @click="handleItem(item)"
        >
          <div class="item-unfollow" @click.stop="handleCollect(item.cameraIndexCode, index)">取消关注</div>
          <video class="item-video" :id="'videoall' + index" muted autoplay :controls="false">
            <source type="application/x-mpegURL" />
          </video>
          <p>
            <span> {{ item.cameraName || item.cameraIndexCode }}</span>
          </p>
        </li>
      </ul>
      <div class="pagination">
        <el-pagination
          v-model:current-page="params.pageNum"
          :page-size="params.pageSize"
          :total="total"
          background
          layout="prev, pager, next"
          @current-change="pageNumChange"
        />
      </div>
    </el-dialog>
  </div>
  <video-dialog v-model="videoShow" :src="src" :isDiy="isDiy" :isCollect="isCollect" :cameraIndexCode="cameraIndexCode" />
</template>

<script setup>
import {getVideoListApi, getColletListApi, getPreviewUrlApi} from '@/api/home'
  import { postVideoCollectApi } from '@/api/monitor'

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

  import Hls from 'hls.js'
  import pubSub from 'pubsub-js'
  import WebRTCWhep from "whepts";

  let modelValue = defineModel()
  let isCollect = ref(0)
  let list = ref([])
  let hlsRefs = []
  let webrtcRefs = []
  let total = ref(0)
  let src = ref('')
  let cameraIndexCode = ref('')
  let videoShow = ref(false)
  let isDiy = ref(0)
  let params = reactive({
    pageNum: 1,
    pageSize: 15,
    isCollect: 1
  })

  watch(
    () => modelValue.value,
    (val) => {
      if (val) {
        setTimeout(() => {
          getVideoList()
        }, 1000)
      }
    }
  )
  const onVideoCollect = () => {
    pubSub.subscribe('videoCollect', () => {
      clearHlsRefs()
  	  getVideoList()
    })
  }
  const handleItem = async (item) => {
    console.log(item, 'iscollect')
    let res = await getPreviewUrlApi({
      cameraIndexCode: item.cameraIndexCode,
      type: 'hls'
    })
    src.value = res.data.url
    isCollect.value = item.isCollect
    isDiy.value = item.isDiy
    cameraIndexCode.value = item.cameraIndexCode
    videoShow.value = true
  }
  const handleCollect = async (id, index) => {
    await postVideoCollectApi({
      cameraIndexCode:id,
      isCollect: 0
    })
    clearHlsRefs()
    params.pageNum = 1
    getVideoList()
    pubSub.publish('videoCollect')
  }
  const handleClose = () => {
    clearHlsRefs()
    modelValue.value = false
  }
  const clearHlsRefs = () => {
    if (hlsRefs.length > 0) {
      hlsRefs.map((item) => {
        item.destroy()
      })
      hlsRefs = []
    }
    if (webrtcRefs.length > 0) {
      webrtcRefs.map((item) => {
        item.close()
      })
      webrtcRefs = []
    }
  }
  const pageNumChange = () => {
    clearHlsRefs()
    list.value = []
    getVideoList()
  }
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(params)
    list.value = res.data
    total.value = res.total
    nextTick(() => {
      list.value.forEach(async (item, index) => {
        var video = document.getElementById(`videoall${index}`)
        createPlayer(item.cameraIndexCode,video);
      })
    })
  }

  onMounted(() => {
	  onVideoCollect()
  })
  onUnmounted(() => {})
</script>

<style scoped lang="scss">
  .z-dialog {
    :deep(.el-dialog) {
      width: vw(2100);
      padding: vw(8);
      background-image: url('@/assets/images/dialog-bg.png') !important;
      background-size: 100% 100%;
    }
    :deep(.el-dialog__header) {
      padding-bottom: 0 !important;
    }
  }
  .list {
    margin-top: vw(30);
    gap: vw(8);
    height: vh(860);
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .item {
      position: relative;
      width: vw(410);
      height: vh(280);
      padding: vw(12);
      box-sizing: border-box;
      background-image: url('@/assets/images/item-primary.png');
      background-size: 100% 100%;
      &-video {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      > p {
        position: absolute;
        bottom: vw(12);
        width: calc(100% - vw(24));
        padding: vw(10) 0;
        background: rgba(4, 30, 69, 0.72);
        > span {
          padding-left: vw(10);
          font-weight: 400;
          font-size: vw(14);
          line-height: vw(14);
          color: #ffffff;
        }
      }
      &-unfollow {
        cursor: pointer;
        display: none;
        position: absolute;
        right: vw(4);
        top: vw(4);
        z-index: 99;
        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;
        }
      }
    }
  }
  .pagination {
    padding-top: vw(20);
    margin-right: vw(20);
    padding-bottom: vw(20);
    display: flex;
    justify-content: flex-end;
  }
  .close {
    cursor: pointer;
    position: absolute;
    right: vw(20);
    top: vw(20);
    width: vw(60);
    z-index: 9999;
  }
</style>
