<template>
  <el-container>
    <el-header style="height: 35px; margin-top: 10px">
      <el-input v-model="patientId" style="width: 200px; margin-left: 2px" clearable placeholder="请输入">
        <template #prepend>门诊id</template>
      </el-input>
      <el-select v-model="medType" style="width: 120px">
        <el-option v-for="item in medTypes" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <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="require">获取门诊处方</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-button type="primary" icon="el-icon-edit-outline" @click="mzPreSetl" style="margin-left: 8px"> 试算 </el-button>
    </el-header>
    <el-main>
      <el-row :gutter="5">
        <el-col :span="2">
          <el-table ref="timesTable" :data="data" highlight-current-row :height="tableHeight" @row-click="clickTimes">
            <el-table-column label="就诊次数">
              <template #default="scope"> 第 {{ scope.row.times }} 次 </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="7">
          <el-table ref="ordersTable" :data="orderNos" highlight-current-row :height="tableHeight" @row-click="clickOrderNo">
            <el-table-column label="处方" width="60">
              <template #default="scope"> 第{{ scope.row.orderNo }}张 </template>
            </el-table-column>
            <el-table-column label="金额(￥)" width="80">
              <template #default="scope">
                {{ scope.row.totalFee.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80">
              <template #default="scope">
                <span v-html="colorStatus(scope.row.status)"></span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" icon="el-icon-check" @click="markMzFees" :disabled="scope.row.status"> 生成 </el-button>
                <el-button type="text" icon="el-icon-delete" @click="unmarkMzFees(scope.row)" :disabled="!scope.row.status"> 撤销 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="15">
          <div style="margin-left: 30px">
            <div class="receipt-title">湖南泰和医院处方笺</div>
            <el-divider></el-divider>
            <div class="receipt-head">
              <div>姓名：{{ mzPatient.name }}</div>
              <div>性别：{{ mzPatient.sex }}</div>
              <div>年龄：{{ mzPatient.age }} 岁</div>
            </div>
            <div class="receipt-head">
              <div>门诊号：{{ mzVisit.patientId }}</div>
              <div>科别：{{ mzVisit.visitDeptName }}</div>
              <div class="ellipsis-text">
                临床诊断：<span :title="mzVisit.icdText">{{ mzVisit.icdText }}</span>
              </div>
            </div>
            <div class="receipt-head">
              <div>开具日期：{{ mzVisit.opDay }}</div>
              <div class="ellipsis-text">
                地址：<span :title="mzPatient.address">{{ mzPatient.address }}</span>
              </div>
              <div>电话：{{ mzPatient.phoneNo }}</div>
            </div>
            <el-divider></el-divider>
            <div :style="receiptBoxStyle">
              <div v-for="(item, index) in currentReceipts" :key="index">
                <div class="receipt-item">
                  <div class="w75">
                    <el-checkbox v-model="item.checked">
                      {{ index + 1 }}）{{ item.drugName }}&nbsp; （
                      <span v-if="item.specification">{{ item.specification }}</span>
                      <span v-else>{{ item.drugUnit }}</span>
                      ）
                    </el-checkbox>
                  </div>
                  <div class="w25">&times;&nbsp;&nbsp;&nbsp;{{ item.quantity }}</div>
                </div>
                <div class="receipt-tips">
                  <span v-if="item.drugQuan"> 用法：{{ item.drugQuan }}{{ item.drugUnit }}/次 </span>
                  <span v-if="item.frequency"> {{ item.frequency }} </span>
                  <span v-if="item.orderDays"> {{ item.orderDays }}天 </span>
                  <span v-if="item.supplyCode"> {{ item.supplyCode }} </span>
                  <span v-if="item.instructionText"> 备注：{{ item.instructionText }} </span>
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div class="receipt-head">
              <div style="font-size: 15px">医师：{{ mzVisit.doctorName }} / {{ mzVisit.doctorCode }}</div>
              <div style="font-size: 15px">
                总金额：<span style="font-size: 18px; font-weight: bold">￥{{ totalFee }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-main>

    <el-dialog title="个人信息" v-model="showInsuinfo" width="65%">
      <el-tag>参保信息</el-tag>
      <el-table :data="psnBaseinfo.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 style="height: 16px"></div>
      <el-tag>身份信息</el-tag>
      <el-table :data="psnBaseinfo.idetinfo" stripe height="180">
        <el-table-column label="人员身份类别" prop="psnIdetTypeName"></el-table-column>
        <el-table-column label="人员类别等级" prop="psnTypeLv"></el-table-column>
        <el-table-column label="备注" prop="memo"></el-table-column>
        <el-table-column label="开始时间" prop="begntime"></el-table-column>
        <el-table-column label="结束时间" prop="endtime"></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-container>
</template>

<script>
import { onMounted, ref } from 'vue'
import {
  deleteAllMzReceipts,
  deleteMzReceipt,
  getMzReceipts,
  insertSiMzFees,
  outpatientPreSettlement,
  outpatientRegistration,
  revokeOutpatientFeeDetails,
  revokeOutpatientRegistration,
  uploadOutpatientFeeDetails,
} from '@/api/medical-insurance/si-outpatient'
import { cptInsutype, cptPersType, cptYbState } from '@/utils/computed'
import { ElMessage, ElMessageBox } from 'element-plus'
import store from '@/store'
import { obtainBasicPersonInfo, querySpecialChronicDiseasesAccreditation } from '@/api/medical-insurance/si-query'
import { getMedTypesByFlag } from '@/api/medical-insurance/si-dict'
export default {
  setup() {
    const medType = ref(null)
    const medTypes = ref([])
    const patientId = ref('')
    const times = ref(null)
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 45
    const receiptBoxStyle = {
      height: tableHeight - 200 + 'px',
      overflowY: 'auto',
    }

    const data = ref([])
    const mzPatient = ref({})
    const showInsuinfo = ref(false)
    const psnBaseinfo = ref({})
    const mzVisit = ref({})
    const receipts = ref({})
    const orderNos = ref([])
    const currentReceipts = ref([])
    const totalFee = ref(null)
    const timesTable = ref(null)
    const ordersTable = ref(null)
    const currentOrder = ref({})
    const spcChrDiseAccts = ref([])
    const showSpcChrAccts = ref(false)

    const nullPatientId = () => {
      if (!patientId.value) {
        ElMessage({
          message: '请输入门诊id号！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return true
      }
      return false
    }

    const clearBscData = () => {
      data.value = []
      orderNos.value = []
      currentReceipts.value = []
      mzPatient.value = {}
      mzVisit.value = {}
    }

    const registor = (command) => {
      if (nullPatientId()) {
        return
      }
      clearBscData()
      const param = {
        patNo: patientId.value,
        medType: medType.value,
        times: times.value,
        needSaving: 1,
      }
      if (command === 'execute') {
        obtainBasicPersonInfo(param).then((res) => {
          times.value = res.times
          psnBaseinfo.value = res
          showInsuinfo.value = true
        })
      } else {
        revokeOutpatientRegistration(param).then((res) => {
          ElMessage({
            message: res,
            type: 'success',
            duration: 2000,
            showClose: true,
          })
        })
      }
    }

    const receiptsOpts = (command) => {
      if (nullPatientId()) {
        return
      }
      data.value = []
      const param = {
        patNo: patientId.value,
        times: times.value,
      }
      switch (command) {
        case 'require':
          fetchReceipts(param)
          break
        case 'delete':
          deleteAllMzReceipts(param).then((res) => {
            ElMessage({
              message: res,
              type: 'success',
              duration: 2000,
              showClose: true,
            })
            fetchReceipts(param)
          })
          break
        case 'upload':
          qrySpcChrDiseAcct(param)
          break
        case 'retract':
          revokeOutpatientFeeDetails(param).then((res) => {
            ElMessage({
              message: res,
              type: 'success',
              duration: 2000,
              showClose: true,
            })
          })
          break
      }
    }

    const fetchReceipts = (param) => {
      getMzReceipts(param)
        .then((res) => {
          data.value = res
          setTimeout(() => {
            timesTable.value.setCurrentRow(res[0])
            clickTimes(res[0])
          }, 100)
        })
        .catch(() => {
          currentReceipts.value = []
        })
    }

    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(() => {
            currentOrder.value.status = true
            ElMessage({
              message: '已成功生成门特处方。',
              type: 'success',
              duration: 2500,
              showClose: true,
            })
          })
        })
        .catch(() => {})
    }

    const qrySpcChrDiseAcct = (param) => {
      if (medType.value === '14') {
        querySpecialChronicDiseasesAccreditation(param).then((res) => {
          spcChrDiseAccts.value = res
          showSpcChrAccts.value = true
        })
      } else {
        uploadFees(param)
      }
    }

    const uploadFees = (row) => {
      uploadOutpatientFeeDetails(row).then((res) => {
        times.value = res.times
        showSpcChrAccts.value = false
        mzPreSetl()
      })
    }

    const handleClickInsuinfo = (row) => {
      const param = {
        patNo: patientId.value,
        times: times.value,
        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 clickOrderNo = (row) => {
      currentOrder.value = row
      currentReceipts.value = receipts.value[row.orderNo]
      totalFee.value = row.totalFee.toFixed(2)
    }

    const clickTimes = (row) => {
      mzPatient.value = row.mzPatient
      mzVisit.value = row.mzVisit
      receipts.value = row.mzReceipts
      orderNos.value = row.orderNos
      times.value = row.times
      currentReceipts.value = []
      setTimeout(() => {
        ordersTable.value.setCurrentRow(orderNos.value[0])
        clickOrderNo(orderNos.value[0])
      }, 100)
    }

    const colorStatus = (status) => {
      return status ? '<span style="color: green">已生成</span>' : '<span style="color: red">未生成</span>'
    }

    const unmarkMzFees = (row) => {
      ElMessageBox.confirm('是否将选中处方从门特处方中删除？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          deleteMzReceipt(row).then(() => {
            currentOrder.value.status = false
            ElMessage({
              message: '已成功删除门特处方。',
              type: 'success',
              duration: 2500,
              showClose: true,
            })
          })
        })
        .catch(() => {})
    }

    const mzPreSetl = () => {
      const param = {
        staffId: store.state.user.info.code,
        patNo: patientId.value,
        times: times.value,
      }
      outpatientPreSettlement(param).then((res) => {
        const message = '医保处方总费用：' + res.totalCost + '，医保报销金额：' + res.fundPay + '。'
        ElMessageBox.alert(message, '试算成功', {
          type: 'success',
          showCancelButton: false,
        }).then(() => {})
      })
    }

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

    return {
      medType,
      medTypes,
      patientId,
      cptYbState,
      cptInsutype,
      cptPersType,
      receiptBoxStyle,
      registor,
      receiptsOpts,
      tableHeight,
      markMzFees,
      unmarkMzFees,
      showInsuinfo,
      psnBaseinfo,
      handleClickInsuinfo,
      mzPatient,
      mzVisit,
      receipts,
      orderNos,
      colorStatus,
      clickOrderNo,
      currentReceipts,
      totalFee,
      ordersTable,
      timesTable,
      mzPreSetl,
      data,
      clickTimes,
      spcChrDiseAccts,
      showSpcChrAccts,
      uploadFees,
    }
  },
}
</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;
}
.receipt-item {
  display: flex;
}
.receipt-tips {
  margin: 0 0 10px 100px;
}
.receipt-tips > span {
  margin-right: 15px;
}
.w75 {
  width: 70%;
  font-size: 15px;
}
.w75 * {
  font-size: 15px;
}
.w25 {
  width: 25%;
  font-size: 15px;
  color: #0f5e0f;
  font-weight: bold;
}
</style>
