<template>
  <el-card>
    <template #header>{{title + '(' + memo + ')'}} 
      <el-button type="primary" @click="play('res')" size="small" title="原画面"><Icon icon="fa-solid:video" /></el-button>
      <el-button type="success" @click="play('ai')" size="small" title="AI画面"><Icon icon="ep:aim" /></el-button>
    </template>
    <video
      ref="videoPlayer"
      controls="true" autoplay="true"
    ></video>
  </el-card>
</template>
<script setup lang="ts">
import { getWebrtcUrl, getWebrtcAiUrl } from '@/utils/srsUrl'
import { onUnmounted,defineProps,onMounted } from 'vue'

defineOptions({ name: 'Player' })
const props = defineProps({
  ip: String,
  domain: String,
  code: String,
  name: String,
});
const videoPlayer = ref(null)
let sdk = null
let title = ref('')
let memo = ref('')
let playUrl = ref('')
let webrtcUrl = ref('')
let webrtcAiUrl = ref('')

/** 打开组件 */
const open = async (ip: String, domain: String,code: String,name: String) => {
    try {
      webrtcUrl.value = getWebrtcUrl(ip,domain,code)
      webrtcAiUrl.value = getWebrtcAiUrl(ip,domain,code)
      title.value = name
      play('res')
    } finally {
    }
}

const play = async (type: String) => {
  try {
    if(type === 'res'){
      playUrl.value = webrtcUrl.value
      memo.value = '原画面'
    }else if(type === 'ai'){
      playUrl.value = webrtcAiUrl.value
      memo.value = 'AI画面'
    }
    console.log('播放地址:' + playUrl.value)
    if (playUrl.value) {
      if (sdk) {
        sdk.close()
        sdk = null
      }
      sdk = new SrsRtcWhipWhepAsync()
      sdk.play(playUrl.value)
        .then(function (session) {
          videoPlayer.value.srcObject = sdk.stream
        })
        .catch(function (reason) {
          console.error(reason)
        })
    } else {
      ElMessage.error(
        playUrl.value + '视频源无法播放'
      )
    }
  } catch (error) {
    console.log(error)
  }
}

const close = async () => {
  if (sdk) {
    sdk.close()
  }
  sdk = null
  playUrl = ref('')
  memo = ref('')
  title = ref('')
}
onMounted(() => {
  console.log('Player props:', props.ip, props.domain, props.code, props.name);
  try {
      webrtcUrl.value = getWebrtcUrl(props.ip,props.domain,props.code)
      webrtcAiUrl.value = getWebrtcAiUrl(props.ip,props.domain,props.code)
      title.value = props.name
      play('res')
    } finally {
    }
});

onUnmounted(() => {
  close
})


</script>

<style scoped>
video {
  width: 100%;
  height: auto;
}
</style>