<!-- 网页加载 -->
<template>
  <view class="webview_page">
    <web-view :src="url" />
  </view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app';
  import { ref, computed, onUnmounted } from 'vue';
  import taskApi from '@/common/api/member/task'
  import sheep from '@/common'
  const taskFormInfo = computed(() => sheep.$store('task').taskFormInfo)
  const url = ref('');
  const webphone = ref(false)
  onLoad(async (options) => {
    url.value = decodeURIComponent(options.url)
	webphone.value = !!options.webphone
	window.addEventListener('message', messageHandler, false)
  })
  onUnmounted(()=>{
	  uni.hideLoading()
	  window.removeEventListener('message', messageHandler, false)
  })
  function messageHandler(event){
	  console.log('Received message from iframe:', event.data);
	  if(event.data.type==='hangup'){
	  	 uni.redirectTo({
	  	   url: '/pages/task/speechConfirm',
	  	 })
	  }
	  if(event.data.type==='ring'){
	  	uni.hideLoading()
	  }
	  if(event.data.type==='reg'){
	  	initWebphone()
	  }
  }
  async function initWebphone(){
	  if(webphone.value){
		uni.showLoading({
		  title: '呼叫中...',
		  mask: true,
		  fail: () => {
		    uni.hideLoading()
		  }
		})
	  	const { code, data } = await taskApi.addTest({
			typeId:taskFormInfo.value.typeId,
			taskName:taskFormInfo.value.name
		})
	  	if (code === 1) {
			sheep.$store('task').updateTaskFormInfo({
				callUserTestId:data.id
			})
	  		var iframeEl = document.querySelector("iframe")
			if (iframeEl) {
				  iframeEl.allow = 'microphone *;camera *'
			}
	  	}else{
			sheep.$router.back()
		}
	  }
  }
</script>

<style lang="scss" scoped>
	:deep() {
		uni-page-body{
			background-color: #222222 !important;
		}
	}
</style>
