<template>
  <el-container>
    <el-header>
      <el-button-group>
        <el-button :disabled="!emrConfig.editor"
                   type="success"
                   icon="CircleCheck"
                   @click="clickSaveData">
          保存
        </el-button>
        <el-button
            type="primary"
            @click="clickToSubmitTheMedicalRecord"
            :disabled="!documentId || !emrConfig.editor">
          提交病历
        </el-button>
        <el-button :disabled="!emrConfig.editor"
                   icon="Delete" type="danger"
                   @click="clickDelete">
          删除
        </el-button>
        <el-button @click="recoveryDialog = true">
          恢复
        </el-button>
      </el-button-group>
      <el-divider direction="vertical"/>
      <emr-auxiliary-tools :pat-info="props.huanZheXinXi"/>
      <!--   恢复到上一次保存的状态   -->
      <historical-emr v-if="recoveryDialog"
                      @closed="recoveryDialog = false"
                      :docunent-id="documentId"
                      @restore-data="restoreData"/>
      <el-divider direction="vertical"/>
      <el-button-group>
        <!--        页面打印支持病历续打，但是可能会出现打印错误，<br/>如果页面打印无法使用请用服务打印，服务打印也不行请换win10电脑打印。-->
        <el-button type="primary" icon="Printer" @click="frontEndPrinting"
                   title="页面打印支持病历续打，但是可能会出现打印错误，<br/>如果页面打印无法使用请用服务打印，服务打印也不行请换win10电脑打印。">
          页面
        </el-button>
        <el-button type="primary" icon="Printer" @click="servicePrint"
                   title="服务打印慢，但是不会出现页面打印错误，不支持病历续打。">
          服务
        </el-button>
      </el-button-group>
      <el-divider direction="vertical"/>
      <el-button-group>
        <el-button type="primary" icon="ZoomIn" @click="zoomFunc(0.1)"
                   title="放大病历">
          放大
        </el-button>
        <el-button type="primary" icon="ZoomOut" @click="zoomFunc(-0.1)"
                   title="缩小病历">
          缩小
        </el-button>
      </el-button-group>
      <el-divider direction="vertical"/>
      <el-button-group>
        <el-button
            type="primary"
            @click="openAssistant.dialog = true"
            title="电子病历助手，目前只能填充手术病历">
          助手
        </el-button>
        <el-button @click="drgIntelligentGrouping"
                   type="primary"
                   title="drg的预分组">
          DRG分组
        </el-button>
      </el-button-group>
      <!--   手术数据填充   -->
      <emr-assistant :data="openAssistant" :to-fill-in-data="clickToFillInData"/>
      <el-divider direction="vertical"/>
      <el-select v-model="reviewMode"
                 style="width: 60px; "
                 @change="isRevisionMode"
                 title="审阅模式">
        <el-option :value="0" label="关闭"
                   title="页面上不显示修改记录"/>
        <el-option :value="1" label="开启"
                   title="病历右侧会以列表的形式显示 添加，删除，更新的记录"/>
        <el-option :value="2" label="嵌入"
                   title="嵌入病历显示修改记录，新增的记录会用背景颜色标记，删除的记录 通过画删除线标记"/>
      </el-select>
      <el-button-group>
        <el-button icon="RefreshLeft"
                   @click="clickUndo('undo')"
                   title="撤销"/>
        <el-button icon="RefreshRight"
                   @click="clickUndo('redo')"
                   title="重做"/>
      </el-button-group>
      <el-button-group>
        <el-button title="仅在病程记录中生效，根据病程记录的时间来进行排序，从小到大。"
                   icon="SortDown"
                   @click="diseaseCourseSequencing"/>
        <el-button title="为页面添加分页标识符,分页符后强制为新页面。" @click="paginationSymbol">
          <i class="iconfont icon-chaifenyemian"></i>
        </el-button>
      </el-button-group>
      <el-divider direction="vertical"/>
      <el-button-group>
        <el-button title="收起左边模板"
                   @click="foldBothSides.isLeft= !foldBothSides.isLeft">
          <el-icon>
            <Fold/>
          </el-icon>
        </el-button>
        <el-button title="收起右边片段"
                   @click="foldBothSides.isRight= !foldBothSides.isRight">
          <el-icon>
            <Expand/>
          </el-icon>
        </el-button>
      </el-button-group>
    </el-header>
    <el-container>
      <div :class="foldBothSides.isLeft ? 'emr-template-open' : 'emr-template-put-away' ">
        <emr-sidebar @nodeClick="nodeClick"
                     @patient-medical-record="foldBothSides.isLeft = true"
                     v-show="foldBothSides.isLeft"
                     ref="emrSidebarRef"
                     :max-height="maxHeight"
                     :huan-zhe-xin-xi="props.huanZheXinXi"/>
      </div>
      <div class="emr-editor">
        <div style="height: 30px" @mousewheel="mousewheel($event)">
          <el-scrollbar ref="tootScrollRef" @scroll="scroll">
            <div class="tool_emr">
              <el-select style="width: 150px;"
                         @change="textStyleFunc.fontFamily()"
                         v-model="emrStyle.fontFamily">
                <el-option v-for="item in availableFonts"
                           :value="item.font"
                           :label="item.text">
                  <span :style="{'fontFamily':item.font }">
                    {{ item.text }}
                  </span>
                </el-option>
              </el-select>
              <el-select style="width: 70px;"
                         @change="textStyleFunc.fontSize()"
                         v-model="emrStyle.fontSize">
                <el-option v-for="item in fontSizes"
                           :value="item.code"
                           :label="item.name"/>
              </el-select>
              <el-divider direction="vertical"/>
              <el-button-group>
                <el-button @click="textStyleFunc.fontSizeAdjust('increase')"
                           title="放大字体">
                  +
                </el-button>
                <el-button @click="textStyleFunc.fontSizeAdjust('decrease') "
                           title="缩小字体">
                  -
                </el-button>
              </el-button-group>
              <el-divider direction="vertical"/>
              <el-button-group>
                <el-button
                    title="字体加粗"
                    :class="buttonClass('fontWeight','bold')"
                    @click="textStyleFunc.fontWeight()">
                  <i class="iconfont icon-jiacu"></i>
                </el-button>
                <el-button
                    title="斜体"
                    :class="buttonClass('fontStyle','oblique')"
                    @click="textStyleFunc.fontStyle()">
                  <i class="iconfont icon-xieti"></i>
                </el-button>
                <el-button
                    title="下划线"
                    :class="buttonClass('underline')"
                    @click="textStyleFunc.underline()">
                  <i class="iconfont icon-xiahuaxian"></i>
                </el-button>
                <el-button
                    title="删除线"
                    :class="buttonClass('lineThrough')"
                    @click="textStyleFunc.lineThrough()">
                  <i class="iconfont icon-shanchuxian"></i>
                </el-button>
                <el-button
                    title="上标"
                    :class="buttonClass('super')"
                    @click="textStyleFunc.super()">
                  <i class="iconfont icon-zitishangbiao"></i>
                </el-button>
                <el-button
                    title="下标"
                    :class="buttonClass('sub')"
                    @click="textStyleFunc.sub()">
                  <i class="iconfont icon-zitixiabiao"></i>
                </el-button>
              </el-button-group>
              <div class="color_picker"
                   title="字体颜色">
                <i class="iconfont icon-zitiyanse"></i>
                <el-color-picker v-model="emrStyle.color"
                                 @change="textStyleFunc.color()"
                                 :predefine="predefineColors"/>
              </div>
              <div class="color_picker"
                   title="背景颜色">
                <i class="iconfont icon-beijingyanse"></i>
                <el-color-picker v-model="emrStyle.backgroundColor"
                                 @change="textStyleFunc.backgroundColor()"
                                 :predefine="predefineColors"/>
              </div>
              <el-divider direction="vertical"/>
              <el-button-group>
                <el-popover
                    :width="0"
                    trigger="hover">
                  <template #reference>
                    <el-button title="无序列表">
                      <i class="iconfont icon-wuxuliebiao"></i>
                    </el-button>
                  </template>
                  <emr-unordered-list list-type="disorder" @click-list="textStyleFunc.unorderedList"/>
                </el-popover>
                <el-popover
                    :width="0"
                    trigger="hover">
                  <template #reference>
                    <el-button title="有序列表">
                      <i class="iconfont icon-youxuliebiao"></i>
                    </el-button>
                  </template>
                  <emr-unordered-list list-type="orderly" @click-list="textStyleFunc.orderedList"/>
                </el-popover>
              </el-button-group>
              <el-divider direction="vertical"/>
              <el-button-group>
                <el-button title="左对齐"
                           @click="textStyleFunc.alignment('left')">
                  <i class="iconfont icon-zuoduiqi"></i>
                </el-button>
                <el-button title="居中对其"
                           @click="textStyleFunc.alignment('center')">
                  <i class="iconfont icon-juzhongduiqi"></i>
                </el-button>
                <el-button title="右对齐"
                           @click="textStyleFunc.alignment('right')">
                  <i class="iconfont icon-youduiqi"></i>
                </el-button>
                <el-button title="两端对齐"
                           @click="textStyleFunc.alignment('justify')">
                  <i class="iconfont icon-zuoyouduiqi"></i>
                </el-button>
              </el-button-group>
              <el-divider direction="vertical"/>
              <el-button-group>
                <el-button title="增加缩进"
                           @click="textStyleFunc.indent(1)">
                  <i class="iconfont icon-yousuojin"></i>
                </el-button>
                <el-button title="减小缩进"
                           @click="textStyleFunc.indent(-1)">
                  <i class="iconfont icon-zuosuojin"></i>
                </el-button>
              </el-button-group>
            </div>
          </el-scrollbar>
        </div>
        <div class="emr-iframe">
          <emr-popup ref="popupRef"
                     @fill-data="popupFunc.fillData"/>

          <div class="creator_prompt">
            <div>
              创建：{{ createName }}
              <br>
              当前：{{ userData.name }}
            </div>

            <div>
              等级：{{ createLevel }}
              <br>
              等级：{{ doctorLevel }}
            </div>

            <div class="edit_mode">
              模式：{{ editorMode ? '只读' : '编辑' }}
            </div>

          </div>

          <iframe ref="emrRef"
                  :height="maxHeight - 100 + 'px' "
                  :src="caseHistoryUrl"/>
        </div>
      </div>
      <div :class="foldBothSides.isRight ? 'emr-fragment-open' : 'emr-fragment-put-away' ">
        <emr-snippet
            v-show="foldBothSides.isRight"
            @node-click="clickSnippet"
            ref="emrSnippetRef"
            :max-height="maxHeight"
            :patientData="patientData"/>
      </div>

    </el-container>

    <xc-dialog-v2 v-model="drgData.dialog" title="DRG预分组" :maximize="true">
      <iframe :src="drgData.url" :height="800" v-if="drgData.dialog"/>
    </xc-dialog-v2>


  </el-container>
</template>

<script setup name="emr">
import {getEmrInpatientData} from "@/api/dictionary/emr-data-maintenance-api";
import EmrSidebar from "@/components/zhu-yuan-yi-sheng/emr/EmrSidebar.vue";
import {
  EMRInteractive,
  emrConfig,
  fontSizes, availableFonts, copyEnum, getEmrCopy, delEmrCopy
} from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init";
import {ElMessage, ElMessageBox} from "element-plus";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import EmrSnippet from "@/components/zhu-yuan-yi-sheng/emr/EmrSnippet.vue";
import store from "@/store";
import {onBeforeRouteLeave} from "vue-router";
import {getServerDateApi, getUuid} from "@/api/public-api";
import {
  getDrgIntelligentGrouping,
  getExtractDataElement, hotSearchSorting,
  submitMedicalRecord
} from "@/api/zhu-yuan-yi-sheng/emr-patient";
import {useDocumentVisibility} from "@vueuse/core";
import EmrAssistant from "@/components/zhu-yuan-yi-sheng/emr/EmrAssistant.vue";
import XcDialogV2 from "@/components/xiao-chan/dialog/XcDialogV2.vue";
import {getWardsApi} from "@/api/login";
import {xcMessage} from "@/utils/xiaochan-element-plus";
import EmrUnorderedList from "@/components/zhu-yuan-yi-sheng/emr/EmrUnorderedList.vue";
import HistoricalEmr from "@/components/zhu-yuan-yi-sheng/emr/HistoricalEmr.vue";
import EmrPopup from "@/components/zhu-yuan-yi-sheng/emr/EmrPopup.vue";
import EmrAuxiliaryTools from "@/components/zhu-yuan-yi-sheng/emr/auxiliary-tools/EmrAuxiliaryTools.vue";

const props = defineProps({
  huanZheXinXi: {
    type: Object,
  },
  maxHeight: {
    type: Number
  },
  visitor: {
    type: Boolean
  },
  isDualScreen: {
    type: Boolean
  }
})

const currentEmr = ref(null)
const emrRef = ref(null)

let recoveryDialog = $ref(false)
let categoryCode = $ref('')
// 文档 id 唯一值
let documentId = $ref('')
let patientId = $ref('')
let categoryId = $ref('')
let templateName = $ref('')
let caseHistoryUrl = $ref('/emr/runtime/#/editor')
let openAssistant = $ref({
  data: {},
  dialog: false
})
// 患者数据
let patientData = {}
// 编辑器
let editor = null
// 侧边栏
const emrSidebarRef = ref(null)
// 片段预览
const emrSnippetRef = ref(null)
// 是否加载完成了
let loaded = $ref(false)
// 是否 改变了数据
let isEditorChange = $ref(false)

// 是否开启审阅模式
let reviewMode = $ref(0)
// 跳转定位
let jumpPositioning = {
  value: '',
  // 这里是业务编码
  code: null
}
let wardList = []
// 创建人 id
let createId = null;
// 获取提取到的数据。
let extractData = {}

let foldBothSides = $ref({
  isLeft: true,
  isRight: true,
})

let emrStyle = $ref({
  // 字体样式
  fontFamily: '"Microsoft YaHei"',
  // 字体大小
  fontSize: '10.5pt',
  // 字体加粗
  fontWeight: 'normal',
  // 斜体
  fontStyle: 'normal',
  // 下划线
  underline: false,
  //删除线
  lineThrough: false,
  // 上标
  super: false,
  // 下标
  sub: false,
  // 颜色
  color: '',
  backgroundColor: '',
  paragraphStyle: {}
})

const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577',
])

const emrEvent = {
  'loaded': async (event) => {
    editor = currentEmr.value.getEditor()
    loaded = false
    setEditorModeFun()
    courseSegmentLocking()
    setTheProgressAnchor()
    deleteDataElement()
    reQueryPatientInformation()
    isRevisionMode()
    // 判断是否只读
    readonlyPattern()
  },

  'contentchange': (event) => {
    if (!editorMode) {
      // 如果是空的编辑器就不触发了
      if (!emrRef.value.src.includes('/emr/runtime/#/editor')) {
        // 判断内容是否改变
        isEditorChange = true
        emrSidebarRef.value.changeTemplateType(2)
      }
    }
  },

  'contextUpdate': (evt, contextMap, component, context) => {
    emrStyle.fontSize = context.fontSize
    emrStyle.fontFamily = context.fontFamily
    emrStyle.fontStyle = context.italic ? 'oblique' : 'normal'
    emrStyle.fontWeight = context.bold ? 'bold' : 'normal'
    emrStyle.underline = context.underline
    emrStyle.lineThrough = context.linethrough
    emrStyle.super = context.superScript
    emrStyle.sub = context.subScript
    emrStyle.color = context.color
    emrStyle.backgroundColor = context.backgroundColor
    emrStyle.paragraphStyle = context.paragraphStyle
  },

  'ready': (event) => {
    editor = currentEmr.value.getEditor()
    popupFunc.setShortcutKey()
    rightClickOnRegistration()
  }
}

// 点击保存病历
const clickSaveData = async () => {
  // 只读模式无法保存数据
  if (editorMode) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "当前为只读模式，无法保存病历。");
  }
  waitForLoadingToComplete()
  // 判断是否有必填项目
  let validator = editor.getValidator();
  let valid = validator.valid();
  if (valid) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "有必填项不能为空,请仔细检查,红色输入框.")
  }
  await analysisIframeSrcSearch()
  let data = {
    emrDocumentId: documentId,
    emrCategoryCode: categoryCode,
    patNo: props.huanZheXinXi.inpatientNo,
    times: props.huanZheXinXi.admissTimes,
    emrName: templateName,
    categoryId: categoryId
  }
  objectValuesCannotBeNull(data)
  data.emrDataElement = editor.getDataElements('business')
  ElMessageBox.prompt('请输入保存的名称', '提示', {
    inputErrorMessage: '长度为2 - 20 个,汉字',
    inputPattern: /^\S{2,20}$/,
    inputValue: templateName
  }).then(async ({value}) => {
    data.name = value
    let newDate = await getServerDateApi()
    currentEmr.value.saveDocument(data, newDate).then(res => {
      // 把提取到的数据放到 patientData 中.
      extractData = res
      Object.assign(patientData, res)
      isEditorChange = false
      emrSidebarRef.value.queryData()
      // 如果是第一次创建就需要跳转
      if (createId == null) {
        let temp = {
          documentId: data.emrDocumentId,
          categoryCode: data.emrCategoryCode,
          name: data.name,
          categoryId: data.categoryId
        };
        createId = userData.code
        updateCaseHistoryUrl(temp)
      }
      xcMessage.success('保存成功')
    }).catch(() => {
      xcMessage.error('保存失败请重新保存')
    })

  }).catch(() => {

  })

}

// 添加片段
const clickToFillInData = (value) => {
  if (!editorMode) {
    editor.setValues(value)
  }
}

const waitForLoadingToComplete = () => {
  if (loaded) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请等待加载成功。")
  }
}

const objectValuesCannotBeNull = (object) => {
  if (!object.emrCategoryCode) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择模板")
  }
  if (!object.patNo) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "请先选择患者")
  }
  if (object.times == null || object.times === 0) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "住院次数为空")
  }
}

// 前端打印
const frontEndPrinting = () => {
  waitForLoadingToComplete()
  editor.execute("print", {
    value: {
      showPreview: true,
    }
  })
}

// 服务打印
const servicePrint = () => {
  waitForLoadingToComplete()
  editor.execute("print", {
    value: {
      showPreview: true,
      mode: 'backend'
    }
  })
}

/**
 * 点击删除数据
 */
const clickDelete = () => {
  if (editorMode) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "无法删除病历。");
  }
  waitForLoadingToComplete()
  whetherThereIsAMedicalRecordId()
  if (createId !== userData.code) {
    BizException(ExceptionEnum.LOGICAL_ERROR, "创建人不是您，无法删除。");
  }
  ElMessageBox.alert('是否要删除该模板。', '提示', {
    type: 'warning'
  }).then(async () => {
    // 电子病历删除
    let res = await currentEmr.value.deleteDocument(documentId)
    if (res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        let item = res[i]
        // 删除提取到的数据源
        delete patientData[item]
        // 删除提取到的数据
        delete extractData[item]
      }
    }
    isEditorChange = false
    emrSidebarRef.value.queryData()
    emptyEditor()
  });
}

const whetherThereIsAMedicalRecordId = () => {
  if (!documentId) {
    BizException(ExceptionEnum.MESSAGE_ERROR, "请先选择患者的病历。")
  }
}

const checkEmrChange = (cb) => {
  if (isEditorChange) {
    ElMessageBox.confirm("您改变了数据是否要保存，不保存可能会丢失数据。", '提示', {
      type: "warning",
      cancelButtonText: '放弃修改',
      confirmButtonText: '保存病历',
      distinguishCancelAndClose: true,
    }).then(() => {
      clickSaveData()
    }).catch((action) => {
      if (action === 'cancel') {
        isEditorChange = false
        cb()
      }
    })
  } else {
    isEditorChange = false
    cb()
  }
}

let createName = $ref()
let createLevel = $ref(3)
const nodeClick = (val, jumpOrNot, templateType) => {
  createName = val.createName
  createId = val.createId
  if (jumpOrNot) {
    if (val.documentId === documentId) {
      positioningTime(val.value, val.code)
    } else {
      updateCaseHistoryUrl(val);
      jumpPositioning = {
        value: val.value,
        code: val.code,
      }
    }
  } else {
    checkEmrChange(() => {
      updateCaseHistoryUrl(val);
    })
  }
}

const updateCaseHistoryUrl = async (val) => {
  courseSegmentLocking()
  let temp = `/emr/runtime/?documentId=${val.documentId}&categoryCode=${val.categoryCode}&categoryId=${val.categoryId}&patientId=${patientId}#/`
  if (temp === caseHistoryUrl) return
  loaded = true
  isEditorChange = false
  documentId = val.documentId
  categoryCode = val.categoryCode
  templateName = val.name
  categoryId = val.categoryId
  caseHistoryUrl = `/emr/runtime/?documentId=${documentId}&categoryCode=${categoryCode}&categoryId=${categoryId}&patientId=${patientId}#/`
}

// 空的编辑器
const emptyEditor = () => {
  isEditorChange = false
  documentId = ''
  categoryCode = ''
  templateName = ''
  categoryId = ''
  caseHistoryUrl = `/emr/runtime/#/editor`
}

/**
 * 跳转到指定的地方
 * @param val 值
 * @param code 业务编码/内部编码/组件编码
 */
const positioningTime = (val, code) => {
  let componentView = currentEmr.value.callMethod('getElementByValue', code, val);
  if (componentView) {
    componentView.focusEnter();
    currentEmr.value.callMethod('scrollToCursor')
    currentEmr.value.callMethod('highlight', componentView, 1500)
    currentEmr.value.callMethod('scrollToCursor', true)
  }
}


const monitorPageRefresh = (event) => {
  if (isEditorChange) {
    event.preventDefault();
    return event.returnValue = "是否确实要退出？还有未保存的数据！";
  }
}

/**
 * 点击插入片段
 * @param content
 * @param styles
 * @param code 片段编码
 */
const clickSnippet = ({content, styles, code}) => {
  let temp = copyEnum[code]
  let data = patientData
  if (temp) {
    let value = getEmrCopy(temp)
    if (value) {
      data = value
      delEmrCopy(temp)
    }
  }
  if (!editorMode) {
    let root = editor.model.document.getRoot()
    let lastView = root.getChild(root.childCount - 1).view
    lastView.setAttribute('readonly', false)
    //移动到文档结尾
    editor.setCursor('DOCUMENT_END');
    editor.scrollToCursor()
    let insertContent = {
      // 内容
      value: content,
      // 样式
      styles: styles,
      isFragment: true,
      // 就是在这里填充的值
      defaultData: data
    }
    editor.execute("insertContents", insertContent);
    lastView.setAttribute('readonly', true)
    editor.setCursor('DOCUMENT_END');
    editor.scrollToCursor()
  }
}

// 用户信息
let userData = store.state.user.info
/**
 * 获取当前用户的信息
 * @param data
 */
const getCurrentPersonnelInformation = (data) => {
  patientData['编辑者'] = [{code: userData.code, name: userData.name}]
  patientData['编辑者编码'] = userData.code
  patientData['编辑者姓名'] = userData.name

  patientData['编辑者科室'] = [{code: userData.deptCode, name: userData.deptName}]
  patientData['编辑者科室编码'] = userData.deptCode
  patientData['编辑者科室名称'] = userData.deptName

  patientData.user_token = userData.token
}


// 设置编辑器的模式
const setEditorModeFun = () => {
  // 判断是不是编辑模式
  if (emrConfig.value.editor) {
    // 设置成编辑模式
    currentEmr.value.callMethod('setEditorMode', 'free')
    // 如果不是首次病程记录就需要执行下面的代码
    if (!categoryCode.includes('shoucibingchengjilu')) {
      // 如果创建人是空的就说明是第一次创建
      if (createId === null) {
        return currentEmr.value.callMethod('setEditorMode', 'free');
      }
      // 创建人不是自己就只能看
      if (doctorLevel === 1 && createId !== userData.code) {
        currentEmr.value.callMethod('setEditorMode', 'readonly');
      }
      if (doctorLevel === 2) {
        // 不能修改三级医生写的病历
        if (createId === extractFields('主任医生编码')) {
          currentEmr.value.callMethod('setEditorMode', 'readonly');
        } else {
          currentEmr.value.callMethod('setEditorMode', 'free');
        }
      }
      // 医生等级 3 没有限制
      if (doctorLevel === 3) {
        currentEmr.value.callMethod('setEditorMode', 'free');
      }
    }
    // 如果创建人不是自己就要开启审阅
    if (createId === userData.code) {
      editor.setRevisionMode('off')
    } else if (createId != null) {
      xcMessage.warning('当前病历创建人不是您，你的操作将会留痕。')
      editor.setRevisionMode('on')
    }
  } else {
    currentEmr.value.callMethod('setEditorMode', 'readonly')
  }
}

/**
 * 设置跳转锚点
 */
const setTheProgressAnchor = () => {
  if (jumpPositioning.code) {
    positioningTime(jumpPositioning.value, jumpPositioning.code)
    jumpPositioning.code = null
  }
}

/**
 * 病程记录专用，
 * 设置段落锁定，和设置跳转锚点
 */
const courseSegmentLocking = () => {
  if (!categoryCode.includes('shoucibingchengjilu')) {
    return
  }
  let root = currentEmr.value.getRoot()
  if (documentId) {
    let courseTitles = []
    let loginUserCode = userData.code
    let modelService = editor.ModelService
    let walker, values
    for (let node of root.getChildren()) {
      if (node.view && node.type === 'area') {
        if (!walker) {
          walker = modelService.createTreeWalker(node);
        } else {
          modelService.setWalkerRoot(walker, node);
        }
        values = modelService.getElementsDataFromWalker(walker, '编辑者');
        // node.view.el.firstElementChild.textContent 如果title不是数据元
        // values['查房标题'].value 如果title是数据元
        courseTitles.push({
          code: '查房时间',
          name: values['查房标题']?.value,
          value: values['查房时间']?.value,
          emrDocumentId: documentId,
          emrCategoryCode: categoryCode,
          jump: true,
          createName: values['编辑者']?.value[0].name,
          createDate: values['查房时间']?.value
        })
        if (emrConfig.value.editor) {
          let editorCode = values['编辑者']?.value[0]?.code;
          if (editorCode) {
            if (doctorLevel === 1) {
              if (editorCode !== loginUserCode) {
                node.view.setReadonly(true);
                node.view.setDeletable(false);
              } else {
                node.view.setReadonly(false);
                node.view.setDeletable(true);
              }
            }
            if (doctorLevel === 2) {
              if (editorCode === extractFields('主任医生编码')) {
                node.view.setReadonly(true);
                node.view.setDeletable(false);
              } else {
                node.view.setReadonly(false);
                node.view.setDeletable(true);
              }
            }
            if (doctorLevel === 3) {
              node.view.setReadonly(false);
              node.view.setDeletable(true);
            }
          }
        } else {
          node.view.setReadonly(true);
          node.view.setDeletable(false);
        }
      }
    }
    emrSidebarRef.value.diseaseDurationRecordTime(documentId, courseTitles)
  } else {
    for (let node of root.getChildren()) {
      if (node.view && node.type === 'area') {
        node.view.setAttribute('userInfo', {code: userData.code, name: userData.name})
      }
    }
  }
}

/**
 * 删除数据元,
 * 根据男性女性删除 月经史 数据元
 */
const deleteDataElement = () => {
  if (patientData['性别名称'] === '男') {
    currentEmr.value.deleteElement(['月经史'])
  }
}

// 重新设置提取的数据, 这里是强制替换
const reQueryPatientInformation = () => {
  // 如果不是是编辑状态
  if (!emrConfig.value.editor) return
  // 如果是只读模式就不触发这个
  if (!editorMode) {
    // 如果没有文档 id 就说明是
    if (documentId) {
      editor.setValues(extractData)
    }
  }
}

/**
 *  撤销或者重做
 */
const clickUndo = (val) => {
  editor.execute(val)
}

/**
 * 单击“提交病历”
 */
const clickToSubmitTheMedicalRecord = () => {
  if (!documentId) {
    return ElMessage.error('请先打开病历')
  }
  submitMedicalRecord(documentId)
}

const visibility = useDocumentVisibility()

watch(() => visibility.value, () => {
  if (visibility.value === 'hidden' && isEditorChange) {
    document.title = `患者【${props.huanZheXinXi.name}】，未保存数据`
  } else {
    document.title = `电子病历-正在编辑【${props.huanZheXinXi.name}】`
  }
}, {immediate: true})

/**
 * 查询患者信息
 * @returns {Promise<void>}
 */
const queryingBasicPatientInformation = async () => {
  patientData = await getEmrInpatientData({
    patNo: props.huanZheXinXi.inpatientNo,
    times: props.huanZheXinXi.admissTimes
  })
  getCurrentPersonnelInformation(patientData)
  openAssistant.data = patientData
}

// DRG 智能分组
const drgData = $ref({
  dialog: false,
  url: ''
})
// 点击查看 drg 分组 通过打开 dialog 的方式， 后续可以使用打开新的页面
const drgIntelligentGrouping = () => {
  getDrgIntelligentGrouping(props.huanZheXinXi.inpatientNo, props.huanZheXinXi.admissTimes).then(async (res) => {
    drgData.dialog = true
    drgData.url = res
  })
}

let editorMode = $ref(true)
// true 是只读 false 不是只读
const readonlyPattern = () => {
  editorMode = editor !== null && editor.getEditorMode() === 'readonly';
  return editorMode
}

// 判断 一级 二级 三级医生
let doctorLevel = $ref(1);
const doctorLevelFunc = () => {
  if (extractFields('管床医生编码') === userData.code) {
    doctorLevel = 1
    createLevel = 1
  }
  if (extractFields('主治医生编码') === userData.code) {
    doctorLevel = 2
    createLevel = 2
  }
  if (extractFields('主任医生编码') === userData.code) {
    doctorLevel = 3
    createLevel = 3
  }
}

// 提取字段
const extractFields = (val) => {
  if (patientData[val] === null) {
    return ''
  } else {
    return patientData[val]
  }
}

// 是否开启审阅模式
const isRevisionMode = () => {
  try {
    editor.setRevisionShowMode(reviewMode);
  } catch (e) {
    console.error(e)
  }

}

// 电子病历排序
const diseaseCourseSequencing = () => {
  if (!categoryCode.includes('shoucibingchengjilu')) {
    return
  }
  editor.execute('execFn', {
    value: {
      scope: this,
      params: [],
      fn: function () {
        const areas = [];        //区域数组
        let walker = null;        //遍历器
        const service = editor.ModelService; //节点工具
        const root = editor.model.document.getRoot(); //文档跟节点
        for (const node of root.getChildren()) { //遍历区域并把时间和区域关键放进areas
          if (node.type === 'area') {
            if (!walker) {
              walker = service.createTreeWalker(node)
            } else {
              service.setWalkerRoot(walker, node);
            }
            let dataElements = service.getDataElementsFromWalker(walker, '查房时间', 'business');
            let time = dataElements['查房时间'].value;
            areas.push({
              time: new Date(time).getTime(),
              t: time,
              view: node.view
            })
          }
        }
        let item = areas[0].view.el, anchor, pos; //anchor为排序插入节点，pos为位置
        if (item.previousElementSibling) {//如果第一个区域有前节点
          anchor = item.previousElementSibling
          pos = 'afterend'
        } else if (item.nextElementSibling) {//有后节点
          anchor = item.nextElementSibling
          pos = 'beforebegin'
        }
        areas.sort((item1, item2) => {
          return item1.time - item2.time
        }).forEach((item) => {
          if (!anchor) {//无前后节点之间append
            anchor.parentElement.appendChild(item.view.el)
          } else {
            anchor.insertAdjacentElement(pos, item.view.el);
            anchor = item.view.el
            pos = 'afterend'
          }
        })
      }
    }
  })
}

const paginationSymbol = () => {
  editor.execute('insertContents', {value: [{type: 'pagebreak'}]})
}

const textStyleFunc = ref({
  fontSizeAdjust: (val) => {
    editor.execute('fontSizeAdjust', {value: val})
  },
  fontFamily: () => {
    editor.execute('fontFamily', {value: emrStyle.fontFamily})
    editor.focus()
  },
  fontSize: () => {
    editor.execute('fontSize', {value: emrStyle.fontSize})
    editor.focus()
  },
  fontWeight: () => {
    let val = emrStyle.fontWeight === 'normal' ? 'bold' : 'normal'
    emrStyle.fontWeight = val
    editor.execute('fontWeight', {value: val})
    editor.focus()
  },
  fontStyle: () => {
    let val = emrStyle.fontStyle === 'normal' ? 'oblique' : 'normal'
    emrStyle.fontStyle = val
    editor.execute('fontStyle', {value: val})
    editor.focus()
  },
  underline: () => {
    emrStyle.underline = !emrStyle.underline
    let value = emrStyle.underline ? 'underline' : 'remove underline'
    editor.execute('textDecoration', {value})
  },
  lineThrough: () => {
    emrStyle.lineThrough = !emrStyle.lineThrough
    let value = emrStyle.lineThrough ? 'line-through' : 'remove line-through'
    editor.execute('textDecoration', {value})
  },
  super: () => {
    emrStyle.super = !emrStyle.super
    let value = emrStyle.super ? 'super' : 'baseline'
    editor.execute('verticalAlign', {value})
  },
  sub: () => {
    emrStyle.sub = !emrStyle.sub
    let value = emrStyle.sub ? 'sub' : 'baseline'
    editor.execute('verticalAlign', {value})
  },
  color: () => {
    editor.execute('color', {value: emrStyle.color})
  },
  backgroundColor: () => {
    editor.execute('backgroundColor', {value: emrStyle.backgroundColor})
  },
  alignment: (val) => {
    editor.execute('textAlign', {value: val})
  },
  unorderedList: (val) => {
    if (val === null) {
      editor.execute("nonList", {
        value: "none"
      })
    }
    editor.execute('symbolList', {"value": val})
  },
  orderedList: (val) => {
    if (val === null) {
      editor.execute("nonList", {
        value: "none"
      })
    }
    //设置有序列表
    editor.execute('orderList', {"value": val})
  },
  indent: (val) => {
    emrStyle.paragraphStyle.paragraphIndent.left += val
    editor.execute('paragraphStyle', {value: emrStyle.paragraphStyle})
  }
})

const scroll = ({scrollLeft: left, scrollTop}) => {
  scrollLeft = left
}

const tootScrollRef = ref(null)
let scrollLeft = 0
const mousewheel = (e) => {
  let eventDelta = -e.wheelDelta || -e.deltaY * 40;
  tootScrollRef.value?.setScrollLeft(scrollLeft + eventDelta);
}

const buttonClass = (val, activation = true) => {
  if (emrStyle[val] === activation) {
    return 'emr__button_select'
  } else {
    return 'button'
  }
}


/**
 * 解析 iframe 上面的参数保证一致
 */
const analysisIframeSrcSearch = async () => {
  // 先一步转成 url 不然 URLSearchParams 不会解析第一个参数
  const url = new URL('http://localhost' + caseHistoryUrl);
  const args = new URLSearchParams(url.search);
  documentId = args.get('documentId')
  // 如果没有的话就去服务器要一个
  if (documentId === null || documentId === 'null') {
    // 这个是 唯一 id 调用服务的雪花算法
    documentId = await getUuid()
  }
}

// 恢复历史数据
const restoreData = (data) => {
  editor.setDocument(data)
  xcMessage.success('恢复成功，请点击保存。')
  recoveryDialog = false
}

const popupRef = ref(null)
const popupFunc = {
  setShortcutKey: () => {
    editor.setShortcutKey("ALT+Q", (evt, view, position) => {
      console.log(position)
      popupRef.value.positionChange(evt, view, position)
    });
  },
  fillData: (val) => {
    hotSearchSorting(userData.code, val.queryKey, 'medical_history_prompts')
    editor.execute('insertContents', {value: [{type: 'text', data: val.content}]})
  }

}

const rightClickOnRegistration = () => {
  editor.regCtxMenu({
    global: [{
      text: '病历提示',

      handler: function (menu) {
        popupRef.value.positionChange(null, null, editor.getCursorPosition())
      }

    }]
  })
}

let zoom = 1
const zoomFunc = (val) => {
  zoom += val
  editor.execute('zoom', {value: zoom})
}

onMounted(() => {
  getExtractDataElement(props.huanZheXinXi.inpatientNo, props.huanZheXinXi.admissTimes).then((res) => {
    extractData = res
  })
  nextTick(async () => {
    emrSidebarRef.value.queryData()
    patientId = props.huanZheXinXi.inpatientNo + '_' + props.huanZheXinXi.admissTimes
    await queryingBasicPatientInformation()
    currentEmr.value = new EMRInteractive(patientData, emrEvent);
    if (emrConfig.value.editor) {
      emrSnippetRef.value.setPatientData(patientData)
    }
    doctorLevelFunc()
    emrRef.value.parentElement.emr = currentEmr.value
    window.addEventListener('beforeunload', monitorPageRefresh, {capture: true})
  })
  getWardsApi().then((res) => {
    if (res.length > 0) {
      for (let i = 0, len = res.length; i < len; i++) {
        wardList.push(res[i].code)
      }
    }
  })
})

onDeactivated(() => {
  window.removeEventListener('beforeunload', monitorPageRefresh, {capture: true})
})


onBeforeRouteLeave((to, from, next) => {
  checkEmrChange(() => {
    next();
  })
})

const closeBothSides = () => {
  foldBothSides.isLeft = false
  foldBothSides.isRight = false
}

defineExpose({
  closeBothSides
})

</script>

<style scoped lang="scss">
.emr-iframe, iframe {
  width: 100%;
  position: relative;
}

.emr__button_select {
  border: 1px solid #a0a0a0;
  font-size: 14px;
}

.button {
  border: 1px solid transparent;
  font-size: 14px;
}

.tool_emr {
  width: max-content;
  height: 30px;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
}

.color_picker {
  &:hover {
    cursor: pointer;
    color: #409EFF;
  }

  background-color: white;
}

.emr-template-open {
  width: 215px;
  background-color: white;
}

.emr-template-put-away {
  width: 10px;
  background-color: white;
}

.emr-editor {
  padding: 0 5px;
  overflow: hidden;
  display: block;
  flex: 1;
  flex-basis: auto;
  box-sizing: border-box;
}

.emr-fragment-open {
  width: 180px;
  background-color: white;
}

.emr-fragment-put-away {
  width: 10px;
  background-color: white;
}

.creator_prompt {
  position: absolute;
  display: flex;
  width: max-content;
  top: 5px;
  color: black;
  left: 5px;
  cursor: pointer;
  padding: 2px;
  z-index: 1;
  background-color: rgb(0 101 241 / 27%);
  box-shadow: 0 4px 8px rgb(0 0 0 / 20%), 0 6px 20px rgb(0 0 0 / 19%);

  div {
    margin: 2px;
  }


  .edit_mode {
    background-color: #f56c6c;
    color: white;
    align-items: center;
    display: flex;
    border-radius: 5px;
    padding: 5px;
  }

  span {
    margin: 0 2px;
  }

}

</style>
