<template>
  <el-row :gutter="15">
    <!--安防摄像头接入-->
    <el-col :span="20" :xs="15">
      <ContentWrap>
        <el-input v-model="url" class="!w-450px" placeholder="请输入视频流ID" />
        <el-button @click="startPlay">接入</el-button>
      </ContentWrap>
      <ContentWrap>
        <video
          ref="videoPlayer"
          controls="true" autoplay="true"
          width="500"
          height="400"
        ></video>
      </ContentWrap>
      <ContentWrap>
        <video
          ref="videoPlayer2"
          controls="true" autoplay="true"
          width="500"
          height="400"
        ></video>
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'
let sdk = null
let sdk2 = null
const videoPlayer = ref(null)
const videoPlayer2 = ref(null)
const baseUrl = 'http://123.60.223.250:1985/rtc/v1/whep/?app=live&stream='
let url = `caoyang001`
let url2 = url+`-ai`

onMounted(() => {
  startPlay()
  startPlay2()
})

onUnmounted(() => {
  if (sdk) {
    sdk.close()
  }
  if (sdk2) {
    sdk2.close()
  }
  sdk = null
  sdk2 = null
})

const startPlay = async () => {
  try {
    console.log(url)
    if (url) {
      if (sdk) {
        sdk.close()
        sdk = null
      }
      sdk = new SrsRtcWhipWhepAsync()
      sdk.play(baseUrl+url)
        .then(function (session) {
          videoPlayer.value.srcObject = sdk.stream
        })
        .catch(function (reason) {
          console.error(reason)
        })
    } else {
      ElMessage.error(
        '请填写正确地址，地址格式为：http://123.60.223.250:1985/rtc/v1/whep/?app=live&stream=ID'
      )
    }
  } catch (error) {
    console.log(error)
  }
}

const startPlay2 = async () => {
  try {
    console.log(url)
    if (url) {
      if (sdk2) {
        sdk2.close()
        sdk2 = null
      }
      sdk2 = new SrsRtcWhipWhepAsync()
      sdk2.play(baseUrl+url2)
        .then(function (session) {
          videoPlayer2.value.srcObject = sdk2.stream
        })
        .catch(function (reason) {
          console.error(reason)
        })
    } else {
      ElMessage.error(
        '请填写正确地址，地址格式为：http://123.60.223.250:1985/rtc/v1/whep/?app=live&stream=ID'
      )
    }
  } catch (error) {
    console.log(error)
  }
}
</script>

<style scoped></style>
