<template>
  <el-container>
    <el-header style="height: 35px; margin-top: 10px">
      <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
        v-model="dateRange"
        type="daterange"
        :shortcuts="shortcuts"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px"
      ></el-date-picker>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" @click="fetchHistoryReceipts">历史处方</el-button>

      <el-dropdown trigger="click" @command="registor" style="margin-left: 8px">
        <el-button type="primary">登记<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="el-icon-bank-card" command="execute">医保登记</el-dropdown-item>
            <el-dropdown-item icon="el-icon-refresh-left" command="revoke">取消登记</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-dropdown trigger="click" @command="receiptsOpts" style="margin-left: 8px">
        <el-button type="primary">处方<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="el-icon-document" command="insert">生成医保处方</el-dropdown-item>
            <el-dropdown-item icon="el-icon-delete" command="delete">删除已生成处方</el-dropdown-item>
            <el-dropdown-item icon="el-icon-upload" command="upload">医保处方上传</el-dropdown-item>
            <el-dropdown-item icon="el-icon-refresh-left" 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">结算<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item icon="el-icon-document" command="pre">试算</el-dropdown-item>
            <el-dropdown-item icon="el-icon-document" command="fin">结算</el-dropdown-item>
            <el-dropdown-item icon="el-icon-refresh-left" command="revoke">取消结算</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button type="danger" icon="el-icon-refresh" @click="clearinfo" style="margin-left: 8px"> 重置 </el-button>
    </el-header>
    <el-container>
      <el-aside width="300px">
        <el-tag>历史处方目录</el-tag>
        <el-table :height="tableHeight" :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="时间"></el-table-column>
        </el-table>
      </el-aside>
      <el-main>
        <el-tag>历史处方明细</el-tag>
        <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-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="60%">
          <el-table :data="matnDises" @row-click="uploadFees" stripe height="360">
            <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-main>
    </el-container>
  </el-container>
</template>

<script>
import {
  deleteAllMzReceipts,
  getHistoryMzReceipts,
  getHistoryReceiptDetail,
  insertSiMzFees,
  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-demi'
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'
export default {
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 70
    const receiptBoxStyle = {
      height: tableHeight - 8 + 'px',
      marginTop: '8px',
      overflowY: 'auto',
    }
    const patNo = ref('')
    const medType = ref('')
    const medTypes = ref([])
    const historyReceipts = ref([])
    const currentRow = ref({})
    const currentReceipts = ref([])
    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
      }
      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) => {
        currentReceipts.value = res
      })
    }

    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 {
        revokeOutpatientRegistration(param).then((res) => {
          ElMessage({
            message: res,
            type: 'success',
            duration: 2000,
            showClose: true,
          })
        })
      }
    }

    const handleClickInsuinfo = (row) => {
      const param = {
        patNo: patNo.value,
        times: currentRow.value.times,
        insutype: row.insutype,
        psnType: row.psnType,
        insuplcAdmdvs: row.insuplcAdmdvs,
        empName: row.empName,
      }
      outpatientRegistration(param).then((res) => {
        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(() => {
          insertSiMzFees(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 {
        querySpecialChronicDiseasesAccreditation(param).then((res) => {
          spcChrDiseAccts.value = res
          showSpcChrAccts.value = true
        })
      }
    }

    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,
      }
      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,
      }
      outpatientSettlement(param).then((res) => {
        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(res, '取消结算成功', {
          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 = []
    }

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

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