<template>
  <div class="layout_display_flex_y">
    <div class="m-b_8px round-header">
      <el-select v-model="search.current" style="width: 70px">
        <el-option v-for="item in search.methods" :key="item.code" :value="item.code"
                   :label="item.name"></el-option>
      </el-select>
      <span v-if="permission < 10" style="margin-left: 8px">
            <el-input v-model="search.zyh" style="width: 100px" clearable @keyup.enter="searchPatient"
                      placeholder="住院号"></el-input>
            <el-button type="primary" icon="Search" @click="searchPatient">检索</el-button>
          </span>
      <el-button type="primary" icon="Postcard" @click="checkIdCard" style="margin-left: 8px">身份信息</el-button>
      <el-button type="success" icon="Document" @click="getRegInfo">登记信息</el-button>
      <el-button type="primary" icon="Tickets" @click="beforeGetTreatinfo">待遇检查</el-button>
      <el-button icon="Document" @click="openEmr">电子病历</el-button>
      <el-button @click="printWristStrap">打印腕带</el-button>
      <BloodSugar :pat-no="patient.inpatientNo" :times="patient.admissTimes" :old-button="false"/>
    </div>
    <div class="layout_flex_1-y layout_display_flex">
      <div style="width: max-content;margin-right: 8px">
        <Overview ref="overview" :showSelection="isUploadPage"/>
      </div>
      <div class="layout_flex_1-x">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive>
              <component :is="Component"/>
            </keep-alive>
          </transition>
        </router-view>
        <Registinfo v-if="showRegisterInfo" :params="patient" @close="showRegisterInfo = false"></Registinfo>
        <IdentifyImage v-if="showIdCardImg" :pat-no="patient.inpatientNo" :times="patient.admissTimes"
                       @close="showIdCardImg = false"></IdentifyImage>
        <Insuinfo v-if="showPsnInsuinfo" :params="checkTreatmentParams" @close="showPsnInsuinfo = false"
                  @row-click="checkTreatmentinfos"/>
        <Treatmentinfo v-if="showTreatmentinfos" :params="checkTreatmentParams" @close="showTreatmentinfos = false"/>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, reactive, ref} from 'vue'
import {getPatientInfo} from '@/api/inpatient/patient'
import {nullPatient} from '@/utils/validate'
import {getGreatestRole} from '@/utils/permission'
import {baseinfo, setBaseinfo} from '@/data/inpatient'
import Overview from '../../../components/medical-insurance/patient-overview/Index.vue'
import IdentifyImage from '../../../components/inpatient/IdentifyImage.vue'
import Registinfo from '../../../components/medical-insurance/registinfo/Index.vue'
import PageLayer from "@/layout/PageLayer";
import {
  emrStateEnum,
  getEmrUrl
} from "@/views/hospitalization/zhu-yuan-yi-sheng/electronic-medical-record/emr-editor/emr-init";
import Treatmentinfo from "@/components/medical-insurance/treatmentinfo/Index.vue";
import Insuinfo from "@/components/medical-insurance/insuinfo/Index.vue";
import {ElMessage} from "element-plus";
import {getDatetime} from "@/utils/date";
import {getLodop, initLodop} from "@/utils/c-lodop";
import {useMedinsStore} from "@/pinia/medins-store";
import BloodSugar from "@/views/hospitalization/zhu-yuan-yi-sheng/yi-zhu-lu-ru/components/BloodSugar.vue";

const search = initSearchParam()
const permission = getGreatestRole()
const patient = computed(() => {
  return baseinfo()
})

const medinsStore = useMedinsStore()
const injuryMode = computed(() => {
  return medinsStore.isInjuryMode
})

const isUploadPage = computed(() => {
  return medinsStore.currentPageName === 'inHospFeeUpload' && !injuryMode.value
})

const overview = ref(null)

const searchPatient = () => {
  if (!search.zyh) {
    overview.value.fetchOverviews()
    setBaseinfo({})
  } else {
    if (permission < 10) {
      overview.value.overviews = []
      setBaseinfo({
        totalCharge: '0.00',
        chargeYb: '0.00'
      })
      getPatientInfo(search.zyh).then((res) => {
        overview.value.currentWard = res.admissWard
        medinsStore.setCurrentWard(res.admissWard)
        medinsStore.setCurrentMedType(res.medType)
        setBaseinfo(res)
        overview.value.overviews.push(makeOverview(res))
      })
    }
  }
}

const showRegisterInfo = ref(false)
const getRegInfo = () => {
  if (nullPatient()) return
  showRegisterInfo.value = true
}

const showIdCardImg = ref(false)
const checkIdCard = () => {
  if (nullPatient()) return
  showIdCardImg.value = true
}

function initSearchParam() {
  return reactive({
    current: 'alpha',
    methods: [
      {code: 'alpha', name: '拼音'},
      {code: 'code', name: '编码'},
      {code: 'name', name: '名称'},
    ],
    zyh: '',
  })
}

const openEmr = () => {
  if (nullPatient()) return
  window.open(getEmrUrl(patient.value.inpatientNo, patient.value.admissTimes, emrStateEnum.在院只读), '_blank')
}

function makeOverview(val) {
  return {
    bedNo: val.bedNo,
    inpatientNo: val.inpatientNo,
    admissTimes: val.admissTimes,
    name: val.name,
    sex: val.sex,
    medType: val.medType,
    dismissOrder: val.dismissOrder,
    mdtrtId: val.mdtrtId,
    injurySerialNo: val.injurySerialNo,
    status: val.mdtrtId || val.injurySerialNo ? 1 : 0,
  }
}

const showPsnInsuinfo = ref(false)
const showTreatmentinfos = ref(false)
const checkTreatmentParams = ref({})
const beforeGetTreatinfo = () => {
  if (nullPatient()) return
  if (!patient.value.medType) {
    ElMessage({
      message: '医疗类别不能为空！',
      type: 'warning',
      duration: 2600,
      showClose: true,
    })
    return true
  }
  checkTreatmentParams.value = {
    medType: patient.value.medType,
    patNo: patient.value.patNo,
    times: patient.value.admissTimes,
    ledgerSn: patient.value.ledgerSn,
    socialNo: patient.value.socialNo,
    name: patient.value.name,
    admdvs: patient.value.admdvs,
  }
  showPsnInsuinfo.value = true
}
const checkTreatmentinfos = (row) => {
  checkTreatmentParams.value.psnNo = row.psnNo
  checkTreatmentParams.value.begntime = getDatetime()
  checkTreatmentParams.value.insutype = row.insutype
  showPsnInsuinfo.value = false
  showTreatmentinfos.value = true
}

const childrenDepts = ['1040000','1040100', '1700015']

function printWristStrap() {
  if (nullPatient()) return
  if (childrenDepts.indexOf(patient.value.smallDept) !== -1) {
    printChildWristStrap()
  } else {
    printNormalWristStrap()
  }
}

let LODOP;
function printNormalWristStrap() {
  LODOP = getLodop();
  LODOP.PRINT_INIT('inpatient_info2')
  LODOP.SET_PRINTER_INDEX('DASCOM DL-520Z')
  LODOP.SET_PRINT_PAGESIZE(2, 0, 0, '')
  LODOP.SET_PRINT_STYLE('FontSize', 9)
  LODOP.SET_PRINT_STYLE('Bold', 1)
  LODOP.ADD_PRINT_BARCODE('7mm', '27mm', '18.5mm', '18.5mm', 'QRCode', patient.value.inpatientNo)
  LODOP.ADD_PRINT_TEXT('8mm', '45mm', '220mm', '7mm',
      `姓名：${patient.value.name} / 性别：${patient.value.sexName} / 年龄：${patient.value.age}`)
  LODOP.ADD_PRINT_TEXT('14mm', '45mm', '220mm', '7mm', `入院科室：${patient.value.smallDeptName}`)
  LODOP.ADD_PRINT_TEXT('20mm', '45mm', '220mm', '7mm', `紧急联系人：${patient.value.contactPhone}`)
  LODOP.PREVIEW()
}

function printChildWristStrap() {
  LODOP = getLodop()
  LODOP.PRINT_INIT('inpatient_info3')
  LODOP.SET_PRINTER_INDEX('DASCOM DL-520Z')
  LODOP.SET_PRINT_PAGESIZE(2, 0, 0, '')
  LODOP.SET_PRINT_STYLE('FontSize', 6)
  LODOP.SET_PRINT_STYLE('Bold', 1)
  LODOP.ADD_PRINT_BARCODE('10mm', '32mm', '15mm', '15mm', 'QRCode', patient.value.inpatientNo)
  LODOP.ADD_PRINT_TEXT('11mm', '45mm', '50mm', '3mm',
      `姓名：${patient.value.name} / 性别：${patient.value.sexName} / 年龄：${patient.value.age}`)
  LODOP.ADD_PRINT_TEXT('14.75mm', '45mm', '50mm', '3mm', `入院科室：${patient.value.smallDeptName}`)
  LODOP.ADD_PRINT_TEXT('18.5mm', '45mm', '50mm', '3mm', `紧急联系人：${patient.value.contactPhone}`)
  LODOP.PREVIEW()
}

onMounted(() => {
  initLodop()
})
</script>
