<template>
  <page-layer>
    <template #header>
      <el-input v-model="patNo" style="width: 120px; margin-left: 2px" clearable placeholder="门诊id"></el-input>
      <el-select v-model="medType" style="width: 120px" placeholder="医疗类别">
        <el-option v-for="item in medTypes" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-date-picker
          style="width: 200px"
          v-model="dateRange"
          type="daterange"
          :shortcuts="shortcuts"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
      ></el-date-picker>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" @click="fetchHistoryReceipts">历史处方</el-button>
      <ReadCard :pat-no="patNo" @success="afterReadCard"/>
      <el-dropdown trigger="click" @command="registor">
        <el-button type="primary">
          登记&nbsp;<el-icon>
          <ArrowDown/>
        </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="CreditCard" command="execute">医保登记</el-dropdown-item>
            <el-dropdown-item icon="RefreshLeft" command="revoke">取消登记</el-dropdown-item>
            <el-dropdown-item divided icon="Edit" command="diags">普门诊断补录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-dropdown trigger="click" @command="receiptsOpts" style="margin-left: 8px">
        <el-button type="primary">
          处方&nbsp;<el-icon>
          <ArrowDown/>
        </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="Document" command="insert">生成医保处方</el-dropdown-item>
            <el-dropdown-item icon="Delete" command="delete">删除已生成处方</el-dropdown-item>
            <el-dropdown-item icon="Upload" command="upload">医保处方上传</el-dropdown-item>
            <el-dropdown-item icon="RefreshLeft" command="retract">撤销医保上传</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-dropdown trigger="click" @command="settlement" style="margin-left: 8px">
        <el-button type="primary">
          结算&nbsp;<el-icon>
          <ArrowDown/>
        </el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="SetUp" command="pre">试算</el-dropdown-item>
            <el-dropdown-item icon="Stamp" command="fin">结算</el-dropdown-item>
            <el-dropdown-item icon="RefreshLeft" command="revoke">取消结算</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button type="danger" icon="Refresh" @click="clearinfo" style="margin-left: 8px"> 重置</el-button>
    </template>
    <template #aside>
      <el-table :data="historyReceipts" stripe highlight-current-row @row-click="fetchHistoryReceiptDetail">
        <el-table-column property="patNo" label="Id号" width="70">
          <template #default="scope">
            <span v-html="colorStatus(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column property="times" label="次数" width="40"></el-table-column>
        <el-table-column property="chargeFee" label="金额" width="60"></el-table-column>
        <el-table-column property="chargeDate" label="时间" width="130"></el-table-column>
      </el-table>
    </template>
    <template #main>
      <img v-if="mzVisit.settledFlag === 1" :src="mzSettled" alt="" style="z-index: 999; width: 230px;
            position: absolute; top: 180px; left: 45%; background: rgba(255,255,255,.5)">
      <div class="receipt-title">长沙泰和医院处方笺</div>
      <el-divider></el-divider>
      <div class="receipt-head">
        <div>姓名：{{ mzVisit.name }}</div>
        <div>性别：{{ mzVisit.sex }}</div>
        <div>年龄：{{ mzVisit.age }} 岁</div>
      </div>
      <div class="receipt-head">
        <div>门诊号：{{ mzVisit.patientId }}</div>
        <div>科别：{{ mzVisit.visitDeptName }}</div>
        <div class="ellipsis-text" :title="mzVisit.icdText">临床诊断：{{ mzVisit.icdText }}</div>
      </div>
      <div class="receipt-head">
        <div>开具日期：{{ mzVisit.opDay }}</div>
        <div class="ellipsis-text">
          地址：<span :title="mzVisit.address">{{ mzVisit.address }}</span>
        </div>
        <div>电话：{{ mzVisit.phoneNo }}</div>
      </div>
      <el-divider></el-divider>
      <div :style="receiptBoxStyle">
        <div v-for="(item, index) in currentReceipts" :key="index">
          <div>
            <el-checkbox v-model="item.checked"></el-checkbox>&nbsp;
            <span style="color: rgb(94, 50, 50)"> {{ index + 1 }}）【{{ item.chargeItemCode }}】{{ item.drugName }}&nbsp;&times;&nbsp;&nbsp;{{
                item.quantity
              }} </span>
            <span :style="{ color: item.nationalCode ? 'green' : 'red', fontWeight: 'bold' }"> &nbsp;&nbsp;【医保码：{{
                item.nationalCode || '未匹配'
              }} 】</span>
          </div>
          <div style="margin-bottom: 16px"></div>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="receipt-head">
        <div style="font-size: 15px; width: 70%">医师：{{ mzVisit.doctorName }} / {{ mzVisit.doctorCode }} /
          <span v-html="highlightYbCode(mzVisit.doctorCode,mzVisit.doctorYbCode)"></span></div>
        <div style="font-size: 15px">
          总金额：<span style="font-size: 18px; font-weight: bold">￥{{ currentRow.chargeFee }}</span>
        </div>
      </div>
      <el-dialog title="个人参保信息" v-model="showInsuinfo" width="65%">
        <el-table :data="insuinfo" @row-click="handleClickInsuinfo">
          <el-table-column property="balc" label="余额"></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 property="psnInsuDate" label="个人参保日期"></el-table-column>
          <el-table-column property="pausInsuDate" label="暂停参保日期"></el-table-column>
          <el-table-column property="cvlservFlagName" label="公务员标志"></el-table-column>
          <el-table-column property="insuplcAdmdvs" label="参保地医保区划"></el-table-column>
          <el-table-column property="insuplcAdmdvsName" label="参保地名称"></el-table-column>
          <el-table-column property="empName" label="单位名称"></el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog title="请选择（慢特病备案信息）" v-model="showSpcChrAccts" width="40%">
        <el-table :data="spcChrDiseAccts" @row-click="uploadFees">
          <el-table-column property="opspDiseCode" label="病种编码"></el-table-column>
          <el-table-column property="opspDiseName" label="病种名称"></el-table-column>
          <el-table-column property="begndate" label="生效日期"></el-table-column>
          <el-table-column property="enddate" label="失效日期"></el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog title="请选择生育诊断" v-model="showMatnDises" width="50%">
        <el-table :data="matnDises" @row-click="uploadFees" stripe height="360" highlight-current-row>
          <el-table-column property="code" label="病种编码"></el-table-column>
          <el-table-column property="name" label="病种名称"></el-table-column>
          <el-table-column property="insutype" label="险种类型"></el-table-column>
          <el-table-column property="limitAmt" label="疾病限额"></el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog title="普门诊断补录" v-model="showInputDiags" width="60%" :close-on-click-modal="false"
                 :close-on-press-escape="false">
        <outpatient-diagnose-supply :med-type="medType" :mz-visit="mzVisit"
                                    @close="showInputDiags = false"></outpatient-diagnose-supply>
      </el-dialog>
    </template>
  </page-layer>
</template>

<script>
import {
  deleteAllMzReceipts,
  getHistoryMzReceipts,
  getHistoryReceiptDetail,
  insertSiMzFeesForSupplement,
  outpatientPreSettlement,
  outpatientRegistration,
  revokeOutpatientFeeDetails,
  revokeOutpatientRegistration,
  uploadOutpatientFeeDetails,
  outpatientSettlement,
  revokeOutpatientSettlement,
} from '@/api/medical-insurance/si-outpatient'
import {
  obtainBasicPersonInfo,
  querySpecialChronicDiseasesAccreditation,
  queryMzMatnDises
} from '@/api/medical-insurance/si-query'
import {onMounted, ref} from 'vue'
import store from '@/store'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getMedTypesByFlag} from '@/api/medical-insurance/si-dict'
import {shortcuts} from '@/data/shortcuts'
import {getDateRangeFormatDate} from '@/utils/date'
import ReadCard from '@/components/medical-insurance/readcard/Index.vue'
import OutpatientDiagnoseSupply from '@/components/medical-insurance/outpatient-diagnose-supply/Index.vue'
import mzSettled from '@/assets/mz-settled.png'
import PageLayer from "@/layout/PageLayer";

export default {
  components: {
    PageLayer,
    ReadCard,
    OutpatientDiagnoseSupply,
  },
  setup() {
    const windowSize = store.state.app.windowSize
    const receiptBoxStyle = {
      height: windowSize.h - 335 + 'px',
      overflowY: 'auto',
    }
    const patNo = ref('')
    const medType = ref('')
    const medTypes = ref([])
    const historyReceipts = ref([])
    const currentRow = ref({})
    const mzVisit = ref({})
    const currentReceipts = ref([])
    const showInputDiags = ref(false)
    const dateRange = ref(shortcuts[2].value)
    const colorStatus = (row) => {
      return row.status > 0 ? `<span style="color: green">${row.patNo}</span>` : `<span style="color: red">${row.patNo}</span>`
    }
    const nullPatNo = () => {
      if (patNo.value) {
        return false
      }
      ElMessage({
        message: '请输入门诊ID！',
        type: 'warning',
        duration: 2500,
        showClose: true,
      })
      return true
    }
    const nullMedtype = () => {
      if (medType.value) {
        return false
      }
      ElMessage({
        message: '请选择医疗类别！',
        type: 'warning',
        duration: 2500,
        showClose: true,
      })
      return true
    }

    const fetchHistoryReceipts = () => {
      if (nullPatNo()) {
        return
      }
      if (nullMedtype()) {
        return
      }
      if (!dateRange.value) {
        ElMessage({
          message: '请选择日期范围！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      clearReadCardData()
      historyReceipts.value = []
      currentRow.value = {}
      const dates = getDateRangeFormatDate(dateRange.value)
      getHistoryMzReceipts(patNo.value, dates.startTime, dates.endTime).then((res) => {
        historyReceipts.value = res
      })
    }
    const fetchHistoryReceiptDetail = (row) => {
      currentRow.value = row
      getHistoryReceiptDetail(row).then((res) => {
        mzVisit.value = res.mzVisit
        currentReceipts.value = res.mzReceipts
      })
    }

    const insuinfo = ref([])
    const showInsuinfo = ref(false)
    const registor = (command) => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patNo: patNo.value,
        medType: medType.value,
        times: currentRow.value.times,
        needSaving: 1,
      }
      if (command === 'execute') {
        obtainBasicPersonInfo(param).then((res) => {
          insuinfo.value = res.insuinfo
          showInsuinfo.value = true
        })
      } else if (command === 'revoke') {
        revokeOutpatientRegistration(param).then((res) => {
          ElMessage({
            message: res,
            type: 'success',
            duration: 2000,
            showClose: true,
          })
        })
      } else {
        showInputDiags.value = true
      }
    }

    const readCardData = reactive({
      mdtrtCertType: null,
      readCardResult: null,
      readCardBizType: null,
    })

    const clearReadCardData = () => {
      readCardData.mdtrtCertType = null
      readCardData.readCardResult = null
      readCardData.readCardBizType = null
    }

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

    const handleClickInsuinfo = (row) => {
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
        insutype: row.insutype,
        psnType: row.psnType,
        medType: medType.value,
        balc: row.balc,
        insuplcAdmdvs: row.insuplcAdmdvs,
        empName: row.empName,
        mdtrtCertType: readCardData.mdtrtCertType,
        readCardResult: readCardData.readCardResult,
        readCardBizType: readCardData.readCardBizType,
      }
      outpatientRegistration(param).then((res) => {
        clearReadCardData()
        showInsuinfo.value = false
        ElMessage({
          message: res,
          type: 'success',
          duration: 2000,
          showClose: true,
        })
      })
    }

    const receiptsOpts = (command) => {
      switch (command) {
        case 'insert':
          markMzFees()
          break
        case 'delete':
          deleteMtFees()
          break
        case 'upload':
          qrySpcChrDiseAcct()
          break
        case 'retract':
          revokeFees()
          break
      }
    }

    const markMzFees = () => {
      if (currentReceipts.value.length === 0) {
        ElMessage({
          message: '请先选择要保存的处方！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      ElMessageBox.confirm('是否将选中处方生成医保处方？', '提示', {
        type: 'warning',
        confirmButtonText: '生成',
        cancelButtonText: '取消',
      }).then(() => {
        insertSiMzFeesForSupplement(currentReceipts.value).then(() => {
          currentRow.value.status = '1'
          ElMessage({
            message: '已成功生成医保处方。',
            type: 'success',
            duration: 2500,
            showClose: true,
          })
        })
      }).catch(() => {})
    }

    const matnDises = ref([])
    const showMatnDises = ref(false)
    const spcChrDiseAccts = ref([])
    const showSpcChrAccts = ref(false)
    const qrySpcChrDiseAcct = () => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
      }
      if (medType.value === '51') {
        queryMzMatnDises().then((res) => {
          matnDises.value = res
          showMatnDises.value = true
        })
      } else if (medType.value === '14') {
        querySpecialChronicDiseasesAccreditation(param).then((res) => {
          spcChrDiseAccts.value = res
          showSpcChrAccts.value = true
        })
      } else {
        uploadFees(param)
      }
    }

    const uploadFees = (row) => {
      if (medType.value === '51') {
        row.patNo = patNo.value
        row.times = currentRow.value.times
        row.opspDiseCode = row.code
        row.opspDiseName = row.name
      }
      uploadOutpatientFeeDetails(row).then((res) => {
        showMatnDises.value = false
        showSpcChrAccts.value = false
        mzPreSetl()
      })
    }

    const mzPreSetl = () => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        staffId: store.state.user.info.code,
        patNo: patNo.value,
        times: currentRow.value.times,
        mdtrtCertType: readCardData.mdtrtCertType,
        readCardResult: readCardData.readCardResult,
        readCardBizType: readCardData.readCardBizType,
      }
      outpatientPreSettlement(param).then((res) => {
        const message = '医保处方总费用：' + res.totalCost + '，医保报销金额：' + res.fundPay + '。'
        ElMessageBox.alert(message, '试算成功', {
          type: 'success',
          showCancelButton: false,
        }).then(() => {
        })
      })
    }

    const revokeFees = () => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
      }
      revokeOutpatientFeeDetails(param).then((res) => {
        ElMessage({
          message: res,
          type: 'success',
          duration: 2000,
          showClose: true,
        })
      })
    }

    const deleteMtFees = () => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
      }
      deleteAllMzReceipts(param).then((res) => {
        ElMessage({
          message: res,
          type: 'success',
          duration: 2000,
          showClose: true,
        })
        currentReceipts.value = []
        fetchHistoryReceipts()
      })
    }

    const mzSettle = () => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
        saved: 1,
        mdtrtCertType: readCardData.mdtrtCertType,
        readCardResult: readCardData.readCardResult,
        readCardBizType: readCardData.readCardBizType,
      }
      outpatientSettlement(param).then((res) => {
        clearReadCardData()
        const message = '医保处方总费用：' + res.totalCost + '，医保报销金额：' + res.fundPay + '。'
        ElMessageBox.alert(message, '结算成功', {
          type: 'success',
          showCancelButton: false,
        }).then(() => {
        })
      })
    }

    const revokeMzSettle = () => {
      if (!currentRow.value.times) {
        ElMessage({
          message: '请先选择历史处方。',
          type: 'warning',
          duration: 2000,
          showClose: true,
        })
        return
      }
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
      }
      revokeOutpatientSettlement(param).then((res) => {
        ElMessageBox.alert('撤销门诊结算成功', '提示', {
          type: 'success',
          showCancelButton: false,
        })
      })
    }

    const settlement = (command) => {
      if (command === 'pre') {
        mzPreSetl()
      } else if (command === 'fin') {
        mzSettle()
      } else {
        revokeMzSettle()
      }
    }

    const clearinfo = () => {
      patNo.value = ''
      medType.value = ''
      historyReceipts.value = []
      currentRow.value = {}
      currentReceipts.value = []
    }

    const highlightYbCode = (hisCode, ybCode) => {
      if (!hisCode) {
        return ''
      }
      return ybCode ? `<span>${ybCode}</span>` : '<span style="color: red">医师无医保编码</span>'
    }

    onMounted(() => {
      getMedTypesByFlag('clinic').then((res) => {
        medTypes.value = res
      })
    })

    return {
      patNo,
      medType,
      medTypes,
      receiptBoxStyle,
      historyReceipts,
      currentRow,
      currentReceipts,
      matnDises,
      showMatnDises,
      insuinfo,
      showInsuinfo,
      spcChrDiseAccts,
      showSpcChrAccts,
      shortcuts,
      dateRange,
      mzVisit,
      showInputDiags,
      mzSettled,
      afterReadCard,
      colorStatus,
      fetchHistoryReceipts,
      fetchHistoryReceiptDetail,
      registor,
      handleClickInsuinfo,
      receiptsOpts,
      uploadFees,
      settlement,
      revokeMzSettle,
      clearinfo,
      highlightYbCode,
    }
  },
}
</script>

<style scoped>
.receipt-title {
  width: 100%;
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  height: 32px;
  line-height: 32px;
}

.receipt-head {
  display: flex;
  height: 22px;
  line-height: 22px;
}

.receipt-head > div {
  width: 33%;
  padding-right: 20px;
}
</style>
