<template>
  <el-container>
    <el-header height="36px" style="margin-top: 8px">
      <el-select v-model="ward.current" style="width: 120px" @change="fetchOverviews">
        <el-option v-for="item in ward.wards" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-select v-model="currentMedType" style="width: 110px">
        <el-option v-for="item in medTypes" :key="item.code" :value="item.code" :label="item.name" :disabled="item.disabled"></el-option>
      </el-select>
      <el-select v-if="isYbVerifyPage" v-model="statusFlag" style="width: 90px">
        <el-option v-for="item in statusFlags" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <span v-if="!isYbVerifyPage">
        <span>&nbsp;&nbsp;查询方式：</span>
        <el-select v-model="search.current" style="width: 70px" @change="handleSelectSearchMehtod">
          <el-option v-for="item in search.methods" :key="item.code" :value="item.code" :label="item.name"></el-option>
        </el-select>
      </span>
      <span v-if="permission < 10">
        &nbsp;
        <el-input v-model="search.zyh" style="width: 100px" clearable @keyup.enter="searchPatient" placeholder="住院号"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchPatient">检索</el-button>
      </span>
      &nbsp;&nbsp;
      <el-popover placement="bottom" width="400" trigger="click">
        <template #reference>
          <el-button type="primary" icon="el-icon-postcard" @click="checkIdInfo">身份信息</el-button>
        </template>
        <el-tag type="info">身份证</el-tag>
        <el-table :data="identityFiles.idCard" @row-click="handleClickIdCard">
          <el-table-column width="50" property="itemNo" label="序号"></el-table-column>
          <el-table-column width="70" property="inpatientNo" label="住院号"></el-table-column>
          <el-table-column width="50" property="admissTimes" label="次数"></el-table-column>
          <el-table-column width="160" property="expirestart" label="证件有效期"></el-table-column>
          <el-table-column width="150" property="agency" label="发证机关"></el-table-column>
        </el-table>
        <div style="height: 20px"></div>
        <el-tag type="info">扫描件</el-tag>
        <el-table :data="identityFiles.scanFile" @row-click="handleClickIdCard">
          <el-table-column width="60" property="itemNo" label="序号"></el-table-column>
          <el-table-column width="100" property="inpatientNo" label="住院号"></el-table-column>
          <el-table-column width="100" property="admissTimes" label="住院次数"></el-table-column>
        </el-table>
      </el-popover>
      <el-button v-if="!isYbVerifyPage" type="primary" icon="el-icon-download" @click="downloadReadCard" style="margin-left: 10px"> 下载读卡程序 </el-button>
      <el-button style="margin-left: 10px" type="success" icon="el-icon-document" @click="getRegInfo">查询登记信息 </el-button>
      <el-button style="margin-left: 10px" type="danger" icon="el-icon-magic-stick" @click="toEmpiView">患者360视图 </el-button>
    </el-header>
    <el-container>
      <el-aside width="260px" style="background-color: white">
        <el-table
          :data="cptOverviews.slice((currentPage - 1) * 15, currentPage * 15)"
          stripe
          :height="tableHieght"
          highlight-current-row
          @row-click="handleClickOverview"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="isUploadPage" type="selection" width="20"></el-table-column>
          <el-table-column prop="bedNo" label="床" width="30"></el-table-column>
          <el-table-column label="姓名" width="70">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <img class="sex-icon" :src="scope.row.sex === 1 ? maleIcon : femaleIcon" />
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="inpatientNo" label="住院号" width="65"></el-table-column>
          <el-table-column label="次数" width="45">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                {{ scope.row.admissTimes }}&nbsp;
                <img v-if="scope.row.dismissOrder > 0" class="sex-icon" :src="dismissIcon" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="45" align="center">
            <template #default="scope">
              <span v-html="getStatusFlag(scope.row.status)"></span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination small :hide-on-single-page="false" :page-size="15" layout="prev, pager, next" @current-change="handleCurrentPageChange" :total="cptOverviews.length">
        </el-pagination>
      </el-aside>
      <el-main>
        <div class="router-parent">
          <router-view v-slot="{ Component }">
            <transition name="fade-transform" mode="out-in">
              <keep-alive>
                <component :is="Component" />
              </keep-alive>
            </transition>
          </router-view>
        </div>
      </el-main>
    </el-container>
    <el-dialog v-model="showRegisterInfo" width="60%">
      <div v-if="injuryMode">
        <el-descriptions title="工伤患者在院信息" :column="3" size="small" border>
          <el-descriptions-item>
            <template #label> 姓名 </template>
            {{ registerInfo.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 住院号 </template>
            {{ registerInfo.patient_id }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 个人电脑号 </template>
            {{ registerInfo.indi_id }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 性别 </template>
            {{ cptSex(registerInfo.sex) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 身份证 </template>
            {{ registerInfo.idcard }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 出生日期 </template>
            {{ registerInfo.birthday }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 医疗类别 </template>
            {{ registerInfo.treatment_name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 入院科室 </template>
            {{ registerInfo.out_dept_name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 入院病房 </template>
            {{ registerInfo.area_name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 诊断编码 </template>
            {{ registerInfo.in_diagnose }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 诊断名称 </template>
            {{ registerInfo.in_disease_name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 就诊登记号 </template>
            {{ registerInfo.serial_no }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 工伤业务序号 </template>
            {{ registerInfo.serial_bo_no }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 入院登记时间 </template>
            {{ registerInfo.reg_date }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 单位名称 </template>
            {{ registerInfo.corp_name }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else>
        <el-descriptions title="患者医保在院信息" :column="3" size="small" border>
          <el-descriptions-item>
            <template #label> 姓名 </template>
            {{ registerInfo.psnName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 住院号 </template>
            {{ registerInfo.iptOtpNo }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 性别 </template>
            {{ cptSex(registerInfo.gend) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 证件类型 </template>
            {{ cptPsnCertType(registerInfo.psnCertType) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 证件号码 </template>
            {{ registerInfo.certno }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 出生日期 </template>
            {{ registerInfo.brdy }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 险种类型 </template>
            {{ cptInsutype(registerInfo.insutype) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 医疗类别 </template>
            {{ cptMedType(registerInfo.medType) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 异地标志 </template>
            {{ cptYesOrNo(registerInfo.outFlag) }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 开始日期 </template>
            {{ registerInfo.begndate }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 就诊ID </template>
            {{ registerInfo.mdtrtId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label> 人员编号 </template>
            {{ registerInfo.psnNo }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import store from '@/store'
import maleIcon from '@/assets/male-icon.png'
import femaleIcon from '@/assets/female-icon.png'
import dismissIcon from '@/assets/dismiss-icon.png'
import { getOverView, getPatientInfo, getIdCardInfo, getEmpiViewUrl } from '@/api/yibao/patient'
import { statusFlags, medTypes } from '@/data/index'
import { nullPatient } from '@/utils/validate'
import { getGreatestRole } from '@/utils/permission'
import { getWards } from '@/api/login'
import { queryInHospitalPatientsInfo } from '@/api/medical-insurance/si-query'
import { cptSex, cptPsnCertType, cptInsutype, cptMedType, cptYesOrNo } from '@/utils/computed'
import { baseinfo, setBaseinfo } from '@/data/inpatient'
import { getInjuryRegisterInfo } from '@/api/medical-insurance/si-injury'
export default {
  setup() {
    const ward = reactive({
      current: '',
      wards: [],
    })
    const search = initSearchParam()
    const tableHieght = store.state.app.windowSize.h - 75
    const permission = getGreatestRole()
    const handleSelectSearchMehtod = (val) => {
      store.commit('ptnt/setSearchMethod', val)
    }
    const patient = computed(() => {
      return baseinfo()
    })
    const isYbVerifyPage = computed(() => {
      return store.state.app.currentPageName === 'medInsVerification'
    })
    const isUploadPage = computed(() => {
      return store.state.app.currentPageName === 'inHospFeeUpload'
    })
    const statusFlag = ref('1')
    const overviews = ref([])
    const fetchOverviews = () => {
      store.commit('user/wardChange', ward.current)
      getOverView(ward.current).then((res) => {
        overviews.value = res
      })
    }
    const cptOverviews = computed(() => {
      if (isYbVerifyPage.value) {
        if (currentMedType.value === '00') {
          return overviews.value.filter((item) => {
            return statusFlag.value === '0' ? true : item.status === statusFlag.value
          })
        }
        return overviews.value.filter((item) => {
          if (statusFlag.value === '0') {
            return item.medType === currentMedType.value
          }
          return item.medType === currentMedType.value && item.status === statusFlag.value
        })
      } else {
        if (currentMedType.value === '00') {
          return overviews.value
        }
        return overviews.value.filter((item) => {
          return item.medType === currentMedType.value
        })
      }
    })
    const handleClickOverview = (row) => {
      store.commit('ptnt/setOverview', row)
      getPatientInfo(row.inpatientNo).then((res) => {
        setBaseinfo(res)
      })
    }

    const searchPatient = () => {
      if (!search.zyh) {
        fetchOverviews()
      } else {
        if (permission < 10) {
          overviews.value = []
          store.commit('ptnt/setBaseinfo', { totalCharge: '0.00', chargeYb: '0.00' })
          getPatientInfo(search.zyh).then((res) => {
            ward.current = res.admissWard
            store.commit('user/wardChange', ward.current)
            store.commit('ptnt/setCurrentMedType', res.medType)
            setBaseinfo(res)
            overviews.value.push(makeOverview(res))
          })
        }
      }
    }

    const currentMedType = computed({
      get: () => {
        return store.state.ptnt.currentMedType
      },
      set: (val) => {
        store.commit('ptnt/setCurrentMedType', val)
        store.commit('ptnt/setBaseinfo', { totalCharge: '0.00', chargeYb: '0.00' })
      },
    })

    const handleSelectionChange = (val) => {
      store.commit('SET_SELECTIONS', val)
    }

    const injuryMode = computed(() => {
      return store.state.ptnt.injuryMode
    })
    const registerInfo = ref({})
    const showRegisterInfo = ref(false)

    const getRegInfo = () => {
      if (nullPatient()) return
      if (injuryMode.value) {
        getInjuryRegisterInfo(patient.value).then((res) => {
          registerInfo.value = res
          showRegisterInfo.value = true
        })
      } else {
        const param = {
          patNo: patient.value.inpatientNo,
          times: patient.value.admissTimes,
          ledgerSn: patient.value.ledgerSn,
          begntime: patient.value.admissDate,
        }
        queryInHospitalPatientsInfo(param).then((res) => {
          registerInfo.value = res[0]
          showRegisterInfo.value = true
        })
      }
    }

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

    const identityFiles = initIdentityFiles()

    const checkIdInfo = () => {
      if (patient.value.inpatientNo) {
        getIdCardInfo(patient.value.inpatientNo, patient.value.admissTimes).then((res) => {
          identityFiles.idCard = res.idCard
          identityFiles.scanFile = res.scanFile
        })
      }
    }
    const handleClickIdCard = (val) => {
      let img = '<img style="width: 390px; height: 210px" src="data:image/png;base64,' + val.fileSfz + '">'
      ElMessageBox.alert(img, '身份信息', {
        dangerouslyUseHTMLString: true,
      })
    }

    const toEmpiView = () => {
      if (nullPatient()) return
      getEmpiViewUrl(patient.value.inpatientNo).then((res) => {
        window.open(res, '_blank')
      })
    }

    onMounted(() => {
      getWards().then((res) => {
        ward.wards = res
        ward.current = res[0].code
        fetchOverviews()
      })
    })

    return {
      ward,
      permission,
      tableHieght,
      injuryMode,
      handleSelectSearchMehtod,
      currentMedType,
      medTypes,
      search,
      searchPatient,
      downloadReadCard,
      cptOverviews,
      maleIcon,
      femaleIcon,
      fetchOverviews,
      getStatusFlag,
      handleClickOverview,
      handleSelectionChange,
      registerInfo,
      showRegisterInfo,
      getRegInfo,
      currentPage,
      handleCurrentPageChange,
      isYbVerifyPage,
      statusFlag,
      statusFlags,
      checkIdInfo,
      handleClickIdCard,
      identityFiles,
      isUploadPage,
      toEmpiView,
      cptSex,
      cptPsnCertType,
      cptInsutype,
      cptMedType,
      cptYesOrNo,
      dismissIcon,
    }
  },
}

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

function makeOverview(val) {
  return {
    bedNo: val.bedNo,
    inpatientNo: val.inpatientNo,
    admissTimes: val.admissTimes,
    name: val.name,
    sex: val.sex,
    status: val.statusFlag,
    medType: val.medType,
    dismissOrder: val.dismissOrder,
  }
}

function getStatusFlag(flag) {
  // 0：撤销-黑色,1：待审核-橙色,2：已审核-绿色,9：未通过-红色,null/-1：未提交-灰色
  switch (flag) {
    case '0':
      return '<span style="color: black;">已撤销</span>'
    case '1':
      return '<span style="color: orange;">待审核</span>'
    case '2':
      return '<span style="color: green">已审核</span>'
    case '9':
      return '<span style="color: red;">未通过</span>'
    default:
      return '<span style="color:grey">未提交</span>'
  }
}

function initIdentityFiles() {
  const identityFiles = reactive({
    idCard: [],
    scanFile: [],
  })
  return identityFiles
}

function downloadReadCard() {
  window.open('http://172.16.32.160:8888/readcard/ReadCard.exe', '_self')
}
</script>

<style>
.router-parent {
  width: calc(100% - 8px);
}
</style>
