<template>
  <!--    <Source src="/code/VitalSigns.vue"></Source>-->
  <div>
    <a-row class="box">
      <!-- 病历号输入框已隐藏，通过setMedicalRecordId方法设置vitalSignsId -->
      <!-- 病历号&nbsp;&nbsp;<a-input v-model="vitalSignsId" style="width: 160px"></a-input> -->
      <a-button-group style="margin-left: 20px;">
        <a-button
          v-if="showCreateButton"
          plain
          type="primary"
          @click="showVitalSignsModal('create')"
          :loading="loading"
          :disabled="!editorReady">创建体温单</a-button>
        <a-button
          v-if="showUpdateButton"
          plain
          type="primary"
          @click="showVitalSignsModal('update')"
          :loading="loading"
          :disabled="!editorReady">更新体温单</a-button>
      </a-button-group>
      <a-button-group v-if="showClearButton" style="margin: 0 20px;">
        <a-button plain type="primary" @click="execCommand('print')" :loading="loading" :disabled="!editorReady">打印</a-button>
      </a-button-group>
      <!-- 修改清空体温单按钮样式，使其更加醒目 -->
      <a-button
        type="primary"
        danger
        v-if="showClearButton"
        @click="clearVitalSigns"
        :loading="loading"
        :disabled="!editorReady"
        style="margin-left: 10px;">
        <a-icon type="delete" /> 清空体温单
      </a-button>
    </a-row>
    <div v-if="!editorReady" style="margin: 10px 0; padding: 10px; background-color: #fffbe6; border: 1px solid #ffe58f;">
      <a-icon type="loading" /> 体温单编辑器加载中...
    </div>

    <!-- 添加体温单生成加载遮罩 -->
    <div v-if="generating" class="generating-mask">
      <div class="generating-content">
        <a-spin size="large" />
        <div class="generating-text">体温单生成中，请稍候...</div>
      </div>
    </div>

    <Editor @editor-ready="onEditorReady" style="margin: 10px 0;" ref="editorComponent"></Editor>

    <!-- 使用TextBox组件替代原有弹窗 -->
    <TextBox
      :visible="modalVisible"
      :modalType="modalType"
      :editorReady="editorReady"
      :id="Number(vitalSignsId) || 180"
      @submit="handleSubmit"
      @cancel="closeModal"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Editor from './editor.vue'
import TextBox from './textBox.vue'
import { message } from 'ant-design-vue'

// 响应式状态
const vitalSignsId = ref(null)
const loading = ref(false)
const editorReady = ref(false)
const editorComponent = ref(null)
const modalVisible = ref(false)
const modalType = ref('create')
const generating = ref(false) // 添加体温单生成中状态
let editor = null
// 定义组件事件
const emit = defineEmits(['submit'])
// 常量
const modalTitles = {
  create: '创建体温单',
  update: '更新体温单'
}

// 接受父组件传递的属性
defineProps({
  showCreateButton: {
    type: Boolean,
    default: false
  },
  showUpdateButton: {
    type: Boolean,
    default: false
  },
  // 添加打印按钮是否显示属性
  showPrintButton: {
    type: Boolean,
    default: false
  },
  showClearButton: {
    type: Boolean,
    default: false
  },
  // 时间模式 -2 ~ 2
  adjustHour: {
    type: Number,
    default: 0
  }
})

// 显示弹窗
function showVitalSignsModal (type) {
  modalType.value = type
  modalVisible.value = true
}

// 关闭弹窗
function closeModal () {
  modalVisible.value = false
}

// 编辑器初始化
function onEditorReady (editorObj) {
  try {
    if (!editorObj) {
      throw new Error('传入的editor对象为null或undefined')
    }

    // 尝试获取编辑器对象
    if (typeof editorObj.createVitalSigns === 'function') {
      editor = editorObj
    } else if (editorObj.getEditor && typeof editorObj.getEditor === 'function') {
      const editorFromComponent = editorObj.getEditor()
      editor = editorFromComponent && typeof editorFromComponent.createVitalSigns === 'function'
        ? editorFromComponent
        : (typeof editorObj.createVitalSigns === 'function' ? editorObj : null)
    }
    if (!editor) {
      throw new Error('无法获取有效的editor对象')
    }
    editorReady.value = true
  } catch (err) {
    console.error('设置editor对象失败:', err)
    message.error('体温单编辑器初始化失败，请刷新页面重试')
  }
}

// 执行命令
function execCommand (cmd) {
  if (!editorReady.value || !editor) return
  loading.value = true
  try {
    editor.execCommand(cmd)
  } catch (err) {
    console.error('执行命令出错:', err)
    message.error(`执行${cmd}命令失败`)
  } finally {
    loading.value = false
  }
}

// 清空体温单
async function clearVitalSigns () {
  if (!editorReady.value || !editor) {
    message.error('体温单编辑器未加载完成，请等待或刷新页面重试')
    return
  }
  loading.value = true
  generating.value = true
  try {
    // 重新加载editor.html页面来完全重置编辑器
    try {
      const iframe = editorComponent.value.$refs.editorIframe
      if (iframe) {
        // 保存当前src
        const currentSrc = iframe.src
        // 确认提示
        message.loading('正在清空体温单...', 1)
        // 重新加载iframe
        iframe.onload = async () => {
          try {
            // 等待iframe重新加载完成
            await new Promise(resolve => setTimeout(resolve, 500))
            // 获取新的editor对象
            const newEditorObj = iframe.contentWindow.editor
            if (newEditorObj) {
              // 等待editor初始化
              if (typeof newEditorObj.init === 'function') {
                await new Promise((resolve) => {
                  const checkInterval = setInterval(() => {
                    if (newEditorObj.isReady) {
                      clearInterval(checkInterval)
                      resolve()
                    }
                  }, 100)
                  // 最多等待5秒
                  setTimeout(() => {
                    clearInterval(checkInterval)
                    resolve()
                  }, 5000)
                })
              }
              // 更新全局editor引用
              editor = newEditorObj
              window.iframeEditor = newEditorObj
            } else {
              throw new Error('重新加载后无法获取editor对象')
            }
          } catch (err) {
            console.error('重新加载iframe后清空体温单出错:', err)
            message.error(`清空体温单失败: ${err.message || '未知错误'}`)
          } finally {
            loading.value = false
            generating.value = false
            // 移除临时onload处理器
            iframe.onload = null
          }
        }
        // 重新加载iframe
        iframe.src = currentSrc + '?t=' + new Date().getTime()
        return
      }
    } catch (reloadErr) {
      console.warn('重新加载iframe失败，将尝试其他方法清空体温单:', reloadErr)
    }
    // 备用清空方法
    try {
      const iframe = editorComponent.value.$refs.editorIframe
      if (iframe?.contentWindow) {
        iframe.contentWindow.eval(`
          try {
            // 尝试使用编辑器提供的各种可能的清空方法
            if (editor) {
              if (typeof editor.loadUrl === 'function') {
                editor.loadUrl('');
              } else if (typeof editor.resetDocument === 'function') {
                editor.resetDocument();
              } else if (typeof editor.clearContent === 'function') {
                editor.clearContent();
              } else if (typeof editor.clear === 'function') {
                editor.clear();
              } else if (typeof editor.setEditorContent === 'function') {
                editor.setEditorContent('');
              } else if (editor.document) {
                try {
                  editor.document.body.innerHTML = '';
                } catch(clearErr) {
                  console.warn('清空编辑器内容失败');
                }
              }
            }
          } catch(e) {
            console.error('清空体温单失败:', e);
          }
        `)
      } else if (window.iframeEditor) {
        const editorObj = window.iframeEditor
        if (typeof editorObj.loadUrl === 'function') {
          editorObj.loadUrl('')
        } else if (typeof editorObj.resetDocument === 'function') {
          editorObj.resetDocument()
        } else if (typeof editorObj.clearContent === 'function') {
          editorObj.clearContent()
        } else if (typeof editorObj.clear === 'function') {
          editorObj.clear()
        } else if (typeof editorObj.setEditorContent === 'function') {
          editorObj.setEditorContent('')
        }
      } else if (editor) {
        if (typeof editor.loadUrl === 'function') {
          editor.loadUrl('')
        } else if (typeof editor.resetDocument === 'function') {
          editor.resetDocument()
        } else if (typeof editor.clearContent === 'function') {
          editor.clearContent()
        } else if (typeof editor.clear === 'function') {
          editor.clear()
        } else if (typeof editor.setEditorContent === 'function') {
          editor.setEditorContent('')
        }
      } else {
        throw new Error('无法获取编辑器对象')
      }
    } catch (err) {
      console.error('清空体温单出错:', err)
      message.error(`清空体温单失败: ${err.message || '未知错误'}`)
    }
  } finally {
    loading.value = false
    generating.value = false
  }
}

// 处理表单提交
async function handleSubmit (formData) {
  console.log('表单数据:', formData)
  if (!editorReady.value || !editor) {
    message.error('体温单编辑器未加载完成，请等待或刷新页面重试')
    return
  }
  loading.value = true
  generating.value = true // 开始生成，显示加载遮罩
  try {
    let result
    try {
      const iframe = editorComponent.value.$refs.editorIframe
      if (iframe?.contentWindow) {
        // 直接传递数据对象，避免使用eval
        if (iframe.contentWindow.editor && typeof iframe.contentWindow.editor.createVitalSigns === 'function') {
          result = iframe.contentWindow.editor.createVitalSigns(formData)
        } else {
          throw new Error('编辑器对象无效')
        }
      } else if (window.iframeEditor) {
        result = window.iframeEditor.createVitalSigns(formData)
      } else {
        throw new Error('无法访问iframe')
      }
    } catch (err) {
      // 备用方案
      if (editor && typeof editor.createVitalSigns === 'function') {
        editor.createVitalSigns(formData)
      } else {
        throw new Error('无法调用createVitalSigns方法')
      }
    }

    vitalSignsId.value = result || formData.id
    modalVisible.value = false
    message.success(`${modalTitles[modalType.value]}成功`)
    emit('submit', formData)
  } catch (err) {
    console.error('创建体温单出错:', err)
    message.error(`创建体温单失败: ${err.message || '未知错误'}`)
  } finally {
    loading.value = false
    generating.value = false // 无论成功失败，都结束加载遮罩
  }
}

// 处理表单数据
function mergeAndTransformData (records, patientInfo, id, date, operateDate) {
  // 提取records中的数据
  const temperatureList = records.map(record => record.temperature).join(',')
  const sphygmusList = records.map(record => record.sphygmus).join(',')
  const breathList = records.map(record => record.breath).join(',')
  const heartList = records.map(record => record.heart).join(',')
  const notesList = records.map(record => record.notes).join(',')
  const painList = records.map(record => record.pain).join(',')
  const data1List = records.map(record => {
    const [systolic, diastolic] = record.data1.split('|')
    return `${systolic}/${diastolic}`
  }).join(',')
  const data2List = records.map(record => record.data2).join(',')
  const data3List = records.map(record => record.data3).join(',')
  const data4List = records.map(record => record.data4).join(',')
  const data5List = records.map(record => record.data5).join(',')
  const data6List = records.map(record => record.data6).join(',')
  const data7List = records.map(record => record.data7).join(',')
  const tempTypeList = records.map(record => record.temptype).join(',')

  // 提取patientInfo中的数据
  const name = patientInfo.name || ''
  const dept = patientInfo.dept || ''
  const bed = patientInfo.bed || ''
  const inDate = patientInfo.indate || ''
  const diag = patientInfo.diag || ''

  // 生成合并后的对象
  const mergedData = {
    bed: bed.toString(),
    sphygmus: sphygmusList,
    notes: notesList,
    medicalNo: id, // 示例中的固定值
    diag: diag,
    type: 'normal', // 示例中的固定值
    breath: breathList,
    temperature: temperatureList,
    id: id, // 示例中的固定值
    tempType: tempTypeList,
    data7: data7List,
    pain: painList,
    data6: data6List,
    data5: data5List,
    data4: data4List,
    data3: data3List,
    data2: data2List,
    inDate: inDate.split(' ')[0], // 只取日期部分
    data1: data1List,
    dept: dept,
    heart: heartList,
    labels: '血压(mmHg)|入水量(ml)|出水量(ml)|大便(次)|小便(次)|身高(cm)|体重(kg)', // 示例中的固定值
    name: name,
    begin: date, // 只取日期部分
    operateDate: operateDate // 只取日期部分
  }
  return mergedData
}
// 设置病历号的方法
function setMedicalRecordId (id) {
  vitalSignsId.value = id
  // console.log('病历号已设置为:', vitalSignsId.value)
}
// 生命周期钩子
onMounted(() => {
  window.addEventListener('message', (event) => {
    if (event.data?.type === 'editorReady' && !editorReady.value && editorComponent.value?.getEditor) {
      try {
        const editorFromComponent = editorComponent.value.getEditor()
        if (editorFromComponent && typeof editorFromComponent.createVitalSigns === 'function') {
          editor = editorFromComponent
          editorReady.value = true
        }
      } catch (err) {
        console.error('从组件获取editor对象错误:', err)
      }
    }
  })
})

// 暴露方法和属性给父组件，使父组件可以通过ref访问
defineExpose({
  // 属性
  vitalSignsId,
  // 清空体温单方法
  clearVitalSigns,
  // 展示更新和创建弹框 创建参数：(String) create, 更新参数：(String) update
  showVitalSignsModal,
  // 触发打印函数 参数：(String) print
  execCommand,
  // 获取当前体温单ID的方法
  getVitalSignsId: () => vitalSignsId.value,
  // 设置体温单ID的方法
  setVitalSignsId: (id) => {
    vitalSignsId.value = id
  },
  // 创建体温单 参数：(Object) data
  handleSubmit,
  // 设置病历号
  setMedicalRecordId,
  // 获取表单数据
  mergeAndTransformData
})
</script>

<style scoped>
.box {
  display: flex;
  align-items: center;
  padding: 1%;
}

/* 体温单生成加载遮罩样式 */
.generating-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.generating-content {
  background-color: white;
  padding: 20px 40px;
  border-radius: 4px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.generating-text {
  margin-top: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
}
</style>
