<template>
    <div style="display: flex;align-items: center;height: 30px">
        <el-button-group>
            <el-button :disabled="!emrConfig.editor"
                       type="success"
                       icon="CircleCheck"
                       @click="clickSaveData">
                保存
            </el-button>
            <el-button
                    type="primary"
                    title="提交不是保存"
                    @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 @click="auditClick" type="primary">
                审核
            </el-button>
        </el-button-group>
        <el-divider direction="vertical"/>
        <el-button-group>
            <!--  工具   -->
            <emr-auxiliary-tools :pat-info="props.huanZheXinXi"
                                 @to-fill-in-data="clickToFillInData"
                                 :emr-data="patientData"/>
            <el-button @click="drgIntelligentGrouping"
                       type="primary"
                       title="drg的预分组">
                DRG分组
            </el-button>
            <emr-result-returns/>
        </el-button-group>
        <el-divider direction="vertical"/>
        <!--   恢复到上一次保存的状态   -->
        <historical-emr v-if="recoveryDialog"
                        @closed="recoveryDialog = false"
                        :docunent-id="documentId"
                        @restore-data="restoreData"/>
        <el-button-group>
            <el-button type="primary" icon="Printer" @click="frontEndPrinting"
                       title="页面打印支持病历续打，但是可能会出现打印错误，如果页面打印无法使用请用服务打印，服务打印也不行请换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 type="primary"
                       icon="ZoomOut"
                       @click="zoomFunc(-0.1)"
                       title="缩小病历"/>
        </el-button-group>

        <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" v-show="!completeModeSwitch"/>
        <el-button-group v-show="!completeModeSwitch">
            <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-divider direction="vertical"/>
        <el-checkbox v-model="autoSave" label="自动保存" @change="autoSaveChange"/>
        <el-checkbox v-model="isOpenPage" label="分页线" @change="openOrClosePage"/>

    </div>

    <div style="display: flex">
        <div class="modLeftRef" v-show="completeModeSwitch">
            <div ref="modLeftRef" class="refDiv"></div>
        </div>
        <div v-show="!completeModeSwitch"
             style="height: max-content"
             :class="foldBothSides.isLeft ? 'emr-template-open' : 'emr-template-put-away' "
             ref="leftRefOld">
            <div ref="leftRef">
                <emr-sidebar @nodeClick="nodeClick"
                             @open-and-save-the-medical-record="openAndSaveTheMedicalRecord"
                             @patient-medical-record="foldBothSides.isLeft = true"
                             v-show="foldBothSides.isLeft"
                             ref="emrSidebarRef"
                             :doctor-grade="doctorLevel"
                             :extract-data="extractData"
                             :patientData="patientData"
                             :max-height="maxHeight"
                             :huan-zhe-xin-xi="props.huanZheXinXi"/>
            </div>
        </div>
        <div class="emr-editor"
             :style="{marginTop: completeModeSwitch ? '10px' : 0 }">
            <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">
                <div>
                    <el-button @click="showIframe  = 1" :type="showIframe === 1 ? 'primary' : ''">正在编辑</el-button>
                    <el-button @click="showIframe  = 2" :type="showIframe === 2? 'primary' : ''">已保存病历</el-button>
                    <el-button @click="showIframe  = 3" :type="showIframe === 3? 'primary' : ''">同时打开</el-button>
                    <el-button @click="showIframe  = 4" :type="showIframe === 4? 'primary' : ''">病案首页</el-button>
                    <el-button @click="showIframe  = 5" :type="showIframe === 5? 'primary' : ''">审核</el-button>
                </div>
                <div style="display: flex;width: 100%">
                    <div :style="emrMainWidth()"
                         v-show="showIframe === 1 || showIframe === 3 ||showIframe === 5">
                        <div style="position: relative">
                            <emr-popup ref="popupRef"
                                       @fill-data="popupFunc.fillData"/>

                            <emr-web-socket :pat-info="props.huanZheXinXi"
                                            :current-editor-user="currentEditorUser"
                                            ref="emrSocket"/>

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

                                <div>
                                    等级：{{ createLevel }}
                                    <br>
                                    等级：{{ doctorLevel }}
                                    <br>
                                    科室：{{ currentEditorUser?.deptName }}
                                </div>

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

                            </div>
                            <iframe ref="emrRef"
                                    :height="iframeHeight() "
                                    :src="caseHistoryUrl"/>
                        </div>
                    </div>

                    <div v-show="showIframe === 5" style="width: 40%;">
                        <emr-audit/>
                    </div>

                    <div :style="{width: showIframe === 3 ? '50%' : '100%'}"
                         v-show="showIframe === 2 || showIframe === 3  ">
                        <div style="position:relative;">
                            <div style="position:absolute;top: 0;left: 0">
                                此病历为只读
                            </div>
                            <iframe :height="iframeHeight()"
                                    :src="saveDocumentId"/>
                        </div>

                    </div>

                    <div v-show="showIframe === 4"
                         style="width: 100%;overflow-y:auto"
                         :style="{height : iframeHeight() }">
                        <!--             病案首页           -->
                        <emr-first-page-of-medical-record :pat-info="huanZheXinXi"/>
                    </div>

                </div>

            </div>
        </div>
        <div class="modRightRef" v-show="completeModeSwitch">
            <div ref="modRightRef" class="refDiv"></div>
        </div>

        <div v-show="!completeModeSwitch"
             style="height: max-content"
             :class="foldBothSides.isRight ? 'emr-fragment-open' : 'emr-fragment-put-away' "
             ref="rightRefOld">
            <div ref="rightRef">
                <emr-snippet
                        v-show="foldBothSides.isRight"
                        @node-click="clickSnippet"
                        ref="emrSnippetRef"
                        :max-height="maxHeight"/>
            </div>
        </div>

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

        <xc-dialog-v2 v-model="saveDialog.dialog" title="提示" manualShutdown destroy-on-close>
            <el-input v-model="saveDialog.name"
                      ref="saveInputRef"
                      maxlength="20"
                      minlength="1"
                      show-word-limit/>
            <br> <br>

            <el-alert type="warning" title="正在解析病程记录，请稍等。" v-if="解析病程提示"/>
            <el-alert type="success" title="解析完成，点击确认即可。" v-else/>

            <emr-connotation :category-code="categoryCode"/>

            <template #footer>
                <el-button @click="saveDialog.close"
                           :disabled="saveDialog.analyzeTheCourseOfTheDisease"
                           type="danger">
                    取消
                </el-button>
                <el-button @click="saveDialog.submit"
                           :disabled="saveDialog.analyzeTheCourseOfTheDisease"
                           type="primary">
                    确认
                </el-button>
            </template>
        </xc-dialog-v2>


    </div>
</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,
    completeModeSwitch,
    emrMitt
} 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 {
    audit,
    getDrgIntelligentGrouping,
    getExtractDataElement, hotSearchSorting,
    submitMedicalRecord
} from "@/api/zhu-yuan-yi-sheng/emr-patient";
import {useDocumentVisibility} from "@vueuse/core";
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";
import sleep from "@/utils/sleep";
import EmrWebSocket from "@/components/zhu-yuan-yi-sheng/emr/web-socket/EmrWebSocket.vue";
import {stringIsBlank} from "@/utils/blank-utils";
import {isDev, needRule} from "@/utils/public";
import {isThereADoctorEditing} from "@/api/zhu-yuan-yi-sheng/emr-socket";
import {onDeactivated} from "vue";
import EmrFirstPageOfMedicalRecord from "@/components/zhu-yuan-yi-sheng/emr/EmrFirstPageOfMedicalRecord.vue";
import EmrResultReturns
    from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/components/EmrResultReturns.vue";
import EmrAudit
    from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/components/EmrAudit.vue";
import EmrConnotation
    from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/components/EmrConnotation.vue";


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

const currentEmr = ref(null)
const emrRef = ref(null)
const emrSocket = 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 patientData = $ref({})
// 编辑器
let editor = null
// 侧边栏
const emrSidebarRef = ref(null)
// 片段预览
const emrSnippetRef = ref(null)
// 是否加载完成了
let loaded = $ref(false)
// 是否 改变了数据
let isEditorChange = $ref(false)
// 是否开启审阅模式
let reviewMode = $ref(2)
// 跳转定位
let jumpPositioning = {
    value: '',
    // 这里是业务编码
    code: null
}
let wardList = []
// 创建人 id
let createId = null;
// 获取提取到的数据。
let extractData = $ref({})
let editorMod = $ref(false)
let parent = ''

let fragmentsCannotBeInserted = false

let currentEditorUser = $ref(null)

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

let emrCodeEnum = {
    // 病程记录
    courseRecord: 'shoucibingchengjilu'
}

const isCourse = () => {
    return categoryCode === 'shoucibingchengjilu' || categoryCode === 'xinshengerjianhujilu';
}

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',
])

let autoSave = $ref(true)

const emrMainWidth = () => {
    if (showIframe.value === 3) {
        return {
            width: '50%'
        }
    }
    if (showIframe.value === 5) {
        return {
            width: '60%'
        }
    }
    return {
        width: '100%'
    }
}

const emrEvent = {
    'loaded': async (event) => {
        editor = currentEmr.value.getEditor()
        loaded = false
        // 获取医生等级
        doctorLevelFunc()
        // 设置 编辑器的模式
        setEditorModeFun()
        // 设置病程记录中的跳转锚点
        await courseSegmentLocking()
        // 设置病程记录跳转
        setTheProgressAnchor()
        // 删除指定的数据元
        deleteDataElement()
        // 是否开启审阅模式
        reviewMode = 2
        isRevisionMode()
        // 判断是否只读
        readonlyPattern()
        // 填充患者数据
        reQueryPatientInformation()
        // 每一个病历只能一个人编辑
        await editJudgment()
        openOrClosePage(isOpenPage.value)
    },

    'contentchange': (e, op) => {
        if (op.batch.type === 'persist') return
        if (!readonlyPattern()) {
            // 如果是空的编辑器就不触发了
            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()
    },
    "editorModeChange": () => {
        readonlyPattern()
    },
    "insertFragment": async (evt, rootView, nodes, fragment, defaultData) => {
        fragmentsCannotBeInserted = true
        //插入的内容是区域片段
        if (nodes.length === 1 && nodes[0].view && nodes[0].view.type === 'area') {
            let view = nodes[0].view
            let modelService = editor.ModelService;
            let node = view.model
            let walker = modelService.createTreeWalker(node);
            let values = modelService.getElementsDataFromWalker(walker, '编辑者');
            let newDate = await getServerDateApi()
            view.setAttribute('fragment', {
                name: values['查房标题'].value,
                createId: userData.code,
                creationTime: newDate,
                referPhysician: extractFields('管床医生编码'),
                consultPhysician: extractFields('主治医生编码'),
                deptDirector: extractFields('主任医生编码'),
            })
        }
        fragmentsCannotBeInserted = false
    },
    "areaFocus": (evt, view) => {
        let modelService = editor.ModelService;
        let node = view.model

        let walker = modelService.createTreeWalker(node);
        let values = modelService.getElementsDataFromWalker(walker, '编辑者');
        let editorCode = values['编辑者']?.value[0]?.code;
        if (editorCode) {
            openTheTraceByUser(editorCode)
        }
    },
    "areaBlur": () => {
        // 区域失去焦点
        // editor.setRevisionMode('off')
    }
}

let saveInputRef = $ref()
let saveDialog = $ref({
    dialog: false,
    name: '',
    cb: null,
    err: null,
    analyzeTheCourseOfTheDisease: false,
    prompt: (name, cb, err) => {
        saveDialog.name = name
        saveDialog.cb = cb
        saveDialog.err = err
        nextTick(async () => {
            await sleep(200)
            saveInputRef.focus()
        })
    },
    close: () => {
        saveDialog.dialog = false
        if (saveDialog.err !== null) {
            saveDialog.err(saveDialog.name)
        }
        saveDialog.clear()
    },
    submit: () => {
        if (saveDialog.name.length > 20) {
            xcMessage.error('模板最大长度 20 个字')
            return
        }
        saveDialog.cb(saveDialog.name);
        saveDialog.dialog = false
        saveDialog.clear()
    },
    clear: () => {
        saveDialog.name = ''
        saveDialog.cb = null
        saveDialog.name = null
    }
})

const editJudgment = async () => {
    emrSocket.value.clearDocument();
    await sleep(100)
    // 没有病历 id 不锁柱
    if (stringIsBlank(documentId)) {
        return
    }
    // 发送正在看的病历
    emrSocket.value.medicalRecordSwitching(userData.name + '正在编辑或查看【' + templateName + '】病历')
        .then(() => {
        }).catch(() => {
    })
    // 不能编辑 不锁柱
    if (!emrConfig.value.editor) {
        return
    }
    // 只读模式不锁柱
    if (readonlyPattern()) {
        return
    }
    currentEditorUser = await isThereADoctorEditing(documentId)
    console.log('有人正在编辑病历 %o', currentEditorUser)
    if (currentEditorUser === null) {
        emrSocket.value.documentChange(documentId);
    } else if (currentEditorUser.code != userData.code) {
        ElMessageBox.alert(`医生：【${currentEditorUser.name}】，科室：【${currentEditorUser.deptName}】，正在编辑病历，请医生退出后，重新打开病历。`, '提示', {
            type: 'error'
        }).then(() => {
        }).catch(() => {
        })
        editor.setEditorMode('readonly')
    }
    readonlyPattern()
}

// 点击保存病历
const clickSaveData = async () => {
    // 只读模式无法保存数据
    if (readonlyPattern()) {
        BizException(ExceptionEnum.MESSAGE_ERROR, "当前为只读模式，无法保存病历。");
    }
    if (editor === null) return
    waitForLoadingToComplete()
    // 判断是否有必填项目
    let validator = editor.getValidator();
    let valid = validator.valid();

    if (valid) {
        BizException(ExceptionEnum.MESSAGE_ERROR, "有必填项不能为空,请仔细检查,红色输入框.")
    }
    // 解析 id
    await analysisIframeSrcSearch()
    let data = {
        emrDocumentId: documentId,
        emrCategoryCode: categoryCode,
        patNo: props.huanZheXinXi.inpatientNo,
        times: props.huanZheXinXi.admissTimes,
        emrName: templateName,
        categoryId: categoryId,
        fragment: [],
        parent: parent
    }
    objectValuesCannotBeNull(data)
    data.emrDataElement = editor.getDataElements('business')
    if (categoryCode === emrCodeEnum.courseRecord) {
        templateName = '病程记录'
    }
    saveDialog.dialog = true
    data.fragment = 解析病程记录()
    saveDialog.prompt(templateName, 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('保存失败请重新保存')
        })

    }, (err) => {
        console.log(err)
    })

}

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

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

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

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

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

/**
 * 点击删除数据
 */
const clickDelete = () => {
    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 auditClick = () => {
    if (doctorLevel < 2) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '您不是改患者的上级医生，无法进行该操作。')
    }
    whetherThereIsAMedicalRecordId()
    waitForLoadingToComplete()
    audit(documentId)
}

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

const checkEmrChange = (cb) => {
    if (readonlyPattern()) {
        isEditorChange = false
    }
    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
    parent = val.parent
    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) => {
    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)
    }
}


/**
 * 点击插入片段
 * @param content
 * @param styles
 * @param code 片段编码
 */
const clickSnippet = async ({content, styles, code}) => {

    // 为了防止上一次插入还没有完成，就再次插入了
    if (fragmentsCannotBeInserted) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '请勿点击过快。')
    }

    let temp = copyEnum[code]
    let data = patientData
    if (temp) {
        let value = getEmrCopy(temp)
        if (value) {
            data = value
            delEmrCopy(temp)
        }
    }
    if (readonlyPattern()) {
        return
    }
    let root = editor.model.document.getRoot()
    let lastView = root.getChild(root.childCount - 1).view
    let isReadonly = lastView.readonly
    if (isReadonly) {
        lastView.setAttribute('readonly', false)
    }
    // 移动到文档结尾
    editor.setCursor('DOCUMENT_END');
    editor.scrollToCursor()
    let insertContent = {
        // 内容
        value: content,
        // 样式
        styles: styles,
        isFragment: true,
        // 就是在这里填充的值
        defaultData: data,
    }
    editor.setRevisionMode('off')
    editor.execute("insertContents", insertContent);
    if (isReadonly) {
        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 (!isCourse()) {
            // 如果创建人是空的就说明是第一次创建
            if (createId === null) {
                return currentEmr.value.callMethod('setEditorMode', 'free');
            }
            if (createId == userData.code) {
                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');
            }
            // 如果创建人不是自己就要开启审阅
            openTheTraceByUser(createId)
        }
    } else {
        currentEmr.value.callMethod('setEditorMode', 'readonly')
    }
}

/**
 * 根据用户的id来判断是否开启流痕
 * @param editorCode
 */
const openTheTraceByUser = (editorCode) => {
    if (editorCode === userData.code) {
        editor.setRevisionMode('off')
    } else {
        editor.setRevisionMode('on')
        xcMessage.warning('当前病历创建人不是您，你的操作将会留痕。')
    }
}

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

/**
 * 病程记录专用，
 * 设置段落锁定，和设置跳转锚点
 */
const courseSegmentLocking = async () => {
    if (!isCourse()) {
        return
    }
    if (documentId) {
        let courseTitles = [];
        let loginUserCode = userData.code;
        循环病程返回数据元((value, node) => {
            let fragment = node.getAttribute('fragment')
            let pushData = {
                code: '查房时间',
                name: value['查房标题']?.value,
                value: value['查房时间']?.value,
                emrDocumentId: documentId,
                emrCategoryCode: categoryCode,
                jump: true,
                createName: createName,
                createDate: value['查房时间']?.value,
                createId: createId,
                type: 'category',
            }
            if (fragment != null) {
                pushData.trueCreationTime = fragment?.creationTime
            }
            courseTitles.push(pushData);

            if (emrConfig.value.editor) {
                let editorCode = value['编辑者']?.value[0]?.code;
                if (editorCode) {
                    // 只有自己可以删除自己创建的片段
                    if (editorCode === loginUserCode) {
                        node.view.setReadonly(false);
                        node.view.setDeletable(true);
                    } else if (doctorLevel === 1) {
                        if (editorCode !== loginUserCode) {
                            node.view.setReadonly(true);
                            node.view.setDeletable(false);
                        } else {
                            node.view.setReadonly(false);
                            node.view.setDeletable(false);
                        }
                    } else if (doctorLevel === 2) {
                        if (editorCode === extractFields('主任医生编码')) {
                            node.view.setReadonly(true);
                            node.view.setDeletable(false);
                        } else {
                            node.view.setReadonly(false);
                            node.view.setDeletable(false);

                        }
                    } else if (doctorLevel === 3) {
                        node.view.setReadonly(false);
                        node.view.setDeletable(false);
                    }
                }
            } else {
                node.view.setReadonly(true);
                node.view.setDeletable(false);
            }
        })
        emrSidebarRef.value.diseaseDurationRecordTime(documentId, courseTitles);
    }
}


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

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

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

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

}

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

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

// 判断 一级 二级 三级医生
let doctorLevel = $ref(1);
const doctorLevelFunc = () => {
    doctorLevel = grade(userData.code)
    createLevel = grade(createId)
}

function grade(userCode) {
    if (needRule(1)) {
        doctorLevel = 3
    }
    if (extractFields('管床医生编码') === userCode) {
        return 1;
    }
    if (extractFields('主治医生编码') === userCode) {
        return 2
    }
    if (extractFields('主任医生编码') === userCode) {
        return 3
    }
    return 1
}


// 提取字段
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 (!isCourse()) {
        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 () => {
    let id = editor.documentData._id
    if (stringIsBlank(id)) {
        // 这个是 唯一 id 调用服务的雪花算法
        documentId = await getUuid()
    } else {
        documentId = id
    }
}

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

const popupRef = ref(null)
const popupFunc = {
    setShortcutKey: () => {
        editor.setShortcutKey("ALT+Q", (evt, view, 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})
}

let interval = null
let intervalTime = 1000 * 60 * 5
const autoSaveChange = () => {
    store.commit('app/setEmrAutosave', autoSave)
    if (interval != null) {
        clearInterval(interval)
    }
    if (autoSave) {
        interval = setInterval(() => {
            autoSaveFunc()
        }, intervalTime)
    } else {
        clearInterval(interval)
    }
}

const autoSaveFunc = () => {
    if (saveDialog.dialog) {
        saveDialog.close()
        clickSaveData()
    } else {
        clickSaveData()
    }
}

/**
 * 拦截
 * @param event
 */
const monitorPageRefresh = (event) => {
    if (readonlyPattern()) {
        isEditorChange = false;
    }
    if (isEditorChange) {
        event.preventDefault();
        event.returnValue = "是否确实要退出？还有未保存的数据！";
    }
}

/**
 * 打开已经保存了的病历
 * @param id 病历 id
 */
const openAndSaveTheMedicalRecord = (id) => {
    saveDocumentId.value = `/emr/runtime/?documentId=${id}#/`
    showIframe.value = 2
}

const showIframe = ref(1)
const saveDocumentId = ref()

const visibility = useDocumentVisibility()

onMounted(async () => {
    pageIsZoom()
    autoSave = store.state.app.emrAutosave;
    extractData = await getExtractDataElement(props.huanZheXinXi.inpatientNo, props.huanZheXinXi.admissTimes)
    await nextTick()
    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)
            }
        }
    })

    autoSaveFunc()

    emrMitt.on('editor', () => {
        return editor
    })

    emrMitt.on('setShowIframe', (val) => {
        showIframe.value = val
    })

    watch(() => visibility.value, () => {
        // 离开页面的时候清空定时器
        if (visibility.value === 'hidden' && isEditorChange) {
            if (interval != null) {
                clearInterval(interval)
            }
            document.title = `患者【${props.huanZheXinXi.name}】，未保存数据`
        } else {
            autoSaveChange()
            document.title = `电子病历-正在编辑【${props.huanZheXinXi.name}】`
        }
    }, {immediate: true})

})

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

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


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

const iframeHeight = () => {
    if (completeModeSwitch.value) {
        return props.maxHeight - (10 + 30 + 24) + 20 + 'px'
    } else {
        return props.maxHeight - 110 + 'px'
    }
}

const headerRef = ref(null)
const headerRefOld = ref(null)

const modLeftRef = ref(null)
const leftRefOld = ref(null)
const leftRef = ref(null)

const modRightRef = ref(null)
const rightRef = ref(null)
const rightRefOld = ref(null)


const turnOnConciseMode = () => {
    modLeftRef.value.appendChild(leftRef.value)
    modRightRef.value.appendChild(rightRef.value)
}

const exitConciseMode = () => {
    leftRefOld.value.appendChild(leftRef.value)
    rightRefOld.value.appendChild(rightRef.value)
}

const closeWebSocket = () => {
    emrSocket.value.clearDocument()
    emrSocket.value.clearSocket()
}

const changeClear = () => {
    isEditorChange = false
}

const isOpenPage = ref(false)
const openOrClosePage = (val) => {
    editor.setPaginate(val)
}

const 解析病程记录 = () => {
    if (!isCourse()) {
        saveDialog.analyzeTheCourseOfTheDisease = false
        return
    }
    saveDialog.analyzeTheCourseOfTheDisease = true
    let fragment = []
    循环病程返回数据元((values, node) => {
        let data
        let fragmentData = node.view.getAttribute('fragment')

        function listNull(name) {
            let temp = null
            try {
                values[name]?.value[0]?.code
            } catch (e) {
            }
            return temp
        }

        // 以前老数据是没有的所以做不到质控
        if (typeof fragmentData === 'undefined') {
            data = {
                name: values['查房标题']?.value,
                createId: listNull('编辑者'),
                creationTime: values['查房时间']?.value,
                referPhysician: values['编辑者']?.value[0]?.code,
                consultPhysician: listNull('上级医师签名'),
                deptDirector: extractFields('主任医生编码'),
            }
            if (!data.name) {
                positioningTime(data.creationTime, '查房时间')
                saveDialog.close()
                BizException(ExceptionEnum.MESSAGE_ERROR, '片段中存在异常标题，请检查。')
            }
        } else {
            let tempDate = fragmentData.creationTime
            if (!fragmentData.creationTime) {
                tempDate = values['查房时间']?.value
            }
            data = fragmentData
            data.creationTime = tempDate
        }
        if (!data.creationTime) {
            saveDialog.close()
            BizException(ExceptionEnum.MESSAGE_ERROR, '片段中存在异常查房时间，请检查。')
        }
        node.view.setAttribute('fragment', data)
        fragment.push(data)
    })
    saveDialog.analyzeTheCourseOfTheDisease = false
    return fragment
}

const 解析病程提示 = computed(() => {
    if (!isCourse()) {
        return false
    } else {
        return saveDialog.analyzeTheCourseOfTheDisease
    }
})

const 循环病程返回数据元 = (callback) => {
    let root = currentEmr.value.getRoot()
    let walker, values;
    let modelService = editor.ModelService;
    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, '编辑者');
            callback(values, node)
        }
    }
}

const pageIsZoom = () => {
    let rate = changeRatio();
    if (rate !== 100) {
        ElMessageBox.alert("当前页面不是100%显示，请按键盘ctrl+0恢复100%显示标准，如果页面是100%缩放请检查系统缩放（可自行百度），设置=》屏幕缩放（选择100%），以防页面显示错乱，以及续打对不准！", '提示', {
            type: "warning"
        }).then(() => {
        }).catch(() => {
        })
        return true
    }
    return false
}

function changeRatio() {
    let ratio = 0;
    const screen = window.screen;
    const ua = navigator.userAgent.toLowerCase();

    if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }

    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }

    if (ratio) {
        ratio = Math.round(ratio * 100);
    }
    return ratio;
}


defineExpose({
    closeBothSides,
    headerRef,
    headerRefOld,
    turnOnConciseMode,
    exitConciseMode,
    closeWebSocket,
    changeClear
})

</script>

<style scoped lang="scss">
.tabs {
  padding: 5px 10px;
  border: 1px solid #000;
  width: max-content;
}

.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;
  }

}

.modLeftRef {
  position: fixed;
  height: 100%;
  width: 20px;
  z-index: 10;

  .refDiv {
    display: none;
  }

  &:hover {
    width: max-content;
    background-color: white;

    .refDiv {
      display: block;
    }
  }
}


.modRightRef {
  position: fixed;
  height: 100%;
  width: 20px;
  z-index: 10;
  right: 0;

  .refDiv {
    display: none;
  }

  &:hover {
    width: max-content;
    background-color: white;

    .refDiv {
      display: block;
    }
  }
}

</style>
