<template>
  <!-- 根据实际部署环境修改 editor.html 的路径 -->
  <iframe
    src="/his/editor/editor.html"
    width="100%"
    height="800"
    frameborder="0"
    @load="onIframeLoad"
    ref="editorIframe">
  </iframe>
</template>

<script setup>

import { ref, onBeforeUnmount } from 'vue'

const editorIframe = ref(null)
const checkEditorTimer = ref(null)
const checkCount = ref(0)
const editor = ref(null)
const iframeWindow = ref(null)
// 对外暴露的获取editor方法
const getEditor = () => {
  if (editor.value) {
    return editor.value
  }
  if (iframeWindow.value && iframeWindow.value.editor) {
    editor.value = iframeWindow.value.editor
    return editor.value
  }
  if (editorIframe.value && editorIframe.value.contentWindow && editorIframe.value.contentWindow.editor) {
    editor.value = editorIframe.value.contentWindow.editor
    return editor.value
  }
  return null
}
// 创建体温单方法
const createVitalSigns = (data) => {
  const editorObj = getEditor()
  if (!editorObj) {
    throw new Error('editor对象未初始化，无法创建体温单')
  }
  if (typeof editorObj.createVitalSigns === 'function') {
    return editorObj.createVitalSigns(data)
  } else {
    throw new Error('editor对象未包含createVitalSigns方法')
  }
}

// 检查editor对象是否已初始化
const startEditorCheck = (frameWindow, iframe) => {
  if (checkEditorTimer.value) {
    clearInterval(checkEditorTimer.value)
  }
  checkCount.value = 0
  checkEditorTimer.value = setInterval(() => {
    checkCount.value++
    try {
      const editorObj = frameWindow.editor
      if (editorObj && typeof editorObj.createVitalSigns === 'function') {
        clearInterval(checkEditorTimer.value)
        editor.value = editorObj
        // 将editor对象暴露到全局
        window.iframeEditor = editorObj
        window.iframeWindow = frameWindow
        // 触发事件
        emit('editor-ready', editorObj)
        emit('load', { target: iframe, editor: editorObj })
        // 发送消息通知
        window.parent.postMessage({ type: 'editorReady' }, '*')
      }
    } catch (err) {
      console.error('检查editor对象时出错:', err)
    }
    if (checkCount.value >= 20) {
      clearInterval(checkEditorTimer.value)
      console.error('Editor 对象加载失败')
    }
  }, 500)
}
// iframe加载完成的处理
const onIframeLoad = (e) => {
  const iframe = e.target
  const frameWindow = iframe.contentWindow
  iframeWindow.value = frameWindow
  if (!frameWindow) {
    console.error('无法访问 iframe 内容')
    return
  }
  // 关闭文书工具栏
  iframe.contentWindow.editor.option.toolbar = false
  startEditorCheck(frameWindow, iframe)
}
// 组件销毁前清理
onBeforeUnmount(() => {
  if (checkEditorTimer.value) {
    clearInterval(checkEditorTimer.value)
  }
})
// 暴露方法给父组件
defineExpose({ getEditor, createVitalSigns })

// 定义事件
const emit = defineEmits(['editor-ready', 'load'])
</script>

<style scoped>
iframe {
  border: none;
  width: 100%;
  min-height: 800px;
}
</style>
