import { onMounted, onBeforeUnmount } from 'vue'
import { postMessageOk, postMessageFail } from '@/utils/iframePip.js'

// 检查数据字段的有效性
const checkData = (list, propList) => {
  if (!Array.isArray(list)) return false
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    for (let j = 0; j < propList.length; j++) {
      const key = propList[j]
      if (item[key] === undefined) return false
    }
  }
  return true
}

// 监听iframe通讯
const useIframeEvent = (detailInfoRef) => {
  const handleMessage = (e) => {
    if (e.data.source === 'InteractiveVideo') {
      console.log('接收到外部调用者的数据', e)
      // 外部传入流程图数据，此时需要更新流程图数据
      if (e.data.toolType === 'InteractiveVideoUser' && e.data.msgType === 'video_change_data') {
        if (
          !e.data.content ||
          // 检查数据字段是否符合要求
          checkData(e.data.content, ['id', 'image', 'name', 'materialId', 'uri', 'optionsList'])
        ) {
          postMessageFail('video_change_data', '数据格式不正确')
          return
        }
        detailInfoRef.value = e.data.content
        postMessageOk('video_change_data')
      }
    }
  }

  onMounted(() => {
    window.addEventListener('message', handleMessage)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('message', handleMessage)
  })
}

export default useIframeEvent
