<template>
  <web-view v-if="webviewUrl" @message="handleMessage" :src="webviewUrl" ></web-view>
</template>

<script setup lang="ts">
import {useUserStore} from "@/store/userStore";
import {ref, watch} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import type User from "@/mode/User";
import {useWsStore} from "@/store/WsStore";
import SendVideoCode from "@/plugins/video/SendVideoCode";
import {storeToRefs} from "pinia";
import {usePeerStore} from "@/store/peerStore";

interface IProps{
  friend:User,
  showVideo:boolean
  peerId:string|undefined
}
const props = defineProps<IProps>();
const wsStore = useWsStore()
const webviewUrl = ref()
const {isClose} = storeToRefs(usePeerStore())

onLoad(() => {
  const user = useUserStore().getUser()
  if(user){
    const url = `/hybrid/html/${props.peerId?'answer':'calling'}.html?id=${user.id}&name=${user.name}&friendId=${props.friend.id}&friendName=${props.friend.name}&friendAvatar=${props.friend.avatar}&showVideo=${props.showVideo}&peerId=${props.peerId}`
    webviewUrl.value = encodeURI(url)
  }
})
watch(isClose, (newVal) => {
  if (newVal) {
    uni.navigateBack()
  }
})

const sendCloseMsg = () => {
  const data = {
    chatId: props.friend.id,
    fromId: useUserStore().getUser()?.id,
    timestamp: new Date().getTime(),
  }
  const sendInfo = {
    code: SendVideoCode.CLOSE,
    message: data
  }
  wsStore.send(JSON.stringify(sendInfo))
}
/**
 * 处理消息 接受来自webview的消息
 * @param data
 */
const handleMessage = (data:any) => {
  const message = data.detail.data[0]
  console.log('message',message)
  switch (message.type)
  {
    case 'ws'://ws消息
      useWsStore().send(JSON.stringify(message.data))
      break;
    case 'close'://关闭
      sendCloseMsg()
      uni.navigateBack()
      break;
  }
}

</script>

<style>
</style>