<template>
  <div class="room">
    <topBar class="room-bar">
      <template
        v-for="(item, index) in menuList"
        :key="index"
      >
        <component
          :is="item.component"
          :value="item.value"
          @callBack="item.callBack"
        />
      </template>
    </topBar>
    <video
      ref="remoteVideo"
      autoplay
      playsinline
    />
    <div class="room-gauge">
      <Gauge
        :value="gauge.speed"
        :gears="gauge.num % 2 ? '倒档' : '前进'"
      />
    </div>
  </div>
</template>

<script setup lang='ts'>
import {
  ref, onMounted, inject, watch,
  onUnmounted,
  shallowRef,
  defineAsyncComponent
} from 'vue'
import topBar from '@/components/topBar.vue'
import Gauge from '@/components/gauge.vue'
import WebRtcService from '@/services/webrtc.service'
import useStore from '@/store/index'

const remoteVideo = ref(null as unknown as HTMLVideoElement)
const RTC = new WebRtcService()
const store = useStore()
const mqtt = inject('MQTT') as Any
const menuList = shallowRef([ { name: '信号', value: 0, component: defineAsyncComponent(() => import('@/components/signal.vue')) },
  { name: '电量', value: 0, component: defineAsyncComponent(() => import('@/components/battery.vue')) },
  {
    name: '录音',
    value: 0,
    callBack: (blob: Blob) => {
      console.log('send audio', blob)
    },
    component: defineAsyncComponent(() => import('@/components/mic.vue'))
  },
  {
    name: '静音', value: 0, callBack: (mute: boolean) => RTC.muteRemoteAudio(mute), component: defineAsyncComponent(() => import('@/components/audio.vue'))
  } ])
const gauge = ref({ speed: 0, num: 0 })

watch(() => store.mqtt_message, async (value: { type: string, data?: RTCSessionDescriptionInit }) => {
  const { type, data } = value
  console.log('二级监听', value)

  // 接收远程offer
  if (type === 'offer') {
    console.log('offer', data)
    await RTC.Peer?.setRemoteDescription(data!)
    const answerd = await RTC.Peer?.createAnswer()
    await RTC.Peer?.setLocalDescription(answerd)
  }
  // 发送本地answer
  if (type === 'answer') {
    console.log('send answer', data)
    mqtt.send(JSON.stringify(data))
  }
})

onMounted(() => RTC.initRTC(remoteVideo.value))
onUnmounted(() => RTC.distory())
</script>
<style lang="scss" scoped>
.room {
  width: 100%;
  height: 100%;
  position: relative;

  &-bar {
    :deep(.topBar-content) {
      display: flex;
      align-items: flex-end;

      &>* {
        margin: 0 0 0 10px;
      }
    }
  }

  video {
    width: 100%;
    height: 100%;
    background: black;
    object-fit: fill;
    font-size: 0;
    z-index: 1;
  }

  &-gauge {
    width: 30vw;
    height: 15vw;
    max-width: 460px;
    max-height: 230px;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2;
  }
}
</style>
