<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { propTypes } from '@/utils/propTypes'

const props = defineProps({
  src: propTypes.string.def(''),
  height: {
    type: [String, Number],
  },
})

const loading = ref(true)
const height = ref<string | number>('')
const frameRef = ref<null | HTMLIFrameElement>(null)
function init() {
  if (!props.height)
    height.value = `${document.documentElement.clientHeight - 94.5}px`
  else
    height.value = props.height

  loading.value = false
}
onMounted(() => {
  setTimeout(() => {
    init()
  }, 300)
})

function sendMessageToIframe(message: any) {
  console.log('proxy func exec, sendMessageToIframe')
  if (frameRef.value && frameRef.value.contentWindow) {
    console.log(`proxy func exec, message send  ${JSON.stringify(message)}`)
    frameRef.value.contentWindow.postMessage(message, '*')
  }
}

defineExpose({
  frameRef,
  sendMessageToIframe,
})

// onMounted(() => {
//   // 监听响应
//   window.addEventListener('message', (event) => {
//     // 处理响应
//     if (event.data)
//       console.warn(event.data)
//   })
// })
</script>

<template>
  <div v-loading="loading" :style="`height:${height}`">
    <iframe ref="frameRef" :src="props.src" style="width: 100%; height: 100%" frameborder="no" scrolling="auto" />
  </div>
</template>
