<template>
    <div class="modHeaderRef" v-show="conciseMode">
        <div ref="modHeaderRef" class="modHeaderDiv"/>
    </div>
    <div ref="headerRefOld">
        <div ref="headerRef">
            <emr-select-pat :pat-info="patientInfo" v-if="emrConfig.editor" @selected="selected"/>
            住院号：
            <el-input v-model="query.patNo" style="width: 120px" @blur="query.patNo = $event.target.value.trim()"/>
            次数 ({{ query.times }})
            <emr-leave-hospital-patient @rowClick="disPatients"/>
            <el-button @click="allPatientsInTheHospital" :disabled="query.state === 4">全院患者</el-button>
            <el-button @click="emrSocketUnlock">解锁重复打开病历</el-button>
            <!--    解锁病历质控        -->
            <emr-quality-control-relieve/>
            <el-button @click="patientListDrawer = !patientListDrawer">患者列表</el-button>
            <el-checkbox v-model="conciseMode" @change="openOrCloseMode" label="简洁模式"/>
            出院天数：{{ dischargeDays }}
            <span style="color: red">出院七天后就无法编辑患者病历</span>
        </div>
    </div>

    <div v-if="show">
        <div ref="patInfoRefOld">
            <div ref="patInfoRef">
                <huan-zhe-xin-xi
                        :huan-zhe-xin-xi="patientInfo"
                        @isShow="patientInfoIsShow"/>
            </div>
        </div>

        <emr-main
                ref="emrMainRef"
                :huan-zhe-xin-xi="patientInfo"
                :max-height="maxHeight"/>
    </div>
    <emr-patient-list @rowClick="listRowClick" v-model="patientListDrawer"/>

  <!--    <xc-dialog-v2 v-model="dialog" title="病历限制" manual-shutdown>-->
  <!--        <div style="color: red;font-size: 24px">-->
  <!--            请各位医生先阅读操作指南 8.15.病历限制，点击下载和在线阅读即可关闭当前弹窗。-->
  <!--        </div>-->
  <!--        <template #footer>-->
  <!--            <el-button @click="操作指南(1)">下载</el-button>-->
  <!--            <el-button @click="操作指南(2)">在线阅读</el-button>-->
  <!--        </template>-->
  <!--    </xc-dialog-v2>-->
</template>

<script setup name='Home'>
import EmrMain from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/EmrMain.vue";
import {getDisPatient, getPatientInfo} from "@/api/inpatient/patient";
import router from "@/router";
import HuanZheXinXi from "@/components/zhu-yuan-yi-sheng/HuanZheXinXi.vue";
import {BizException, ExceptionEnum} from "@/utils/BizException";
import {isDisReqEdit} from "@/api/zhu-yuan-yi-sheng/emr-patient";
import {getOperationGuide, getServerDateApi} from "@/api/public-api";
import {subtractTime} from "@/utils/date";
import {
    applicationData, canIUnlockIt,
    completeModeSwitch,
    conciseMode,
    emrConfig, emrMitt,
    query,
    resolveRoute, unlockEnum
} from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init";
import EmrPatientList from "@/components/zhu-yuan-yi-sheng/emr/EmrPatientList.vue";
import EmrLeaveHospitalPatient from "@/components/zhu-yuan-yi-sheng/emr/EmrLeaveHospitalPatient.vue";
import EmrSelectPat from "@/components/zhu-yuan-yi-sheng/EmrSelectPat.vue";
import XcDialogV2 from "@/components/xiao-chan/dialog/XcDialogV2.vue";
import {emrSocketUnlockApi, repeatedlyOpenTheSamePatient} from "@/api/zhu-yuan-yi-sheng/emr-socket";
import {stringIsBlank, stringNotBlank} from "@/utils/blank-utils";
import EmrQualityControlRelieve
    from "@/components/zhu-yuan-yi-sheng/emr/EmrQualityControlRelieve/EmrQualityControlRelieve.vue";
import {getMyUnlockByPatNo} from "@/api/zhu-yuan-yi-sheng/emr-control-rule";
import store from "@/store";

const patInfoRef = ref(null)
const patInfoRefOld = ref(null)

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

const modHeaderRef = ref(null)
const emrMainRef = ref(null)
// 最大高度
let maxHeight = $ref()
// 是否显示页面
let show = $ref(false)
// 获取患者信息
let patientInfo = $ref({})
// 距离今天的出院天数
let dischargeDays = $ref(0)
// 患者列表 list
let patientListDrawer = $ref(false)


let dialog = $ref(true)

const selected = ({inpatientNo, admissTimes}) => {
    query.value.patNo = inpatientNo
    query.value.times = admissTimes
    query.value.maxTimes = admissTimes
    allPatientsInTheHospital()
}

// 点击查询出院患者
const disPatients = async () => {
    if (query.value.times === 0 || !query.value.patNo) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '请输入住院号，住院次数不能为 0 ')
    }
    query.value.state = 2
    let te = JSON.stringify(query.value)
    await router.push('/myEmrEditor/' + window.btoa(te))
    location.reload()
    await routerFunc()
}

// 解析路由数据
const routerFunc = async () => {
    emrMainRef.value?.closeWebSocket()
    show = false
    if (router.currentRoute.value.params.pat) {
        resolveRoute(router.currentRoute.value.params.pat)
        let sid = 'emr_' + query.value.patNo.trim() + "_" + query.value.times
        let res = await repeatedlyOpenTheSamePatient(sid)
        console.log('重复打开病历 %o 连接 %s', res, sid);
        if (res) {
            show = false
            BizException(ExceptionEnum.LOGICAL_ERROR, "请勿重复打开病历。")
        }
        let reqUnlock = await getMyUnlockByPatNo(query.value.patNo, query.value.times)
        console.log('申请数据 %o', reqUnlock)
        if (reqUnlock != null) {
            reqUnlock.unlockJson = JSON.parse(reqUnlock.unlockJson)
            applicationData.value = reqUnlock
        } else {
            applicationData.value = null
        }
        if (query.value.state !== 2) {
            patientInfo = await getPatientInfo(query.value.patNo);
            patientInfo.$inOutFlag = 1;
        }
        if (query.value.state === 1) {
            await queryActPatient()
        } else if (query.value.state === 2) {
            await queryDisPatient()
        } else if (query.value.state === 3) {
            await queryAllPatients(true)
        } else if (query.value.state === 4) {
            await queryAllPatients(false)
        } else if (query.value.state === 5) {
            await queryDisPatient()
            emrConfig.value.editor = false
        }
        await nextTick();
    } else {
        show = false
    }
}

// 查询在院患者数据
const queryActPatient = async () => {
    show = true
}

// 查询出院患者信息
const queryDisPatient = async () => {
    patientInfo = await getDisPatient(query.value.patNo, query.value.times)
    patientInfo.$inOutFlag = 2
    dischargeDays = subtractTime(await getServerDateApi(), patientInfo.disDate)
    // 如果患者的出院时间大于 7 天就只能看病历和打印病历了
    emrConfig.value.editor = dischargeDays <= 7;
    // 如果超过了七天就去查看是否有申请编辑
    if (!emrConfig.value.editor) {
        emrConfig.value.editor = canIUnlockIt(unlockEnum.出院编辑)
    }
    show = true;
}

// 点击全院患者数据
const allPatientsInTheHospital = async () => {
    if (!query.value.patNo) {
        BizException(ExceptionEnum.MESSAGE_ERROR, '请输入住院号。 ')
    }
    query.value.state = 3
    let te = JSON.stringify(query.value)
    await router.push('/myEmrEditor/' + window.btoa(te))
    location.reload()
    await routerFunc()
}


const queryAllPatients = async (flag) => {
    query.value.times = patientInfo.admissTimes
    query.value.maxTimes = patientInfo.admissTimes
    show = true
    emrConfig.value.editor = flag
}

const listRowClick = async (val) => {
    let temp = {
        patNo: val.inpatientNo,
        times: val.admissTimes,
        maxTimes: val.admissTimes,
        state: 4
    }
    let te = JSON.stringify(temp)
    await router.push('/myEmrEditor/' + window.btoa(te))
    location.reload()
    await routerFunc()
}

const patientInfoIsShow = (flag, height) => {
    maxHeight = window.innerHeight - height - 24
}

const 操作指南 = (val) => {
    let fileName = null
    getOperationGuide("住院医生教程").then((res) => {
        fileName = res
        if (val === 1) {
            window.open(`http://webhis.thyy.cn:8080/download/操作指南/住院医生教程/住院医生操作指南 ${fileName}.docx`, '_blank')
        } else {
            window.open(`http://webhis.thyy.cn:8080/download/操作指南/住院医生教程/住院医生操作指南 ${fileName}.pdf`, '_blank')
        }
        localStorage.setItem("电子病历限制", "false")
        dialog = false
    })
}

const openOrCloseMode = (val) => {
    if (val) {
        modHeaderRef.value.appendChild(headerRef.value);
        modHeaderRef.value.appendChild(patInfoRef.value);
        emrMainRef.value.turnOnConciseMode();
    } else {
        headerRefOld.value.appendChild(headerRef.value)
        patInfoRefOld.value.appendChild(patInfoRef.value)
        emrMainRef.value.exitConciseMode();
    }
    completeModeSwitch.value = val
}

const channel = new BroadcastChannel('login-channel');
channel.addEventListener('message', (event) => {
    if (navigator.userAgent.indexOf("Firefox") !== -1 || navigator.userAgent.indexOf("Chrome") !== -1) {
        emrMainRef.value.changeClear()
        window.location.href = "about:blank";
        window.close();
    } else {
        emrMainRef.value.changeClear()
        window.opener = null;
        window.open("", "_self");
        window.close();
    }
})

const emrSocketUnlock = async () => {
    let documentSid = ''
    try {
        let editor = emrMitt.emit('editor')
        let id = editor.documentData._id
        let userData = store.state.user.info
        if (stringNotBlank(id)) {
            documentSid = 'documentEmr_' + id + '_' + userData.code;
        }
    } catch {

    }
    await emrSocketUnlockApi('emr_' + query.value.patNo.trim() + '_' + query.value.times, documentSid)
    show = false
    location.reload()
    await routerFunc()
}

onMounted(async () => {
    let temp = localStorage.getItem("电子病历限制")
    if (temp !== null) {
        dialog = false
    }
    await nextTick();
    await routerFunc()
})


</script>

<style scoped lang="scss">
.modHeaderRef {
  height: 10px;
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 10;

  .modHeaderDiv {
    display: none;
    padding: 10px;
  }

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

    .modHeaderDiv {
      display: block;
    }
  }
}
</style>
