<template>
  <div id="app" class="parent">
      <video style="width: 100%;height: 100%;object-fit:fill;" ref="video" muted  autoplay="true" > </video>
     

      <ptz v-if="ptzShow" @childTriggerParent="startVideo" :cameraId="cameraId" />
    </div>
</template>

<script>
import { ref, onMounted, defineProps, defineEmits } from 'vue'

import { ZLMRTCClient } from '@/components/camera/ZLMediaKit-Webrtc-Vue/ZLMRTCClient'

import { CameraApi } from '@/api/logistics/camera'
import { number } from 'vue-types'
import ptz from '@/components/camera/ptz.vue'

const cameraId = ref(1)

const formData = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  ip: undefined,
  port: undefined,
  user: undefined,
  password: undefined,
  rtcServer: undefined,
  rtcServerPort: undefined,
  rtspPort: undefined,
  channel: undefined,
  recorderIp: undefined
})

export default {
  props: {
    cameraId: {
      default: 2
    },
    ptzShow: {
      type: Boolean,
      default: true
    }
  },
 

  setup(props) {
    // console.log(props.ptzShow)
    const video = ref(null)
    const selfVideo = ref(null)
    const url = ref(null)
    const simulcast = ref(null)
    const useCamera = ref(null)
    const audioEnable = ref(null)
    const videoEnable = ref(null)
    const datachannel = ref(null)
    const msgsend = ref(null)
    const msgrecv = ref(null)

    // const streamUrl = ref(document.location.protocol + "//" + window.location.host + "/index/api/webrtc?app=live&stream=test&type=play");
   
    const player = ref(null)
    const recvOnly = ref(true)
    const resolutions = ref([])
    const resolution = ref('')
    // 监听 cameraId 的变化
    watch(() => props.cameraId, (newCameraId, oldCameraId) => {
      // console.log(newCameraId);
      if (newCameraId !== oldCameraId) {
        
      ZLMRTCClient.GetAllScanResolution().forEach((r, i) => {
        let text = r.label + '(' + r.width + 'x' + r.height + ')'
        resolutions.value.push({
          text: text,
          value: r
        })
      })

      resolution.value = resolutions.value[0].text
        stopVideo()
        startVideo()
        // console.log(newCameraId);
        // 释放资源
        // console.log(newCameraId+"54651561");
      }
    }),
    
    onMounted(() => {
     
      // formData.value = CameraApi.getCamera(props.cameraId)
      // console.log(formData.value);
      ZLMRTCClient.GetAllScanResolution().forEach((r, i) => {
        let text = r.label + '(' + r.width + 'x' + r.height + ')'
        resolutions.value.push({
          text: text,
          value: r
        })
      })

      resolution.value = resolutions.value[0].text
      
      stopVideo()
      startVideo()
    })
    
    
    // 卸载事件
    onUnmounted(() => {
      stopVideo()
    })
    // const radioChange = (value) => {
    //   let urlObj = new URL(streamUrl.value)
    //   urlObj.searchParams.set('type', value)
    //   streamUrl.value = urlObj.href
    //   if (value == 'play') {
    //     recvOnly.value = true
    //   } else if (value == 'echo') {
    //     recvOnly.value = false
    //   } else {
    //     recvOnly.value = false
    //   }
    // }

    const changeResolution = (e) => {
      resolution.value = e.target.options[e.target.selectedIndex].text
    }
    const start_play =async () => {
      // const urlIp = ref("")
      const resCamera = await CameraApi.getCamera(props.cameraId)
    const urlIp = resCamera

      console.log(urlIp);
      const streamUrl = ref(
      document.location.protocol +
        '//' +
        urlIp.rtcServer +
        ':'+urlIp.rtcServerPort+'/index/api/webrtc?app=live&stream=camera' +
        props.cameraId +
        '&type=play'
    )
      console.log(streamUrl.value);
      let res = resolution.value.match(/\d+/g)
      let h = parseInt(res.pop())
      let w = parseInt(res.pop())

      player.value = new ZLMRTCClient.Endpoint({
        element: video.value, // TML视频元素的ID或引用，用于显示接收到的远程媒体流。通常是一个<video>元素
        debug: false, // 指定是否启用调试模式。如果启用，则会输出调试日志，有助于问题的排查和调试。
        zlmsdpUrl: streamUrl.value, //这是一个URL，指向用于SDP（会话描述协议）消息交换的服务器。在WebRTC通信中，SDP消息用于协商媒体流的参数，如编解码器、IP地址和端口等。
        simulecast: false, //指定是否启用多路复用（Simulcast）。多路复用允许同时发送多个分辨率和比特率的视频流，以便客户端可以根据其网络条件和能力选择合适的流。
        useCamera: false, //指定是否使用摄像头作为视频源。如果为false，可能需要使用屏幕共享或其他视频源。
        audioEnable: false, //指定是否启用音频流。
        videoEnable: true, //指定是否启用视频流。
        recvOnly: true, //指定是否仅接收媒体流（即作为接收端）。如果为true，则不会发送本地媒体流到远端。
        usedatachannel: false, //指定是否使用数据通道（DataChannel）。数据通道允许在WebRTC连接上直接发送和接收任意数据。

        resolution: {
          w: '100px',
          h: '100px'
        },
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, function (e) {
        // console.log('ICE 协商出错')
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS, function (e) {
        // console.log('播放成功', e.streams)
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, function (e) {
        // console.log('offer anwser 交换失败', e)
        stopVideo()
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM, function (s) {
        selfVideo.value.srcObject = s
        selfVideo.value.muted = true
      })

      player.value.on(ZLMRTCClient.Events.CAPTURE_STREAM_FAILED, function (s) {
        // console.log('获取本地流失败')
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE, function (state) {
        // console.log('当前状态==>', state)
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_OPEN, function (event) {
        // // console.log('rtc datachannel 打开 :', event)
      })

      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_MSG, function (event) {
        // console.log('rtc datachannel 消息 :', event.data)
        msgrecv.value.value = event.data
      })
      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_ERR, function (event) {
        // console.log('rtc datachannel 错误 :', event)
      })
      player.value.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_CLOSE, function (event) {
        // console.log('rtc datachannel 关闭 :', event)
      })
    }

    const startVideo = () => {
      // console.log('开始')
      stopVideo()
      let res = resolution.value.match(/\d+/g)
      let h = '50%'
      let w = '50%'
      // console.log(h, w)
      // console.log(video.value)
      start_play()
    }

    const stopVideo = () => {
      // console.log('停止')
      if (player.value) {
        player.value.close()
        player.value = null
        
      }
    }

    const send = () => {
      if (player.value) {
        player.value.sendMsg(msgsend.value.value)
      }
    }

    const close = () => {
      if (player.value) {
        player.value.closeDataChannel()
      }
    }
    return {
      //测试相关
      video,
      selfVideo,
      url,
      simulcast,
      useCamera,
      audioEnable,
      videoEnable,
      datachannel,
      msgsend,
      msgrecv,
      // streamUrl,
      player,
      recvOnly,
      resolutions,
      resolution,
      // radioChange,
      changeResolution,
      startVideo,
      stopVideo,
      send,
      close
    }
  }
}
</script>

<style>
.parent {
  position: relative;  /* 父元素设置为相对定位 */
}


.operation-item img {
  width: 24px;
  height: 24px;
  margin: 0 5px;
}

.direction-list {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000; /* 确保浮在最上层 */
  background-color: rgba(255, 255, 255, 0.8); /* 半透明背景 */
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.direction-item {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.direction-item img {
  width: 24px;
  height: 24px;
  margin: 0 5px;
}
</style>
