<template>
  <div>
    <el-button icon="Location" type="primary" @click="beforeFetchAssigninfo">定点信息</el-button>
    <el-button icon="Check" type="primary" @click="submitPatientInfo"> 保存</el-button>
    <ReadCard :pat-no="patient.inpatientNo" biztype="01103" @success="afterReadCard"/>
    <el-button icon="Top" type="success" @click="checkRegisterDatetime">医保入院登记</el-button>
    <el-button icon="Bottom" type="danger" @click="beforeCancelRegister">撤销入院登记</el-button>
    <el-button icon="Coin" type="success" @click="xiangMuLuRuRouter">项目录入</el-button>
    <generate-medicine-return-order/>
  </div>
  <div style="margin-top: 4px">
    <el-tag type="info">病人基本信息</el-tag>
    <div style="height: 4px"></div>
    <el-descriptions :column="3" border>
      <el-descriptions-item>
        <template #label> 住院号</template>
        {{ patient.inpatientNo }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 住院次数</template>
        {{ patient.admissTimes }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 出生日期</template>
        {{ patient.birthDate }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>入院日期</template>
        {{ patient.admissDate }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 病区</template>
        {{ patient.admissWardName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 入院诊断</template>
        <div style="width: 180px" class="ellipsis-text" :title="patient.admissDiagStr">
          {{ patient.admissDiagStr }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 小科室</template>
        {{ patient.smallDeptName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 入院医生</template>
        {{ patient.admissPhysicianName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>身份证号</template>
        <el-input v-model="patient.socialNo" style="width: 180px" clearable></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 姓名</template>
        <el-input v-model="patient.name" style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 性别</template>
        <el-select v-model="patient.sex" placeholder=" " style="width: 180px">
          <el-option v-for="item in sexes" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 联系电话</template>
        <el-input v-model="patient.homeTel" style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 管床医生</template>
        <el-input v-model="patient.referPhysicianName" readonly @click="searchPhysician(1)"
                  style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 责任护士</template>
        <el-input v-model="patient.dutyNurseName" readonly @click="searchPhysician(2)"
                  style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 国籍</template>
        <el-select v-model="patient.country" style="width: 180px" :filterable="true">
          <el-option v-for="item in countries" :key="item.code" :label="item.name" :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 民族</template>
        <el-select v-model="patient.nation" style="width: 180px" :filterable="true">
          <el-option v-for="item in nations" :key="item.code" :label="item.name" :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 联系人姓名</template>
        <el-input v-model="patient.contactName" style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 联系人关系</template>
        <el-select v-model="patient.contactRelation" style="width: 180px" :filterable="true">
          <el-option v-for="item in relations" :key="item.code" :label="item.name" :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 联系人地址</template>
        <el-input v-model="patient.contactAddrName" style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 联系人电话</template>
        <el-input v-model="patient.contactPhone" style="width: 180px"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 登记日期</template>
        <el-date-picker v-model="patient.ybRegisterDate" placeholder="选择日期时间" style="width: 180px"
                        type="datetime"
                        @change="formatYbRegisterDate"></el-date-picker>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 参保地区</template>
        <el-select v-if="injuryMode" v-model="patient.injuryArea" placeholder="工伤参保地" size="small">
          <el-option v-for="item in injuryAreas" :key="item.code" :label="item.name" :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
        <el-select v-else v-model="patient.admdvs" :clearable="true" :filterable="true" placeholder="请选择"
                   style="width: 180px">
          <el-option v-for="item in admdvses" :key="item.code" :label="item.name" :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 医疗类别</template>
        <el-select v-model="patient.medType" :clearable="true" placeholder="请选择" @change="handleSelectMedType"
                   style="width: 180px">
          <el-option v-for="item in medTypes" :key="item.code" :disabled="item.disabled" :label="item.name"
                     :value="item.code">
            <span style="color: #8492a6; font-size: 12px">{{ item.code }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-descriptions-item>
      <span v-if="patient.medType === '52'">
          <el-descriptions-item>
            <template #label>生育类别</template>
              <el-select v-model="patient.matnType" placeholder="请选择" style="width: 180px">
              <el-option v-for="item in matnTypes" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>是否晚育</template>
            <el-select v-model="patient.latechbFlag" placeholder="请选择" style="width: 180px">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>是否早产</template>
            <el-select v-model="patient.pretFlag" placeholder="请选择" style="width: 180px">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-descriptions-item>
        </span>
      <el-descriptions-item v-if="patient.medType === '2102' || patient.medType === '52'">
        <template #label>患者病种</template>
        <el-input v-model="patient.diseName" readonly style="width: 180px" @click="openDiseInput"></el-input>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>就诊人群类型</template>
        <el-select v-model="expContent.MDTRT_GRP_TYPE" placeholder="请选择" style="width: 180px">
          <el-option v-for="item in mdtrtGrpTypes" :key="item.code" :label="item.name" :value="item.code"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>外伤标志</template>
        <el-select v-model="expContent.TRUM_FLAG" placeholder="请选择" style="width: 180px">
          <el-option label="否" value="0"></el-option>
          <el-option label="是" value="1"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>涉及第三方标志</template>
        <el-select v-model="expContent.REL_TTP_FLAG" placeholder="请选择" style="width: 180px">
          <el-option label="否" value="0"></el-option>
          <el-option label="是" value="1"></el-option>
        </el-select>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>住院类型</template>
        <el-select v-model="expContent.IPT_TYPE" placeholder="请选择" style="width: 180px">
          <el-option label="普通住院" value="1"></el-option>
          <el-option label="急诊或者请求住院" value="2"></el-option>
          <el-option label="转院住院" value="3"></el-option>
        </el-select>
      </el-descriptions-item>
    </el-descriptions>

    <div style="margin-top: 16px">
      <el-tag type="info"> 医保入院诊断（*自费患者无需填写*）</el-tag>
      <el-button circle icon="Plus" title="添加入院诊断" type="primary" @click="openDiagDialog"></el-button>
      <el-button :disabled="zyInYbDiags.length === 0" circle icon="Check" title="保存入院诊断" type="success"
                 @click="saveYbDiags"></el-button>
    </div>
    <div style="margin-top: 8px">
      <el-table :data="zyInYbDiags" height="160" stripe>
        <el-table-column label="诊断序号" prop="diagNo"></el-table-column>
        <el-table-column label="诊断属性" prop="property"></el-table-column>
        <el-table-column label="诊断编码" prop="icdCode"></el-table-column>
        <el-table-column label="诊断名称" prop="icdText"></el-table-column>
        <el-table-column label="诊断类别">
          <template #default="scope">
            {{ getDiagTypeName(scope.row.diagType) }}
          </template>
        </el-table-column>
        <el-table-column label="诊断时间" prop="opDate"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button circle icon="Delete" type="danger" @click="deleteYbDiag(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Assignmentinfo v-if="showAssigninfo" :admdvs="patient.admdvs" :social-no="patient.socialNo"
                    @close="showAssigninfo = false"/>
  </div>
  <el-dialog v-model="openXmlr"
             :fullscreen="true"
             destroy-on-close
             title="项目录入">
    <Xmlr @closeXmlr="openXmlr = false"/>
  </el-dialog>
  <el-dialog v-model="showSearchSpecialDiag" :close-on-click-modal="false" title="医保患者病种录入" width="60%">
    <div style="margin: -16px 0 4px 2px; height: 22px; line-height: 22px">
      患者当前病种：
      <span style="padding: 2px 6px; background: #005279; border-radius: 4px; color: white">
          {{ patient.diseCode ? (patient.diseCode + ' | ' + patient.diseName) : '无' }}
        </span>
    </div>
    <el-tag>可选病种</el-tag>&nbsp;&nbsp;
    <el-input v-model="specialDiagName" clearable placeholder="请输入病种名称" style="width: 260px"></el-input>
    <el-table :data="cptSpecialDiags.slice((currentPage - 1) * 10, currentPage * 10)" height="400"
              highlight-current-row stripe>
      <el-table-column label="病种编码" prop="newCode"></el-table-column>
      <el-table-column label="病种名称" prop="newName"></el-table-column>
      <el-table-column label="限额方式" prop="limitWay"></el-table-column>
      <el-table-column label="限额额度计算方式" prop="limitAmountCalculateWay"></el-table-column>
      <el-table-column label="疾病限额" prop="limitAmount"></el-table-column>
      <el-table-column>
        <template #default="scope">
          <el-button type="primary" @click="addDiseInfo(scope.row)">选择此病种</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :current-page="currentPage"
        :page-size="10"
        :total="cptSpecialDiags.length"
        :layout="'total, prev, pager, next, jumper'"
        style="margin-top: 5px"
        @current-change="handleCurrentChange"
    ></el-pagination>
  </el-dialog>

  <el-dialog v-model="showAdmissApplyForm" title="医保入院登记申请" width="500px">
    <div style="margin-bottom: 20px">
      登记时间：
      <el-date-picker v-model="admissApply.admissDatetime" placeholder="请选择医保登记开始时间"
                      type="datetime"></el-date-picker>
    </div>
    <el-input v-model="admissApply.inputComment" placeholder="请输入申请理由" type="textarea"></el-input>
    <div style="width: 450px; text-align: right; margin-top: 30px">
      <el-button icon="Close" type="info" @click="cancelAdmissApply">取消</el-button>
      <el-button icon="Check" type="success" @click="confirmAdmissApply">提交</el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="showPsnInsuinfo" title="人员信息" width="65%">
    <el-tag>{{ injuryMode ? '工伤信息' : '参保信息' }}</el-tag>
    <div v-if="injuryMode">
      <el-table :data="injuryinfo" height="180" stripe @row-click="handleClickInjuryinfo">
        <el-table-column label="电脑号" prop="indiId"></el-table-column>
        <el-table-column label="工伤个人业务序号" prop="serialPers"></el-table-column>
        <el-table-column label="工伤认定号" prop="identifyCode"></el-table-column>
        <el-table-column label="认定申请时间" prop="identyDate"></el-table-column>
        <el-table-column label="受伤部位" prop="injuryPart"></el-table-column>
        <el-table-column label="报告时间" prop="reportDate"></el-table-column>
        <el-table-column label="事故发生时间" prop="accidentDate"></el-table-column>
        <el-table-column label="事故详细情况" prop="accidentDetail"></el-table-column>
      </el-table>
    </div>
    <div v-else>
      <el-table :data="psnBaseinfo.insuinfo" height="180" stripe @row-click="handleClickInsuinfo">
        <el-table-column label="余额" prop="balc"></el-table-column>
        <el-table-column label="险种类型" prop="insutypeName"></el-table-column>
        <el-table-column label="人员类别" prop="psnTypeName"></el-table-column>
        <el-table-column label="参保状态" prop="psnInsuStasName"></el-table-column>
        <el-table-column label="个人参保日期" prop="psnInsuDate"></el-table-column>
        <el-table-column label="暂停参保日期" prop="pausInsuDate"></el-table-column>
        <el-table-column label="公务员标志" prop="cvlservFlagName"></el-table-column>
        <el-table-column label="参保地医保区划" prop="insuplcAdmdvs"></el-table-column>
        <el-table-column label="参保地名称" prop="insuplcAdmdvsName"></el-table-column>
        <el-table-column label="单位名称" prop="empName"></el-table-column>
      </el-table>
      <div style="height: 16px"></div>
      <el-tag>身份信息</el-tag>
      <el-table :data="psnBaseinfo.idetinfo" height="180" stripe>
        <el-table-column label="人员身份类别" prop="psnIdetTypeName"></el-table-column>
        <el-table-column label="人员类别等级" prop="psnTypeLv"></el-table-column>
        <el-table-column label="备注" prop="memo"></el-table-column>
        <el-table-column label="开始时间" prop="begntime"></el-table-column>
        <el-table-column label="结束时间" prop="endtime"></el-table-column>
      </el-table>
    </div>
  </el-dialog>
  <Search
      v-if="searchParams.showSearch"
      :med-type="patient.medType"
      :target="searchParams.target"
      :title="searchParams.title"
      @close="searchParams.showSearch = false"
      @click-item="handleClickSearchItem"
  />
</template>

<script setup>
import store from '@/store'
import {computed, onActivated, onDeactivated, onMounted, reactive, ref, watchEffect} from 'vue'
import {getZyInYbDiags, saveZyInYbDiags, submitSiPatientInfo} from '@/api/inpatient/patient'
import {getAllSpecialDiags} from '@/api/inpatient/dictionary'
import {
  fetchCountryDictionary,
  fetchNationDictionary,
  fetchRelationDictionary
} from '@/api/dictionary/fetch-dictionaries'
import {admdvses, diagTypes, sexes} from '@/data'
import {nullPatient} from '@/utils/validate'
import {ElMessage, ElMessageBox} from 'element-plus'
import {admissRegister, revokeAdmission} from '@/api/medical-insurance/si-inpatient'
import {formatDatetime, getDatetime} from '@/utils/date'
import {getGreatestRole} from '@/utils/permission'
import {clone} from '@/utils/clone'
import {getMatnTypes, getMedTypesByFlag} from '@/api/medical-insurance/si-dict'
import {checkRegisterDate, obtainBasicPersonInfo} from '@/api/medical-insurance/si-query'
import {admissRegistration, cancelInjuryRegister, getPersonBaseinfo} from '@/api/medical-insurance/si-injury'
import {selectAdmissApply, submitAdmissApply} from '@/api/medical-insurance/si-admiss-apply'
import {baseinfo} from '@/data/inpatient'
import Xmlr from '@/components/inpatient/XiangMuLuRu.vue'
import Assignmentinfo from '@/components/medical-insurance/assigninfo/Index.vue'
import Search from '@/components/search/Index.vue'
import ReadCard from '@/components/medical-insurance/readcard/Index.vue'
import GenerateMedicineReturnOrder
  from "@/components/medical-insurance/medicine-return-order/GenerateMedicineReturnOrder.vue";


const greatestRole = getGreatestRole()
const patient = computed(() => {
  const patientInfo = baseinfo()
  const pContent = patientInfo.expContent ? JSON.parse(patientInfo.expContent) : {}
  expContent.MDTRT_GRP_TYPE = pContent.MDTRT_GRP_TYPE
  expContent.TRUM_FLAG = pContent.TRUM_FLAG
  expContent.REL_TTP_FLAG = pContent.REL_TTP_FLAG
  expContent.IPT_TYPE = pContent.IPT_TYPE
  return patientInfo
})
const fetchZyYbDiags = () => {
  if (nullPatient()) {
    return
  }
  getZyInYbDiags(patient.value.inpatientNo, patient.value.admissTimes).then((res) => {
    zyInYbDiags.value = res
  })
}

const actived = ref(false)

onActivated(() => {
  actived.value = true
})

onDeactivated(() => {
  actived.value = false
})

const currentPatNo = ref(null)
watchEffect(() => {
  if (actived.value) {
    if (patient.value.inpatientNo && patient.value.inpatientNo !== currentPatNo.value) {
      currentPatNo.value = patient.value.inpatientNo
      fetchZyYbDiags()
    }
  }
})

const searchParams = reactive({
  showSearch: false,
  title: '',
  target: '',
})

const medTypes = ref([])
const countries = ref([])
const nations = ref([])
const relations = ref([])
const diagItem = ref({})
const showSearchSpecialDiag = ref(false)
const zyInYbDiags = ref([])
const specialDiags = ref([])
const specialDiagName = ref('')
const cptSpecialDiags = computed(() => {
  return specialDiags.value.filter((item) => {
    return (item.oldName + '' + item.newName).indexOf(specialDiagName.value) !== -1
  })
})
const matnTypes = ref([])

const injuryAreas = [
  {code: 1, name: '长沙市'},
  {code: 4, name: '长沙县'},
  {code: 2, name: '望城县'},
  {code: 3, name: '省直'},
]

const expContent = reactive({
  MDTRT_GRP_TYPE: '',
  TRUM_FLAG: '',
  REL_TTP_FLAG: '',
  IPT_TYPE: ''
})
const mdtrtGrpTypes = [
  {code: '', name: '普通患者'},
  {code: '1', name: '新冠肺炎确诊患者'},
  {code: '2', name: '其他国家突发公共事件'},
  {code: '3', name: '新冠肺炎疑似患者'},
  {code: '4', name: '无症状感染者'},
]

const openDiagDialog = () => {
  if (nullPatient()) {
    return
  }
  if (!patient.value.medType) {
    ElMessage({
      message: '请先选择医疗类别！',
      type: 'warning',
      duration: 2500,
      showClose: true,
    })
    return
  }
  searchParams.title = '医保入院诊断'
  searchParams.target = injuryMode.value ? 'injurydiag' : 'diag'
  searchParams.showSearch = true
}

const openDiseInput = () => {
  getAllSpecialDiags(patient.value.medType).then((res) => {
    specialDiags.value = res
    showSearchSpecialDiag.value = true
  })
};

const addDiseInfo = (row) => {
  patient.value.diseCode = row.newCode
  patient.value.diseName = row.newName
  showSearchSpecialDiag.value = false
}

const getDiagTypeName = (val) => {
  for (let i = 0; i < diagTypes.length; i++) {
    if (diagTypes[i].code === val) {
      return diagTypes[i].name
    }
  }
}

const deleteYbDiag = (index) => {
  zyInYbDiags.value.splice(index, 1)
  for (let i = 0; i < zyInYbDiags.value.length; i++) {
    const element = zyInYbDiags.value[i]
    element.diagNo = i + 1
    if (i === 0) {
      element.property = '主要诊断'
    }
  }
}

const saveYbDiags = () => {
  const param = {
    inpatientNo: patient.value.inpatientNo,
    admissTimes: patient.value.admissTimes,
    diags: zyInYbDiags.value,
  }
  saveZyInYbDiags(param).then(() => {
    ElMessage({
      message: '医保入院诊断保存成功。',
      type: 'success',
      duration: 2500,
      showClose: true,
    })
    showSearchSpecialDiag.value = false
  })
}

const handleSelectMedType = (val) => {
  store.commit('ptnt/setInjuryMode', val === '42')
}

const submitPatientInfo = () => {
  if (nullPatient()) {
    return
  }
  ElMessageBox.confirm('确定保存患者信息？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    patient.value.expContent = JSON.stringify(expContent)
    submitSiPatientInfo({patient: patient.value, diags: zyInYbDiags.value}).then(() => {
      ElMessage({
        message: '保存患者信息成功。',
        type: 'success',
        duration: 2500,
        showClose: true,
      })
    })
  })
}

const searchPhysician = (flag) => {
  switch (flag) {
    case 1:
      searchParams.title = '管床医生'
      break
    case 2:
      searchParams.title = '责任护士'
      break
  }
  searchParams.target = 'physician'
  searchParams.showSearch = true
}

const handleClickSearchItem = (item) => {
  if (searchParams.target === 'physician') {
    switch (searchParams.title) {
      case '管床医生':
        patient.value.referPhysician = item.code
        patient.value.referPhysicianName = item.name
        break
      case '责任护士':
        patient.value.dutyNurse = item.code
        patient.value.dutyNurseName = item.name
        break
    }
  } else if (searchParams.target === 'diag' || searchParams.target === 'injurydiag') {
    diagItem.value.icdCode = item.icdCode
    diagItem.value.icdText = item.icdText
    diagItem.value.diagType = item.diagType
    diagItem.value.property = zyInYbDiags.value.length === 0 ? '主要诊断' : '次要诊断'
    diagItem.value.diagNo = zyInYbDiags.value.length + 1
    diagItem.value.opDate = getDatetime()
    zyInYbDiags.value.push(clone(diagItem.value))
  }
  searchParams.showSearch = false
}

const injuryMode = computed(() => {
  return store.state.ptnt.injuryMode
})

const afterReadCard = (result) => {
  patient.value.mdtrtCertType = result.mdtrtCertType
  patient.value.readCardResult = result.readCardResult
  patient.value.readCardBizType = result.readCardBizType
}

const formatYbRegisterDate = () => {
  patient.value.ybRegisterDate = formatDatetime(patient.value.ybRegisterDate)
}

const admissApply = ref({})
const showAdmissApplyForm = ref(false)
const checkRegisterDatetime = () => {
  if (nullPatient()) {
    return
  }
  patient.value.expContent = JSON.stringify(expContent)
  submitSiPatientInfo({patient: patient.value, diags: zyInYbDiags.value}).then(() => {
    checkRegisterDate(patient.value.inpatientNo, patient.value.admissTimes).then(() => {
      selectAdmissApply(patient.value).then((res) => {
        if (null === res.status) {
          admissApply.value.patNo = patient.value.inpatientNo
          admissApply.value.times = patient.value.admissTimes
          admissApply.value.ledgerSn = patient.value.ledgerSn
          admissApply.value.admissDatetime = patient.value.ybRegisterDate
          admissApply.value.inputComment = '人证相符。'
          showAdmissApplyForm.value = true
        } else {
          switch (res.status) {
            case 0:
              ElMessageBox.alert('医保科尚未处理此患者的医保入院申请，请耐心等候或者致电医保科（内线电话：2102）。', '提示', {
                type: 'warning',
              })
              break
            case 1:
              getPsnInsuinfo()
              break
            case 2:
              ElMessageBox.confirm('医保科驳回了此患者的医保入院申请，驳回意见为【' + res.handleComment + '】', '提示', {
                type: 'error',
                distinguishCancelAndClose: true,
                confirmButtonText: '我知道了',
                cancelButtonText: '重新提交',
                showCancelButton: true,
              }).catch((action) => {
                if (action === 'cancel') {
                  admissApply.value.patNo = patient.value.inpatientNo
                  admissApply.value.times = patient.value.admissTimes
                  admissApply.value.ledgerSn = patient.value.ledgerSn
                  admissApply.value.admissDatetime = patient.value.ybRegisterDate
                  showAdmissApplyForm.value = true
                }
              })
              break
          }
        }
      })
    })
  })
}

const cancelAdmissApply = () => {
  admissApply.value = {}
  showAdmissApplyForm.value = false
}

const confirmAdmissApply = () => {
  if (!admissApply.value.admissDatetime) {
    ElMessage({
      message: '医保入院登记时间不能为空！',
      type: 'error',
      duration: 2500,
      showClose: true,
    })
    return
  }
  if (!admissApply.value.inputComment) {
    ElMessage({
      message: '申请理由不能为空！',
      type: 'error',
      duration: 2500,
      showClose: true,
    })
    return
  }
  admissApply.value.admissDatetime = formatDatetime(admissApply.value.admissDatetime)
  ElMessageBox.confirm('是否确认提交入院登记申请？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
      .then(() => {
        submitAdmissApply(admissApply.value).then((res) => {
          ElMessage({
            message: res,
            type: 'success',
            duration: 2500,
            showClose: true,
          })
          showAdmissApplyForm.value = false
        })
      })
      .catch(() => {
      })
}

const psnBaseinfo = ref({})
const showPsnInsuinfo = ref(false)
const injuryinfo = ref([])
const getPsnInsuinfo = () => {
  if (nullPatient()) {
    return
  }
  if (!patient.value.medType) {
    ElMessage({
      message: '请选择患者的医疗类别！',
      type: 'warning',
      showClose: true,
    })
    return
  }
  if (injuryMode.value) {
    getPersonBaseinfo(patient.value).then((res) => {
      injuryinfo.value = res
      showPsnInsuinfo.value = true
    })
  } else {
    const param = {
      medType: patient.value.medType,
      patNo: patient.value.inpatientNo,
      times: patient.value.admissTimes,
      ledgerSn: patient.value.ledgerSn,
      socialNo: patient.value.socialNo,
      name: patient.value.name,
      admdvs: patient.value.admdvs,
      needSaving: 1,
    }
    obtainBasicPersonInfo(param).then((res) => {
      patient.value.psnNo = res.psnNo
      psnBaseinfo.value = res
      showPsnInsuinfo.value = true
    })
  }
}

const handleClickInjuryinfo = (row) => {
  ElMessageBox.confirm('确定进行工伤入院登记？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    const param = {
      baseinfo: patient.value,
      injuryinfo: row,
    }
    admissRegistration(param).then((res) => {
      ElMessage({
        message: '审核已通过，医保入院登记成功。',
        type: 'success',
        duration: 2500,
        showClose: true,
      })
      showPsnInsuinfo.value = false
    })
  }).catch(() => {
  })
}

const handleClickInsuinfo = (row) => {
  ElMessageBox.confirm('确定进行医保入院登记？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    patient.value.balc = row.balc
    patient.value.insutype = row.insutype
    patient.value.psnType = row.psnType
    patient.value.insuplcAdmdvs = row.insuplcAdmdvs
    patient.value.empName = row.empName
    admissRegister(patient.value).then(() => {
      ElMessage({
        message: '医保入院登记成功。',
        type: 'success',
        duration: 2500,
        showClose: true,
      })
      showPsnInsuinfo.value = false
    })
  }).catch(() => {
  })
}

const beforeCancelRegister = () => {
  if (nullPatient()) return
  ElMessageBox.prompt('请输入撤销入院登记的原因：', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(({value}) => {
    if (!value) {
      ElMessage({
        message: '撤销入院登记的原因不能为空！',
        type: 'warning',
        duration: 2500,
        showClose: true,
      })
      return
    }
    ElMessageBox.confirm('撤销医保入院登记的原因为【' + value + '】确定撤销？', '提示', {
      type: 'warning',
    }).then(() => {
      patient.value.revokeRemark = value
      if (injuryMode.value) {
        cancelInjuryRegister(patient.value).then(() => {
          ElMessageBox.alert('撤销入院登记成功。', '提示', {
            type: 'success',
          })
        })
      } else {
        revokeAdmission(patient.value).then(() => {
          ElMessageBox.alert('撤销入院登记成功。', '提示', {
            type: 'success',
          })
        })
      }
    })
  }).catch(() => {
  })
}

const showAssigninfo = ref(false)
const beforeFetchAssigninfo = () => {
  if (nullPatient()) {
    return
  }
  if (!patient.value.socialNo) {
    ElMessage({
      message: '患者身份证不能为空！',
      type: 'warning',
      duration: 2500,
      showClose: true,
    })
    return
  }
  if (!patient.value.admdvs) {
    ElMessage({
      message: '患者参保地不能为空！',
      type: 'warning',
      duration: 2500,
      showClose: true,
    })
    return
  }
  showAssigninfo.value = true
}

// 项目录入
const openXmlr = ref(false)
const xiangMuLuRuRouter = () => {
  openXmlr.value = true
}

const currentPage = ref(1)
const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(() => {
  getMedTypesByFlag('hospitalization').then((res) => {
    medTypes.value = res
  })
  fetchCountryDictionary().then((res) => {
    countries.value = res
  })
  fetchNationDictionary().then((res) => {
    nations.value = res
  })
  fetchRelationDictionary().then((res) => {
    relations.value = res
  })
  getMatnTypes().then((res) => {
    matnTypes.value = res
  })
})
</script>

<style scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.el-collapse-item__content {
  padding-bottom: 0;
}

.el-collapse-item__header {
  height: 30px;
  line-height: 30px;
}

.el-collapse-item__header,
.el-collapse-item__wrap {
  background-color: inherit;
}

.el-autocomplete-suggestion li {
  line-height: normal !important;
}
</style>
