<template>
  <view>
    <iot-p2p-player-with-mjpg
      id="playerRef"
      :deviceInfo="deviceInfo"
      :xp2pInfo="xp2pInfo"
      :rotate="90"
      :fill="true"
      orientation="horizontal"
    >
    </iot-p2p-player-with-mjpg>
    <iot-p2p-voice
      :deviceInfo="deviceInfo"
      :xp2pInfo="xp2pInfo"
      class="w-5 h-5"
      voiceType="Pusher"
      id="voiceComponent"
      :showLog="true"
      @voicestatechange="handleVoiceStateChange"
      @voiceerror="handleVoiceError"
    >
    </iot-p2p-voice>

    <view class="fixed bottom-20">
      <button v-if="!isVoice" @click="startVoice">开始语音</button>
      <button v-else @click="stopVoice">停止语音</button>
    </view>
  </view>
</template>

<script setup>
  import { getXp2pManager } from './xp2pManager'
  import { onMounted, ref } from 'vue'

  let xp2pManager = null

  const deviceInfo = ref({
    deviceId: 'NIHQMTTLM4/1000000000',
    productId: 'NIHQMTTLM4',
    deviceName: '1000000000'
  })
  const xp2pInfo = ref('XP2Pd2ZVIS4Um5pNW1Wydny5ow==%2.4.49')

  const isVoice = ref(false)

  onMounted(async () => {
    if (!xp2pManager) {
      xp2pManager = getXp2pManager()
    }

    const servicePromise = await xp2pManager.startP2PService({
      deviceInfo: deviceInfo.value,
      xp2pInfo: xp2pInfo.value,
      caller: 1
    })
  })

  const handleVoiceStateChange = state => {
    console.log(111111, state)
  }

  const handleVoiceError = error => {
    console.log(1111113, error)
  }

  const startVoice = () => {
    const page = getCurrentPages().pop()
    const playerRef = page.selectComponent('#playerRef')
    console.log(1111113, playerRef)
    playerRef.requestFullScreen()
    // const voiceNode = res[0].node
    // if (voiceNode) {
    //   voiceNode.startVoice({
    //     needRecord: false,
    //     customPusher: {}
    //   })
    // }
  }

  const stopVoice = () => {
    isVoice.value = false
    const query = uni.createSelectorQuery()
    query
      .select('#voiceComponent')
      .node()
      .exec(res => {
        const voiceNode = res[0].node
        if (voiceNode) {
          voiceNode.stopVoice()
        }
      })
  }
</script>
