<template>
  <el-container>
    <el-header>
      <el-select v-model="medType" placeholder="医疗类别" style="width: 145px" clearable>
        <el-option v-for="item in needVerifyMedTypes" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-select v-model="statusFlag" placeholder="审核状态" style="width: 100px" clearable>
        <el-option v-for="item in statusFlags" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-select v-show="injuryMode" v-model="patient.injuryArea" placeholder="工伤参保地" style="width: 120px">
        <el-option v-for="item in injuryAreas" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-button style="margin-left: 10px" type="primary" icon="Tickets" @click="getPsnInsuinfo(1)">待遇检查</el-button>
      <el-button type="primary" icon="User" @click="checkIdCard">身份信息</el-button>
      <ReadCard :pat-no="patient.inpatientNo" biztype="01103" @success="afterReadCard" />
      <el-button type="success" icon="Check" @click="beforeHandleApply(true)">审核通过</el-button>
      <el-button type="danger" icon="Close" @click="beforeHandleApply(false)">审核不通过</el-button>
      <el-button type="primary" icon="Document" @click="getRegInfo">登记信息</el-button>
    </el-header>
    <el-main>
      <el-container>
        <el-aside width="245px">
          <el-table :height="tableHeight" :data="cptApplies" stripe highlight-current-row @row-click="handleClickAdmissApply">
            <el-table-column label="姓名" width="70">
              <template #default="scope">
                <div style="display: flex; align-items: center">
                  <img class="sex-icon" :src="scope.row.gender === 1 ? maleIcon : femaleIcon" />
                  {{ scope.row.name }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="住院号" width="65" align="center">
              <template #default="scope">
                <span v-html="getStatusFlag(scope.row.status, scope.row.patNo)"></span>
              </template>
            </el-table-column>
            <el-table-column prop="wardName" label="病房" width="110"></el-table-column>
          </el-table>
        </el-aside>
        <el-main>
          <el-tag>患者基本信息</el-tag>
          <el-descriptions :column="4" 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.socialNo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label> 姓名 </template>
              {{ patient.name }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label> 性别 </template>
              {{ patient.sex === 1 ? '男' : patient.sex === 2 ? '女' : '' }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label> 病区 </template>
              {{ patient.admissWardName }}
            </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>
              {{ patient.referPhysicianName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label> 床位 </template>
              {{ patient.bedNo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label> 入院日期 </template>
              {{ patient.admissDate }}
            </el-descriptions-item>
          </el-descriptions>
          <div style="margin-top: 8px">
            <el-tag>入院登记申请信息</el-tag>
            <el-descriptions :column="4" border>
              <el-descriptions-item>
                <template #label> 登记时间 </template>
                {{ currentApply.admissDatetime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 医疗类别 </template>
                {{ currentApply.medTypeName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 参保地区 </template>
                {{ currentApply.admdvsName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 申请人 </template>
                {{ currentApply.inputName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 申请时间 </template>
                {{ currentApply.inputDatetime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 申请理由 </template>
                {{ currentApply.inputComment }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 处理人 </template>
                {{ currentApply.handleStaffName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 处理时间 </template>
                {{ currentApply.handleDatetime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label> 处理意见 </template>
                {{ currentApply.handleComment }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div style="height: 8px"></div>
          <el-tag>医保入院诊断</el-tag>
          <el-table :data="zyInYbDiags" stripe>
            <el-table-column prop="diagNo" label="诊断序号"></el-table-column>
            <el-table-column prop="property" label="诊断属性"></el-table-column>
            <el-table-column prop="icdCode" label="诊断编码"></el-table-column>
            <el-table-column prop="icdText" label="诊断名称"></el-table-column>
            <el-table-column label="诊断类别">
              <template #default="scope">
                {{ getDiagTypeName(scope.row.diagType) }}
              </template>
            </el-table-column>
            <el-table-column prop="opDate" label="诊断时间"></el-table-column>
          </el-table>
          <Insuinfo v-if="showPsnInsuinfo" :params="checkTreatmentParams" @close="showPsnInsuinfo = false" @row-click="handleClickInsuinfo" />
          <Treatmentinfo v-if="showTreatmentinfos" :params="checkTreatmentParams" @close="showTreatmentinfos = false" />
          <Registinfo v-if="showRegisterInfo" :params="patient" @close="showRegisterInfo = false"></Registinfo>
          <IdentifyImage v-if="showIdCardImg" :pat-no="currentApply.patNo" :times="currentApply.times" @close="showIdCardImg = false"></IdentifyImage>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import { computed, onActivated, onMounted, ref } from 'vue'
import store from '@/store'
import maleIcon from '@/assets/male-icon.png'
import femaleIcon from '@/assets/female-icon.png'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDiagTypes } from '@/api/medical-insurance/si-dict'
import { checkRegisterDate } from '@/api/medical-insurance/si-query'
import { admissRegistration } from '@/api/medical-insurance/si-injury'
import { admissRegister } from '@/api/medical-insurance/si-inpatient'
import { statusFlags, needVerifyMedTypes } from '../../../data/index'
import { selectUnhandledApplies, selectPatientInfo, handleApply } from '../../../api/medical-insurance/si-admiss-apply'
import Insuinfo from '../../../components/medical-insurance/insuinfo/Index.vue'
import Treatmentinfo from '../../../components/medical-insurance/treatmentinfo/Index.vue'
import IdentifyImage from '../../../components/inpatient/IdentifyImage.vue'
import Registinfo from '../../../components/medical-insurance/registinfo/Index.vue'
import ReadCard from '@/components/medical-insurance/readcard/Index.vue'
export default {
  components: {
    Insuinfo,
    Treatmentinfo,
    IdentifyImage,
    Registinfo,
    ReadCard,
  },
  setup() {
    const patient = ref({})
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 50
    const psnBaseinfo = ref({})
    const showTreatmentinfos = ref(false)
    const showPsnInsuinfo = ref(false)
    const insuRowClickFlag = ref(null)
    const zyInYbDiags = ref([])
    const injuryinfo = ref([])
    const injuryAreas = initInjuryAreas()
    const injuryMode = computed(() => {
      return store.state.ptnt.injuryMode
    })
    const currentApply = ref({})
    const medType = ref(null)
    const statusFlag = ref('')
    const allApplies = ref([])
    const cptApplies = computed(() => {
      return allApplies.value.filter((itm) => {
        if ('' !== statusFlag.value) {
          return medType.value ? itm.medType === medType.value && itm.status === statusFlag.value : itm.status === statusFlag.value
        } else {
          return medType.value ? itm.medType === medType.value : true
        }
      })
    })

    const handleClickAdmissApply = (row) => {
      store.commit('ptnt/setInjuryMode', row.medType === '42')
      selectPatientInfo(row)
        .then((res) => {
          patient.value = res.patient
          currentApply.value = row
          zyInYbDiags.value = res.indiags
        })
        .catch(() => {
          patient.value = {}
          currentApply.value = {}
          zyInYbDiags.value = []
        })
    }

    const beforeHandleApply = (approve) => {
      if (!currentApply.value.patNo) {
        ElMessage({
          message: '请先选择患者',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      if (!approve) {
        ElMessageBox.prompt('请输入处理意见：', '审核不通过', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: null,
        })
          .then(({ value }) => {
            if (value) {
              currentApply.value.status = 2
              currentApply.value.handleComment = value
              handleApply(currentApply.value).then((res) => {
                ElMessage({
                  message: res,
                  type: 'success',
                  duration: 2500,
                  showClose: true,
                })
              })
            } else {
              ElMessage({
                message: '处理意见不能为空',
                type: 'warning',
                duration: 2500,
                showClose: true,
              })
            }
          })
          .catch(() => {
            currentApply.value.status = 0
          })
      } else {
        checkRegisterDate(patient.value.inpatientNo, patient.value.admissTimes).then(() => {
          getPsnInsuinfo(2)
        })
      }
    }

    const getPsnInsuinfo = (flag) => {
      if (!currentApply.value.patNo) {
        ElMessage({
          message: '请先选择患者',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      if (injuryMode.value) {
        checkTreatmentParams.value = patient.value
        showPsnInsuinfo.value = true
      } else {
        insuRowClickFlag.value = flag
        checkTreatmentParams.value = {
          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,
        }
        showPsnInsuinfo.value = true
      }
    }

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

    const handleClickInsuinfo = (row) => {
      if (injuryMode.value) {
        handleClickInjuryinfo(row)
      } else {
        patient.value.psnNo = row.psnNo
        if (insuRowClickFlag.value === 1) {
          chkTrtmt(row)
        } else if (insuRowClickFlag.value === 2) {
          admRgstn(row)
        }
      }
      showPsnInsuinfo.value = false
    }

    const checkTreatmentParams = ref({})
    const chkTrtmt = (row) => {
      checkTreatmentParams.value.patNo = patient.value.inpatientNo
      checkTreatmentParams.value.times = patient.value.admissTimes
      checkTreatmentParams.value.psnNo = patient.value.psnNo
      checkTreatmentParams.value.medType = patient.value.medType
      checkTreatmentParams.value.begntime = patient.value.ybRegisterDate
      checkTreatmentParams.value.insutype = row.insutype
      showPsnInsuinfo.value = false
      showTreatmentinfos.value = true
    }

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

    const admRgstn = (row) => {
      ElMessageBox.confirm('审核通过将直接进行医保入院登记，确定审核通过？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          patient.value.insutype = row.insutype
          patient.value.psnType = row.psnType
          patient.value.insuplcAdmdvs = row.insuplcAdmdvs
          patient.value.empName = row.empName
          admissRegister(patient.value).then(() => {
            currentApply.value.status = 1
            currentApply.value.handleComment = '同意办理'
            handleApply(currentApply.value).then((res) => {
              ElMessage({
                message: '审核已通过，医保入院登记成功。',
                type: 'success',
                duration: 2500,
                showClose: true,
              })
              showPsnInsuinfo.value = false
            })
          })
        })
        .catch(() => {})
    }

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

    const showIdCardImg = ref(false)
    const checkIdCard = () => {
      if (!currentApply.value.patNo) {
        ElMessage({
          message: '请先选择患者',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
      } else {
        showIdCardImg.value = true
      }
    }

    const showRegisterInfo = ref(false)
    const getRegInfo = () => {
      if (!currentApply.value.patNo) {
        ElMessage({
          message: '请先选择患者',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      showRegisterInfo.value = true
    }

    onActivated(() => {
      selectUnhandledApplies().then((res) => {
        allApplies.value = res
      })
    })

    onMounted(() => {
      getDiagTypes().then((res) => {
        diagTypes.value = res
      })
    })

    return {
      patient,
      medType,
      statusFlag,
      statusFlags,
      injuryAreas,
      zyInYbDiags,
      tableHeight,
      injuryMode,
      injuryinfo,
      maleIcon,
      femaleIcon,
      psnBaseinfo,
      showPsnInsuinfo,
      needVerifyMedTypes,
      checkTreatmentParams,
      showTreatmentinfos,
      getDiagTypeName,
      filterYesOrNo,
      getPsnInsuinfo,
      handleClickInsuinfo,
      getStatusFlag,
      cptApplies,
      currentApply,
      handleClickAdmissApply,
      showIdCardImg,
      checkIdCard,
      beforeHandleApply,
      getRegInfo,
      showRegisterInfo,
      afterReadCard,
    }
  },
}

function initInjuryAreas() {
  return [
    { code: 1, name: '长沙市' },
    { code: 4, name: '长沙县' },
    { code: 2, name: '望城县' },
    { code: 3, name: '省直' },
  ]
}

function filterYesOrNo(val) {
  if (val === '0') {
    return '否'
  } else if (val === '1') {
    return '是'
  }
  return ''
}

function getStatusFlag(status, patNo) {
  // 0：撤销-黑色,1：待审核-橙色,2：已审核-绿色,9：未通过-红色,null/-1：未提交-灰色
  switch (status) {
    case 0:
      return `<span style="color: gray">${patNo}</span>`
    case 1:
      return `<span style="color: green">${patNo}</span>`
    case 2:
      return `<span style="color: red">${patNo}</span>`
  }
}
</script>

<style scoped>
.remark {
  padding: 5px 10px;
}

.mt10 {
  margin-top: 10px;
}

.yb-tag {
  padding: 5px 0 0 20px;
}
</style>
