<template>
  <div>
    <el-button type="success" icon="RefreshRight" @click="rcvrcalcost"> 费用接收重算</el-button>
    <el-button type="primary" icon="RefreshLeft" @click="showConventions"> 撤销检验项目</el-button>
    <el-button type="success" icon="Money" @click="showChargeList = true"> 费用清单</el-button>
    <el-button type="success" icon="Timer" @click="beforeSettle(false)">出院结算</el-button>
    <el-button type="info" icon="VideoPause" @click="beforeSettle(true)">中间断账</el-button>
    <el-button type="warning" icon="Odometer" :disabled="!isAdmin" @click="cancelDismiss">取消出院结算</el-button>
    <el-button v-if="isKqk" type="danger" icon="Tickets" @click="makeDismissOrder">生成出院医嘱</el-button>
    <el-button type="danger" @click="rejectNotGeneratedMedicationListClick">撤销未生成的药单</el-button>
  </div>
  <div style="margin-top: 4px">
    <el-tag type="info">基本信息</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.name }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>性别</template>
        {{ cptSex(patient.sex) }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 病房</template>
        {{ patient.admissWardName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 床号</template>
        {{ patient.bedNo }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 总费用</template>
        <span v-show="patient.inpatientNo">{{ patient.totalCharge }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 余额</template>
        <span v-html="getBalance(patient.balance)"></span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 入院日期</template>
        {{ patient.admissDate }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 手术</template>
        <span v-show="patient.inpatientNo">{{ cptOperation(patient.operation) }}</span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 医疗类别</template>
        {{ patient.medTypeName }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label> 险种类型</template>
        {{ patient.insutypeName }}
      </el-descriptions-item>
    </el-descriptions>
    <div class="m-divider"></div>
    <div>
      <el-tag type="info">医保出院诊断</el-tag>
      <el-table :data="diags.yb" stripe :height="tableHeight">
        <el-table-column prop="disDiagNo" label="序号"></el-table-column>
        <el-table-column prop="disDiag" label="诊断编码"></el-table-column>
        <el-table-column prop="disDiagComment" label="诊断内容"></el-table-column>
        <el-table-column prop="disDiagStatus" label="出院转归"></el-table-column>
        <el-table-column prop="opName" label="录入人"></el-table-column>
      </el-table>
      <div style="height: 10px"></div>
      <el-tag type="info">病案首页诊断</el-tag>
      <el-table :data="diags.bl" stripe :height="tableHeight">
        <el-table-column prop="disDiagNo" label="序号"></el-table-column>
        <el-table-column prop="disDiag" label="诊断编码"></el-table-column>
        <el-table-column prop="disDiagComment" label="诊断内容"></el-table-column>
        <el-table-column prop="disDiagStatusName" label="出院转归"></el-table-column>
        <el-table-column prop="opName" label="录入人"></el-table-column>
      </el-table>
    </div>
    <el-dialog title="请选择中间断账的日期和时间" v-model="showZjdzDate" width="500px">
      <div style="height: 20px"></div>
      <el-date-picker v-model="patient.zjdzDatetime" type="datetime" placeholder="选择日期时间"></el-date-picker>
      <div style="height: 30px"></div>
      <div style="width: 450px; text-align: right">
        <el-button type="info" icon="Close" @click="cancelSelectZjdzDate">取消</el-button>
        <el-button type="success" icon="Check" @click="confirmSelectZjdzDate">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dismissBtnText + '申请'" v-model="showSettleApplyForm" width="500px">
      <div v-if="settleApply.deathFlag" style="margin-bottom: 20px; color: red">
        患者已死亡。
      </div>
      <div style="margin-bottom: 20px">
        {{ dismissBtnText }}时间：
        <el-date-picker
            :disabled="!patient.midSetl"
            v-model="settleApply.settleDatetime"
            type="datetime"
            placeholder="请选择要断账的时间"
        ></el-date-picker>
      </div>
      <div style="margin-bottom: 20px">
        使用个人账户：
        <el-radio size="large" v-model="settleApply.acctUsedFlag" label="1">是</el-radio>
        <el-radio size="large" v-model="settleApply.acctUsedFlag" label="0">否</el-radio>
      </div>
      <el-input type="textarea" v-model="settleApply.inputComment" placeholder="请输入申请理由"></el-input>
      <div style="width: 450px; text-align: right; margin-top: 30px">
        <el-button type="info" icon="Close" @click="cancelSettleApply">取消</el-button>
        <el-button type="success" icon="Check" @click="confirmSettleApply">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dismissBtnText" v-model="showActOrders" fullscreen @close="closeActOrder">
      <el-table :data="actOrders" @row-click="switchActOrder" :height="actOrderHeight">
        <el-table-column label="医嘱号" fixed>
          <template #default="scope">
            <span v-html="getOrderStatus(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column property="list[0].orderName" label="医嘱名称" fixed></el-table-column>
        <el-table-column property="list[0].frequCode" label="频率"></el-table-column>
        <el-table-column property="cxFlag" label="撤销">
          <template #default="scope">
            <span v-html="getCxFlag(scope.row.cxFlag)"></span>
          </template>
        </el-table-column>
        <el-table-column property="list[0].drugSpecification" label="规格"></el-table-column>
        <el-table-column property="list[0].startTime" label="开始时间"></el-table-column>
        <el-table-column property="list[0].endTime" label="结束时间"></el-table-column>
        <el-table-column property="list[0].chargeAmount" label="一次领量"></el-table-column>
        <el-table-column property="list[0].supplyCode" label="给药方式"></el-table-column>
        <el-table-column property="list[0].physician" label="医生"></el-table-column>
        <el-table-column property="list[0].enterOper" label="录入人"></el-table-column>
        <el-table-column property="list[0].orderCode" label="医嘱码"></el-table-column>
        <el-table-column property="list[0].wardCode" label="病房"></el-table-column>
      </el-table>
      <div style="height: 1px; background: lightgray; margin: 15px 0"></div>
      <el-table :data="actOrderDetail" :height="actOrderHeight">
        <el-table-column label="日期" fixed>
          <template #default="scope">
            <span v-html="getOrderDetailStatus(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column property="chargeCode" label="收费码"></el-table-column>
        <el-table-column property="chargeName" label="项目名称"></el-table-column>
        <el-table-column property="drugSpecification" label="规格"></el-table-column>
        <el-table-column property="chargeStatus" label="状态">
          <template #default="scope">
            {{ scope.row.chargeStatus }}
          </template>
        </el-table-column>
        <el-table-column property="chargeAmount" label="数量"></el-table-column>
        <el-table-column property="chargeFee" label="金额"></el-table-column>
        <el-table-column property="pageNo" label="药品单号"></el-table-column>
        <el-table-column property="execUnit" label="执行科室"></el-table-column>
        <el-table-column property="wardName" label="病区"></el-table-column>
      </el-table>
      <div style="height: 5px"></div>
      <el-tag style="float: left; margin-top: 5px" v-cloak>
        <span style="background: orangered" class="color-span"></span>&nbsp;医技未确认 <span
          style="background: dodgerblue" class="color-span"></span>&nbsp;未确认药
        <span style="background: orange" class="color-span"></span>&nbsp;未接收
      </el-tag>
      <div style="float: right; margin-top: 5px" v-cloak>
        <el-checkbox v-model="patient.deathFlag">患者已死亡</el-checkbox>&nbsp;&nbsp;
        <ReadCard :pat-no="patient.inpatientNo" biztype="01301" @success="afterReadCard"/>
        <el-button type="primary" icon="DataAnalysis" @click="doCalFee">费用计算</el-button>
        <el-button type="success" icon="Timer" @click="excuteDismiss">{{ dismissBtnText }}</el-button>
        <el-button type="warning" icon="Close" @click="closeActOrder">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="此患者费用清单存在负数" v-model="showNegativeFee" width="800px">
      <div style="display: inline-block">
        <el-table :data="negativeFees.slice(0, negativeFees.length / 2 + 1)" empty-text=" " height="300">
          <el-table-column property="code" label="费用" width="80"></el-table-column>
          <el-table-column property="chargeCode" label="编码" width="80"></el-table-column>
          <el-table-column property="name" label="名称" width="180"></el-table-column>
        </el-table>
      </div>
      <div style="display: inline-block; margin-left: 8px">
        <el-table :data="negativeFees.slice(negativeFees.length / 2 + 1, negativeFees.length)" empty-text=" "
                  height="300">
          <el-table-column property="code" label="费用" width="80"></el-table-column>
          <el-table-column property="chargeCode" label="编码" width="80"></el-table-column>
          <el-table-column property="name" label="名称" width="180"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog title="此患者有未处理的药单" v-model="showUnhandledDrugOrder" width="400px">
      <el-table :data="negativeFees" empty-text=" " height="300">
        <el-table-column property="groupName" label="药房" width="120"></el-table-column>
        <el-table-column property="pageNo" label="药单号" width="120"></el-table-column>
        <el-table-column property="pageNoTy" label="退药单号" width="120"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="撤销检验项目" v-model="conventionsVisible" fullscreen @close="closeThreeConventions">
      <el-table :data="roughConventions" @row-click="clickConvention" highlight-current-row :height="actOrderHeight"
                @selection-change="handleSelectConvention">
        <el-table-column type="selection"></el-table-column>
        <el-table-column property="inpatientNo" label="住院号"></el-table-column>
        <el-table-column property="name" label="姓名"></el-table-column>
        <el-table-column property="bedNo" label="床号"></el-table-column>
        <el-table-column property="actOrderNo" label="医嘱号"></el-table-column>
        <el-table-column property="occTime" label="医嘱日期"></el-table-column>
        <el-table-column property="doctorName" label="医生"></el-table-column>
        <el-table-column property="orderName" label="医嘱名称"></el-table-column>
      </el-table>
      <div style="height: 1px; background: lightgray; margin: 15px 0"></div>
      <el-table :data="conventionDetails" :height="actOrderHeight">
        <el-table-column label="选择" width="70">
          <template #default="scope">
            <input type="checkbox" disabled :checked="scope.row.checked"/>
          </template>
        </el-table-column>
        <el-table-column property="name" label="姓名"></el-table-column>
        <el-table-column property="actOrderNo" label="医嘱号"></el-table-column>
        <el-table-column property="orderName" label="医嘱名称"></el-table-column>
        <el-table-column property="doctorName" label="医生"></el-table-column>
        <el-table-column property="occTime" label="医嘱日期"></el-table-column>
        <el-table-column property="xmName" label="项目名称"></el-table-column>
        <el-table-column property="price" label="单价"></el-table-column>
        <el-table-column property="amount" label="数量"></el-table-column>
        <el-table-column property="fee" label="金额"></el-table-column>
      </el-table>
      <el-tag style="float: right; margin-top: 5px" v-cloak>
        <el-button type="success" @click="confirmRetractConventions">撤销检验项目</el-button>
        <el-button type="warning" @click="closeThreeConventions">关闭</el-button>
      </el-tag>
    </el-dialog>
    <el-dialog title="请选择出院医嘱的日期和时间" v-model="showDismissOrderDate" width="500px">
      <el-date-picker v-model="patient.dismissOrderDate" type="datetime" placeholder="选择日期时间"></el-date-picker>
      <div style="height: 30px"></div>
      <div style="width: 450px; text-align: right">
        <el-button type="info" icon="Close" @click="cancelSelectDismissOrderDate">取消</el-button>
        <el-button type="success" icon="Check" @click="confirmSelectDismissOrderDate">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="出院预审有可疑数据" v-model="showPreDischargeErrors" width="600px">
      <el-table :data="preDischargeErrors" empty-text=" " max-height="300">
        <el-table-column property="dept_name" label="科室" width="120"></el-table-column>
        <el-table-column property="doctor_name" label="医生" width="120"></el-table-column>
        <el-table-column property="return_code_message" label="描述" ></el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        是否继续为患者办理出院？
        <el-button type="primary" @click="executeDismissCalculate(false, null)">继续办理</el-button>
        <el-button @click="cancelDischarge">取消办理</el-button>
      </div>
    </el-dialog>
    <charge-list v-if="showChargeList" :pat-no="patient.inpatientNo" :times="patient.admissTimes"
                 @close="showChargeList = false"></charge-list>
  </div>
</template>

<script setup>
import {computed, onActivated, onDeactivated, onMounted, reactive, ref, watchEffect} from 'vue'
import store from '@/store'
import {cptOperation, cptSex} from '@/utils/computed'
import {genDismissActOrder, getDisDiag, receiveAndRecalculateCost} from '@/api/inpatient/patient'
import {powersiPreDischarge, dismissCalculate, getActOrders, selfPayDismiss} from '@/api/inpatient/dismiss'
import {formatDatetime, getDatetime} from '@/utils/date'
import {nullPatient} from '@/utils/validate'
import {ElMessage, ElMessageBox} from 'element-plus'
import {dischargeProcessing, revokeSettlement} from '@/api/medical-insurance/si-inpatient'
import {getSiPatInfo} from '@/api/medical-insurance/si-query'
import {getDetailConventions, getRoughConventions, retractConventions} from '@/api/inpatient/conventions'
import {getGreatestRole} from '@/utils/permission'
import {injurySettlement, revokeInjurySettlement} from '@/api/medical-insurance/si-injury'
import {selectSettleApply, submitSettleApply} from '@/api/medical-insurance/si-settle-apply'
import {baseinfo} from '@/data/inpatient'
import ReadCard from '@/components/medical-insurance/readcard/Index.vue'
import ChargeList from '@/components/medical-insurance/charge-list/Index.vue'
import {rejectNotGeneratedMedicationList} from "@/api/inpatient/xiang-mu-lu-ru";

const isAdmin = getGreatestRole() < 10
const actOrderHeight = (store.state.app.windowSize.h - 160) / 2
const patient = computed(() => {
  return baseinfo()
})
const injuryMode = computed(() => {
  return store.state.ptnt.injuryMode
})
const diags = initDiags()
const fecthDisDiags = () => {
  getDisDiag(patient.value.inpatientNo, patient.value.admissTimes).then((res) => {
    diags.yb = res.yb
    diags.bl = res.bl
  })
}
const clearDiags = () => {
  diags.yb = []
  diags.bl = []
}

const actived = ref(false)

watchEffect(() => {
  if (actived.value) {
    if (patient.value.inpatientNo) {
      fecthDisDiags()
    } else {
      clearDiags()
    }
  }
})

onActivated(() => {
  actived.value = true
})

onDeactivated(() => {
  actived.value = false
})

const tableHeight = (store.state.app.windowSize.h - 256) / 2
const showZjdzDate = ref(false)
const cancelSelectZjdzDate = () => {
  patient.value.zjdzDatetime = null
  showZjdzDate.value = false
}
const confirmSelectZjdzDate = () => {
  patient.value.zjdzDatetime = formatDatetime(patient.value.zjdzDatetime)
  ElMessageBox.confirm('您选择的中间断账时间为【' + patient.value.zjdzDatetime + '】', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    showZjdzDate.value = false
    fetchActOrders()
  })
}

const cancelSettleApply = () => {
  patient.value.zjdzDatetime = null
  settleApply.value = {}
  showSettleApplyForm.value = false
}

const confirmSettleApply = () => {
  if (settleApply.value.type === 2 && !settleApply.value.settleDatetime) {
    ElMessage({
      message: '中间断账的时间不能为空！',
      type: 'error',
      duration: 2500,
      showClose: true,
    })
    return
  }
  if (!settleApply.value.inputComment) {
    ElMessage({
      message: '申请理由不能为空！',
      type: 'error',
      duration: 2500,
      showClose: true,
    })
    return
  }
  settleApply.value.settleDatetime = formatDatetime(settleApply.value.settleDatetime)
  let message = '是否确认提交' + dismissBtnText.value + '申请？'
  if (settleApply.value.type === 2) {
    message += '您选择的中间断账时间为【' + settleApply.value.settleDatetime + '】，请仔细核对。'
  }
  ElMessageBox.confirm(message, '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    submitSettleApply(settleApply.value).then((res) => {
      ElMessage({
        message: res,
        type: 'success',
        duration: 2500,
        showClose: true,
      })
      showSettleApplyForm.value = false
    })
  }).catch(() => {
  })
}

const dismissBtnText = computed(() => {
  return patient.value.midSetl ? '中间断账' : '出院结算'
})
const dismissCalMsg = ref('')
const actOrders = ref([])
const actOrderDetail = ref([])
const showActOrders = ref(false)
const showSettleApplyForm = ref(false)
const settleApply = ref({})
const closeActOrder = () => {
  actOrders.value = actOrderDetail.value = []
  dismissCalMsg.value = ''
  showActOrders.value = false
}
const executeDismissCalculate = (midSetl, disdate) => {
  showPreDischargeErrors.value = false
  dismissCalculate(patient.value).then(() => {
    settleApply.value.patNo = patient.value.inpatientNo
    settleApply.value.times = patient.value.admissTimes
    settleApply.value.ledgerSn = patient.value.ledgerSn
    settleApply.value.type = midSetl ? 2 : 1
    settleApply.value.settleDatetime = disdate || setlDatetime.value
    settleApply.value.acctUsedFlag = '0'
    settleApply.value.deathFlag = patient.value.deathFlag
    settleApply.value.inputComment = midSetl ? null : '医嘱离院。'
    showSettleApplyForm.value = true
  }).catch((res2) => {
    if (res2.code && res2.code === 1004) {
      negativeFees.value = res2.data
      dismissCalMsg.value = res2.message
      showNegativeFee.value = true
    } else if (res2.code && res2.code === 1104) {
      negativeFees.value = res2.data
      dismissCalMsg.value = res2.message
      showUnhandledDrugOrder.value = true
    } else {
      dismissCalMsg.value = res2.toString()
    }
  })
}

const preDischargeErrors = ref([])
const showPreDischargeErrors = ref(false)
const setlDatetime = ref('')

const cancelDischarge = () => {
  showPreDischargeErrors.value = false
  preDischargeErrors.value = []
  setlDatetime.value = ''
}

const preDischarge = (midSetl, settleDatetime) => {
  if (midSetl) {
    executeDismissCalculate(midSetl, settleDatetime)
  } else {
    powersiPreDischarge(makeVisitId()).then(() => {
      executeDismissCalculate(midSetl, settleDatetime)
    }).catch((e) => {
      setlDatetime.value = settleDatetime
      preDischargeErrors.value = e.data
      showPreDischargeErrors.value = true
    })
  }
}

const makeVisitId = () => {
  return patient.value.inpatientNo + '_'
      + patient.value.admissTimes + '_'
      + patient.value.ledgerSn
}

const beforeSettle = (midSetl) => {
  if (nullPatient()) {
    return
  }
  patient.value.midSetl = midSetl
  selectSettleApply(patient.value).then((res) => {
    if (null === res.status) {
      patient.value.sid = store.getters['user/sid']
      patient.value.zjdzDatetime = getDatetime()
      ElMessageBox.confirm('请确认患者状态：', '提示', {
        type: 'warning',
        confirmButtonText: '患者未死亡',
        cancelButtonText: '患者已死亡',
        distinguishCancelAndClose: true,
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).then(() => {
        patient.value.deathFlag = false
        preDischarge(midSetl, res.settleDatetime)
      }).catch((action) => {
        if (action === 'cancel') {
          patient.value.deathFlag = true
          preDischarge(midSetl, res.settleDatetime)
        }
      })
    } else {
      switch (res.status) {
        case 0:
          ElMessageBox.alert('医保科尚未处理此患者的' + dismissBtnText.value + '申请，请耐心等候或者致电医保科（内线电话：2102）。', '提示', {
            type: 'warning',
          })
          break
        case 1:
          patient.value.acctUsedFlag = res.acctUsedFlag
          patient.value.deathFlag = res.deathFlag
          if (res.settleDatetime) {
            patient.value.zjdzDatetime = res.settleDatetime
            fetchActOrders()
          } else {
            if (midSetl) {
              patient.value.zjdzDatetime = getDatetime()
              showZjdzDate.value = true
            } else {
              fetchActOrders()
            }
          }
          break
        case 2:
          ElMessageBox.confirm('医保科驳回了此患者的' + dismissBtnText.value + '申请，驳回意见为【' + res.handleComment + '】', '提示', {
            type: 'error',
            distinguishCancelAndClose: true,
            confirmButtonText: '我知道了',
            cancelButtonText: '重新提交',
            showCancelButton: true,
          }).catch((action) => {
            if (action === 'cancel') {
              patient.value.sid = store.getters['user/sid']
              patient.value.zjdzDatetime = res.settleDatetime
              ElMessageBox.confirm('请确认患者状态：', '提示', {
                type: 'warning',
                confirmButtonText: '患者未死亡',
                cancelButtonText: '患者已死亡'
              }).then(() => {
                patient.value.deathFlag = false
                executeDismissCalculate(midSetl, res.settleDatetime)
              }).catch(() => {
                patient.value.deathFlag = true
                executeDismissCalculate(midSetl, res.settleDatetime)
              })
            }
          })
          break
      }
    }
  })
}

const fetchActOrders = () => {
  getActOrders(patient.value.inpatientNo, patient.value.admissTimes).then((res) => {
    actOrders.value = res
    if (res.length > 0) {
      actOrderDetail.value = res[0].list
    }
    showActOrders.value = true
  })
}

const switchActOrder = (row) => {
  actOrderDetail.value = row.list
}

const showNegativeFee = ref(false)
const showUnhandledDrugOrder = ref(false)
const negativeFees = ref([])

const doCalFee = () => {
  patient.value.sid = store.getters['user/sid']
  dismissCalculate(patient.value).then((res) => {
    dismissCalMsg.value = 'done'
    ElMessageBox.alert('计算成功。', '提示', {
      type: 'success',
    })
  }).catch((res) => {
    if (res.code && res.code === 1004) {
      negativeFees.value = res.data
      dismissCalMsg.value = res.message
      showNegativeFee.value = true
    } else if (res.code && res.code === 1104) {
      negativeFees.value = res.data
      dismissCalMsg.value = res.message
      showUnhandledDrugOrder.value = true
    } else {
      dismissCalMsg.value = res.toString()
    }
  })
}
const excuteDismiss = () => {
  if (dismissCalMsg.value !== 'done') {
    const message = dismissCalMsg.value === '' ? '请先进行费用计算！' : dismissCalMsg.value
    ElMessage({
      message: message,
      type: 'error',
      duration: 2500,
      showClose: true,
    })
    return
  }
  const param = {
    patNo: patient.value.inpatientNo,
    times: patient.value.admissTimes,
    ledgerSn: patient.value.ledgerSn,
  }
  getSiPatInfo(param).then((res) => {
    patient.value.medType = res.medType
    if (!res.mdtrtId) {
      ziFeiDismiss()
    } else {
      injuryMode.value ? injuryDismiss() : yibaoDismiss()
    }
  })
}

const injuryDismiss = () => {
  injurySettlement(patient.value).then((res) => {
    ElMessageBox.alert(dismissBtnText.value + '成功。', '提示', {
      type: 'success',
    })
  }).then(() => {
    afterDismiss()
  })
}

const ziFeiDismiss = () => {
  const param = {
    inpatientNo: patient.value.inpatientNo,
    admissTimes: patient.value.admissTimes,
    bedNo: patient.value.bedNo,
    deptCode: patient.value.admissDept,
    wardCode: patient.value.admissWard,
    midSetl: patient.value.midSetl,
    zjdzDatetime: patient.value.zjdzDatetime,
  }
  selfPayDismiss(param).then(() => {
    ElMessageBox.alert(dismissBtnText.value + '成功。', '提示', {
      type: 'success',
    }).then(() => {
      afterDismiss()
    })
  })
}

const yibaoDismiss = () => {
  dischargeProcessing(patient.value).then(() => {
    ElMessageBox.alert(dismissBtnText.value + '成功。', '提示', {
      type: 'success',
    }).then(() => {
      afterDismiss()
    })
  })
}

const afterDismiss = () => {
  if (patient.value.midSetl) {
    patient.value.ledgerSn += 1
  }
  showActOrders.value = false
}
const showChargeList = ref(false)
const conventionsVisible = ref(false)
const roughConventions = ref([])
const conventionDetails = ref([])
const selectedConventions = ref([])
const showConventions = () => {
  if (nullPatient()) return
  conventionDetails.value = []
  getRoughConventions(patient.value.inpatientNo, patient.value.admissTimes).then((res) => {
    roughConventions.value = res
    if (res.length > 0) {
      clickConvention(res[0])
    }
    conventionsVisible.value = true
  })
}
const clickConvention = (row) => {
  getDetailConventions(row.inpatientNo, row.actOrderNo).then((res) => {
    conventionDetails.value = res
    if (selectedConventions.value.indexOf(row) > -1) {
      conventionDetails.value.forEach((item) => (item.checked = true))
    }
  })
}
const handleSelectConvention = (val) => {
  selectedConventions.value = val
}
const confirmRetractConventions = () => {
  if (selectedConventions.value.length === 0) {
    ElMessage({
      message: '没有选中的条目。',
      type: 'warning',
      duration: 2500,
      showClose: true,
    })
  } else {
    ElMessageBox.confirm('确定撤销选中的常规项目吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '放弃',
    }).then(() => {
      let orders = []
      selectedConventions.value.forEach((item) => {
        orders.push(item.actOrderNo)
      })
      retractConventions(orders).then(() => {
        ElMessage({
          message: '撤销成功。',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
        showConventions()
      })
    }).catch(() => {})
  }
}

const closeThreeConventions = () => {
  roughConventions.value = conventionDetails.value = []
  conventionsVisible.value = false
}

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

const cancelDismiss = () => {
  ElMessageBox.confirm('确定取消此患者的医保结算？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
    type: 'warning',
  }).then(() => {
    if (injuryMode.value) {
      revokeInjurySettlement(patient.value).then(() => {
        ElMessage({
          message: '取消医保结算成功。',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
      })
    } else {
      revokeSettlement(patient.value).then(() => {
        ElMessage({
          message: '取消医保结算成功。',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
      })
    }
  }).catch(() => {})
}

const showDismissOrderDate = ref(false)

const cancelSelectDismissOrderDate = () => {
  patient.value.dismissOrderDate = new Date()
  showDismissOrderDate.value = false
}

const confirmSelectDismissOrderDate = () => {
  ElMessageBox.confirm('您选择的出院医嘱时间为：' + formatDatetime(patient.value.dismissOrderDate) + '，是否确认？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    patient.value.dismissOrderDate = formatDatetime(patient.value.dismissOrderDate)
    genDismissActOrder(patient.value).then((res) => {
      ElMessageBox.alert('生成出院医嘱成功！医嘱号为：' + res, '提示', {
        type: 'success',
        confirmButtonText: '确定',
      })
    }).then(() => {
      showDismissOrderDate.value = false
      fecthDisDiags()
    })
  }).catch(() => {})
}

const makeDismissOrder = () => {
  if (nullPatient()) return
  patient.value.dismissOrderDate = new Date()
  showDismissOrderDate.value = true
}
const isKqk = computed(() => {
  return store.state.user.info.deptCode === '8000201' || store.state.user.info.deptCode === '1090000'
})
const rcvrcalcost = () => {
  if (nullPatient()) return
  receiveAndRecalculateCost(patient.value).then((res) => {
    ElMessage({
      type: 'success',
      message: res,
      duration: 2000,
      showClose: true,
    })
  })
}

const rejectNotGeneratedMedicationListClick = () => {
  if (nullPatient()) return
  ElMessageBox.confirm('请问是否要撤销所有未提交的药单，此操作不可逆。', '提示', {
    type: 'warning',
  }).then(() => {
    rejectNotGeneratedMedicationList(patient.value.inpatientNo, patient.value.admissTimes)
  }).catch(() => {

  })
}

onMounted(() => {
  if (patient.value.inpatientNo) {
    fecthDisDiags()
  }
})

function getBalance(val) {
  return val > 0 ? '<span style="color: green">' + val + '</span>' : val
}

function initDiags() {
  return reactive({
    yb: [],
    bl: [],
  })
}

function getOrderStatus(val) {
  switch (val.chargeStatus) {
    case 5: // 未确认药
      return '<p style="background: dodgerblue; color: white;">' + val.actOrderNo + '</p>'
    case 6: // 未接收
      return '<p style="background: orange; color: white;">' + val.actOrderNo + '</p>'
    case 8: // 医技未确认
      return '<p style="background: orangered; color: white;">' + val.actOrderNo + '</p>'
    default:
      return '<p>' + val.actOrderNo + '</p>'
  }
}

function getOrderDetailStatus(val) {
  switch (val.chargeStatus) {
    case 5: // 未确认药
      return '<p style="background: dodgerblue; color: white;">' + val.chargeDate + '</p>'
    case 6: // 未接收
      return '<p style="background: orange; color: white;">' + val.chargeDate + '</p>'
    case 8: // 医技未确认
      return '<p style="background: orangered; color: white;">' + val.chargeDate + '</p>'
    default:
      return '<p>' + val.chargeDate + '</p>'
  }
}

function getCxFlag(val) {
  return val === '1' ? '<p style="color: orangered;">是</p>' : '<p style="color:green">否</p>'
}
</script>

<style scoped>
.m-divider {
  height: 1px;
  background-color: white;
  width: 100%;
  margin: 5px 0;
}

.color-span {
  display: inline-block;
  width: 30px;
  height: 10px;
  margin-left: 15px;
}
</style>
