<template>
  <div class="layout_container">
    <header class="round-header">
      <el-date-picker
          style="width: 200px"
          v-model="dateRange"
          type="daterange"
          :shortcuts="shortcuts"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
      ></el-date-picker>
      <el-input v-model="patNo" style="width: 100px; margin-left: 2px" clearable placeholder="门诊id"></el-input>
      <el-select v-model="medType" style="width: 106px" placeholder="医疗类别" @change="handleMedTypeChange">
        <el-option v-for="item in medTypes" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-cascader
          v-model="admdvsCascader"
          clearable filterable
          placeholder="参保地区"
          :options="allAdmdvses"
          @change="handleAdmdvsChange"
          style="width: 160px"
          :disabled="injuryMode === true"
      ></el-cascader>
      <el-select v-model="acctUsedFlag" style="width: 118px">
        <el-option label="不使用个账" value="0"></el-option>
        <el-option label="使用本人个账" value="1"></el-option>
        <el-option label="使用共济人个账" value="2"></el-option>
      </el-select>
      <el-select v-model="patMedInsPaused" style="width: 110px">
        <el-option label="患者正常参保" value="normal"></el-option>
        <el-option label="患者已停保" value="paused"></el-option>
      </el-select>
      <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="register">
        <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="Help" command="emergencyRescue">急诊抢救</el-dropdown-item>
            <el-dropdown-item icon="Refresh" command="rvkEmergencyRescue">急诊抢救撤销</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="success" style="margin-left: 8px" @click="seeMzBlRecord">门诊病历</el-button>
      <el-button type="danger" icon="Refresh" @click="clearinfo"> 重置</el-button>
    </header>
    <div class="layout_main layout_container layout-horizontal">
      <aside class="layout_el-table">
        <el-table
            :data="historyReceipts"
            stripe
            highlight-current-row
            @row-click="fetchHistoryReceiptDetail"
            height="100%"
        >
          <el-table-column property="patNo" label="ID号_次数" width="120">
            <template #default="scope">
              <span v-html="colorStatus(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="诊间" width="40">
            <template #default="scope">
              <span v-html="isMztczf(scope.row)"></span>
            </template>
          </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>
      </aside>
      <div class="layout_main" style="padding: 30px; position: relative">
        <img v-if="mzVisit.settledFlag === 1" :src="mzSettled" alt="" style="z-index: 999; width: 230px;
            position: absolute; top: 160px; left: 260px; background: rgba(255,255,255,.5)">
        <mz-receipt :mz-visit="mzVisit" :receipts="currentReceipts" show-checkbox/>
      </div>
    </div>
  </div>

  <el-dialog title="个人信息" v-model="showInsuinfo" 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="aac002"></el-table-column>
        <el-table-column label="姓名" prop="aac003"></el-table-column>
        <el-table-column label="单位名称" prop="aab004"></el-table-column>
        <el-table-column label="受伤时间" prop="alc020"></el-table-column>
        <el-table-column label="认定申请时间" prop="alc017"></el-table-column>
        <el-table-column label="认定ID" prop="aaz127"></el-table-column>
        <el-table-column label="个人编号" prop="aac001"></el-table-column>
        <el-table-column label="参保统筹区" prop="baa027Name"></el-table-column>
      </el-table>
    </div>
    <div v-else>
      <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>
    </div>
  </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>

  <mz-bl-record
      v-if="showMzBlRecord"
      :patient-id="currentRow.patNo"
      :times="currentRow.times"
      @closed="showMzBlRecord = false"
  ></mz-bl-record>

  <EmergencyRescue ref="emergencyRef" :param="emergencyParams" />
</template>

<script setup>
import {
  deleteAllMzReceipts,
  getHistoryMzReceipts,
  getHistoryReceiptDetail,
  insertSiMzFeesForSupplement,
  outpatientPreSettlement,
  outpatientRegistration,
  revokeOutpatientFeeDetails,
  revokeOutpatientRegistration,
  uploadOutpatientFeeDetails,
  outpatientSettlement,
  revokeOutpatientSettlement,
} from '@/api/medical-insurance/si-outpatient'
import {
  employeeInfoInquiry2, injuryOutpatientFeeUpload,
  injuryOutpatientRegister, injuryOutpatientSettlement, revokeInjuryOutpatientFee,
  revokeInjuryOutpatientRegistration, revokeInjuryOutpatientSettlement
} from "@/api/medical-insurance/si-injury";
import {
  obtainBasicPersonInfo,
  querySpecialChronicDiseasesAccreditation,
  queryMzMatnDises
} from '@/api/medical-insurance/si-query'
import {onMounted, ref} from 'vue'
import {ElMessageBox, ElSelect} 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 {allAdmdvses} from "@/data/admdvs";
import MzBlRecord from "@/components/outpatient/MzBlRecord.vue";
import MzReceipt from "@/components/outpatient/MzReceipt.vue";
import {useUserStore} from "@/pinia/user-store";
import {CyMessageBox} from "@/components/cy/message-box";
import EmergencyRescue from "@/views/medical-insurance/outpatient/component/EmergencyRescue.vue";
import {xcMessage} from "@/utils/xiaochan-element-plus";
import {checkGeneratedFees} from "@/api/medical-insurance/emergency-rescue";

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 patMedInsPaused = ref('normal')
const injuryinfo = ref([])
const injuryMode = computed(() => {
  return medType.value === '41' || medType.value === '46'
})
const colorStatus = (row) => {
  return row.status > 0 ? `<span style="color: green">${row.patNo}_${row.times}</span>` : `<span style="color: red">${row.patNo}_${row.times}</span>`
}
const isMztczf = (row) => {
  return row.zgmztczf === 1 ? `<span style="color: green">医保</span>` : `<span>自费</span>`
}

const admdvs = ref(null)
const admdvsCascader = ref([])
const handleMedTypeChange = (val) => {
  if (val === '41') {
    admdvsCascader.value = []
    admdvs.value = null
  }
}
const handleAdmdvsChange = (val) => {
  admdvs.value = val ? val[1] : null;
}

const nullPatNo = () => {
  if (patNo.value) {
    return false
  }
  xcMessage.warning('请输入门诊ID！')
  return true
}
const nullMedtype = () => {
  if (medType.value) {
    return false
  }
  xcMessage.warning('请选择医疗类别！')
  return true
}

const fetchHistoryReceipts = () => {
  if (nullPatNo()) {
    return
  }
  if (nullMedtype()) {
    return
  }
  if (!dateRange.value) {
    xcMessage.warning('请选择日期范围！')
    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
    mzVisit.value.totalFee = row.chargeFee
    currentReceipts.value = res.mzReceipts
  })
}

const insuinfo = ref([])
const showInsuinfo = ref(false)

const handleClickInjuryinfo = (row) => {
  row.patNo = patNo.value
  row.times = currentRow.value.times
  row.ledgerSn = 0
  row.aka130 = medType.value
  if (row.aka130 === '41') {
    row.bka003 = '410'
  } else if (row.aka130 === '46') {
    row.bka003 = '461'
  }
  injuryOutpatientRegister(row).then(() => {
    showInsuinfo.value = false
    clearReadCardData()
    xcMessage.success('登记成功')
  })
}

const register = (command) => {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方。')
    return
  }
  const param = {
    patNo: patNo.value,
    medType: medType.value,
    times: currentRow.value.times,
    admdvs: admdvs.value,
    legderSn: 0,
    needSaving: 1,
  }
  if (command === 'execute') {
    beforeRegister(param)
  } else if (command === 'revoke') {
    revokeRegister(param)
  } else if (command === 'emergencyRescue') {
    beforeEmergencyRescue(param)
  } else if (command === 'rvkEmergencyRescue') {
    revokeEmergencyRescue(param)
  } else {
    showInputDiags.value = true
  }
}

function beforeRegister(param) {
  if (param.medType === '1301') {
    xcMessage.error('医疗类别为【急诊抢救】的患者，请选择急诊抢救专用通道。')
    return
  }
  if (injuryMode.value) {
    employeeInfoInquiry2(param).then((res) => {
      injuryinfo.value = res
      showInsuinfo.value = true
    })
  } else {
    obtainBasicPersonInfo(param).then((res) => {
      insuinfo.value = res.insuinfo
      showInsuinfo.value = true
    })
  }
}

function revokeRegister(param) {
  if (injuryMode.value) {
    revokeInjuryOutpatientRegistration(param).then(res => {
      xcMessage.success(res)
    })
  } else {
    revokeOutpatientRegistration(param).then((res) => {
      xcMessage.success(res)
    })
  }
}

function beforeEmergencyRescue(param) {
  if (param.medType !== '1301') {
    xcMessage.error('医疗类别请选择【急诊抢救】。')
    return
  }
  checkGeneratedFees(param).then(() => {
    obtainBasicPersonInfo(param).then(res => {
      insuinfo.value = res.insuinfo
      showInsuinfo.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 emergencyRef = ref(null)
const emergencyParams = ref({})
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,
  }
  if (param.medType === '1301') {
    emergencyRescueProcess(param)
  } else {
    normalOutpatientRegister(param)
  }
}

function emergencyRescueProcess(param) {
  showInsuinfo.value = false
  emergencyParams.value = param
  nextTick().then(() => {
    emergencyRef.value.start()
  })
}

function revokeEmergencyRescue(param) {
  if (param.medType !== '1301') {
    xcMessage.error('医疗类别请选择【急诊抢救】。')
    return
  }
  emergencyParams.value = param
  nextTick().then(() => {
    emergencyRef.value.revoke()
  })
}

function normalOutpatientRegister(param) {
  outpatientRegistration(param).then((res) => {
    clearReadCardData()
    showInsuinfo.value = false
    xcMessage.success(res)
  });
}

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) {
    xcMessage.warning('请先选择要保存的处方！')
    return
  }
  ElMessageBox.confirm('是否将选中处方生成医保处方？', '提示', {
    type: 'warning',
    confirmButtonText: '生成',
    cancelButtonText: '取消',
  }).then(() => {
    insertSiMzFeesForSupplement(currentReceipts.value).then(() => {
      currentRow.value.status = '1'
      xcMessage.success('已成功生成医保处方。');
    })
  }).catch(() => {
  })
}

const matnDises = ref([])
const showMatnDises = ref(false)
const spcChrDiseAccts = ref([])
const showSpcChrAccts = ref(false)
const qrySpcChrDiseAcct = () => {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  const param = {
    patNo: patNo.value,
    times: currentRow.value.times,
    ledgerSn: 0,
    calType: 0
  }
  if (injuryMode.value) {
    injuryOutpatientFeeUpload(param).then(() => {
      injuryOutpatientSettlement(param).then(res => {
        const message = '处方总费用：' + res.totalCost + '，工伤报销金额：' + res.fundPay + '。'
        ElMessageBox.alert(message, '试算成功', {
          type: 'success',
          showCancelButton: false,
        }).then(() => {
        })
      })
    });
  } else {
    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
    if (patMedInsPaused.value === 'normal') {
      mzPreSetl()
    } else {
      CyMessageBox.alert({
        type: 'success',
        message: '上传成功'
      })
    }
  })
}

const userStore = useUserStore()
const mzPreSetl = () => {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  const param = {
    staffId: userStore.code,
    patNo: patNo.value,
    times: currentRow.value.times,
    mdtrtCertType: readCardData.mdtrtCertType,
    readCardResult: readCardData.readCardResult,
    readCardBizType: readCardData.readCardBizType,
    acctUsedFlag: acctUsedFlag.value,
    ledgerSn: 0,
    calType: 0
  }
  if (injuryMode.value) {
    injuryOutpatientSettlement(param).then(res => {
      const message = '处方总费用：' + res.totalCost + '，工伤报销金额：' + res.fundPay + '。'
      ElMessageBox.alert(message, '试算成功', {
        type: 'success',
        showCancelButton: false,
      }).then(() => {
      })
    });
  } else {
    outpatientPreSettlement(param).then((res) => {
      const message = '医保处方总费用：' + res.totalCost + '，医保报销金额：' + res.fundPay + '。'
      ElMessageBox.alert(message, '试算成功', {
        type: 'success',
        showCancelButton: false,
      }).then(() => {
      })
    })
  }
}

const revokeFees = () => {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  const param = {
    patNo: patNo.value,
    times: currentRow.value.times,
    ledgerSn: 0,
  }
  if (injuryMode.value) {
    revokeInjuryOutpatientFee(param).then(res => {
      xcMessage.success(res)
    })
  } else {
    revokeOutpatientFeeDetails(param).then((res) => {
      xcMessage.success(res)
    });
  }
}

const deleteMtFees = () => {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  const param = {
    patNo: patNo.value,
    times: currentRow.value.times,
  }
  deleteAllMzReceipts(param).then((res) => {
    xcMessage.success(res)
    currentReceipts.value = []
    fetchHistoryReceipts()
  })
}

const acctUsedFlag = ref('1')

const mzSettle = () => {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  const param = {
    patNo: patNo.value,
    times: currentRow.value.times,
    saved: 1,
    mdtrtCertType: readCardData.mdtrtCertType,
    readCardResult: readCardData.readCardResult,
    readCardBizType: readCardData.readCardBizType,
    ledgerSn: 0,
    calType: 1,
    acctUsedFlag: acctUsedFlag.value,
  }
  if (injuryMode.value) {
    injuryOutpatientSettlement(param).then(res => {
      const message = '处方总费用：' + res.totalCost + '，工伤报销金额：' + res.fundPay + '。'
      ElMessageBox.alert(message, '结算成功', {
        type: 'success',
        showCancelButton: false,
      }).then(() => {
      })
    });
  } else {
    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) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  const param = {
    patNo: patNo.value,
    times: currentRow.value.times,
    ledgerSn: 0
  }
  if (injuryMode.value) {
    revokeInjuryOutpatientSettlement(param).then(res => {
      ElMessageBox.alert(res, '提示', {
        type: 'success',
        showCancelButton: false,
      })
    });
  } else {
    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 showMzBlRecord = ref(false)

function seeMzBlRecord() {
  if (!currentRow.value.times) {
    xcMessage.warning('请先选择历史处方！')
    return
  }
  showMzBlRecord.value = true
}

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