<template>
  <el-container>
    <el-header height="35px">
      <el-button type="success" @click="feeDtle">费用明细</el-button>
      <el-button type="success" @click="preCalculateCost">医保试算</el-button>
      <el-button type="success" @click="uploadFees">费用上传</el-button>
      <el-button type="warning" :disabled="!isAdmin" @click="cancelFees">取消上传</el-button>
      <el-button type="primary" @click="weiGuiTuiFeiFenXiDialogOpen(true)">违规费用分析</el-button>
      <el-popover placement="left" width="730" trigger="click">
        <template #reference>
          <el-button type="warning" icon="el-icon-circle-close" plain>错误信息 ({{ errorMessages.length }}) </el-button>
        </template>
        <el-tag type="info">错误信息</el-tag>
        <el-divider direction="vertical"></el-divider>
        <el-button type="warning" @click="clearErrorMessages">清除内容</el-button>
        <el-table width="700" max-height="300" class="errTable" :data="errorMessages">
          <el-table-column width="80" property="inpatientNo" label="住院号"></el-table-column>
          <el-table-column width="80" property="patientName" label="姓名"></el-table-column>
          <el-table-column width="80" property="detailSn" label="流水号"></el-table-column>
          <el-table-column width="450" property="msg" label="错误详情"></el-table-column>
        </el-table>
      </el-popover>
      &nbsp;&nbsp;
      <el-tag type="info" size="medium">
        <span style="color: black">￥ {{ patient.totalCharge }}</span>
        |
        <span style="color: orangered">￥ {{ patient.chargeYb }}</span>
      </el-tag>
    </el-header>
    <el-main>
      <el-tag type="info">治疗明细</el-tag><el-tag>合计：￥ {{ fees.xmSum }}</el-tag>
      <el-table :data="fees.xm" stripe :height="feeTableHeight">
        <el-table-column prop="detailSn" label="流水号" width="80"></el-table-column>
        <el-table-column prop="chargeCodeMx" label="院内码" width="100"></el-table-column>
        <el-table-column prop="chargeAmount" label="数量" sortable width="80"></el-table-column>
        <el-table-column prop="chargeFee" label="金额" width="80"></el-table-column>
        <el-table-column prop="chargeDate" label="收费日期"></el-table-column>
        <el-table-column prop="ybCode" label="医保码"></el-table-column>
        <el-table-column prop="chargeName" label="项目名称"></el-table-column>
        <el-table-column prop="ybSelfFlag" label="是否报销" width="80"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleXmSizeChange"
        @current-change="handleCurrentXmChange"
        :current-page="page.xmPage"
        :page-sizes="[10, 30, 50, 70, 100, 300]"
        :page-size="page.xmPageSize"
        layout="total, sizes, prev, pager, next"
        :total="fees.xmTotal"
      >
      </el-pagination>
      <div style="height: 5px"></div>
      <el-tag type="info">药品明细</el-tag><el-tag>合计：￥ {{ fees.ypSum }}</el-tag>
      <el-table :data="fees.yp" stripe :height="feeTableHeight">
        <el-table-column prop="detailSn" label="流水号" width="80"></el-table-column>
        <el-table-column prop="chargeCodeMx" label="院内码" width="100"></el-table-column>
        <el-table-column prop="chargeAmount" label="数量" sortable width="80"></el-table-column>
        <el-table-column prop="chargeFee" label="金额" width="80"></el-table-column>
        <el-table-column prop="chargeDate" label="收费日期"></el-table-column>
        <el-table-column prop="ybCode" label="医保码"></el-table-column>
        <el-table-column prop="chargeName" label="项目名称"></el-table-column>
        <el-table-column prop="ybSelfFlag" label="是否报销" width="80"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleYpSizeChange"
        @current-change="handleCurrentYpChange"
        :current-page="page.ypPage"
        :page-sizes="[10, 30, 50, 70, 100, 300]"
        :page-size="page.ypPageSize"
        layout="total, sizes, prev, pager, next"
        :total="fees.ypTotal"
      >
      </el-pagination>
      <div class="m-wrapper" v-show="showProgress">
        <div class="dj-center-box-wrapper">
          <div class="el-message-box" style="font-size: 13px">
            <div style="background: #409eff; color: white; padding: 7px 10px; font-weight: bold">
              <i class="el-icon-loading"></i>
              上传进度
            </div>
            <div style="padding: 10px">
              <div style="margin-bottom: 10px">{{ uploadIndexText }} ...</div>
              <div style="margin-bottom: 10px" v-show="percentage === 100">上传结束，正在进行费用计算 ...</div>
              <el-progress :text-inside="true" :stroke-width="22" :percentage="percentage" status="success"></el-progress>
              <div style="height: 5px"></div>
            </div>
          </div>
        </div>
      </div>
    </el-main>
    <el-dialog v-model="weiGuiTuiFeiFenXiDialog" title="违规费用分析" :fullscreen="true">
      <wei-gui-fei-yong-fen-xi :init="weiGuiTuiFeiInit" @open="weiGuiTuiFeiOpenDialog" ref="weiGui" :patient="weiGuiJiBenXinXi"></wei-gui-fei-yong-fen-xi>
    </el-dialog>
    <el-dialog v-model="showFeeDetl" title="医保费用明细" :close-on-click-modal="false" fullscreen>
      <MedfeeAnalyse type="unsettled" :timestamp="timestamp" :mdtrt-id="patient.mdtrtId" />
    </el-dialog>
  </el-container>
</template>

<script>
import store from '@/store'
import { computed, onActivated, onDeactivated, onMounted, reactive, ref, watch } from 'vue'
import { fetchNotUploadedFees } from '@/api/yibao/patient'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { nullPatient } from '@/utils/validate'
import { multipleUpload } from '@/api/yibao/yibao'
import { hospitalizationPreSettlement, uploadFeeDetail, revokeUploadFees } from '@/api/medical-insurance/si-inpatient'
import { uploadInjuryFees, cancelInjuryFee, injuryPrecal } from '@/api/medical-insurance/si-injury'
import { setCallback } from '@/utils/websocket'
import { getGreatestRole } from '@/utils/permission'
import { baseinfo } from '@/data/inpatient'
import WeiGuiFeiYongFenXi from '@/components/inpatient/WeiGuiFeiYongFenXi.vue'
import MedfeeAnalyse from '../../../components/medical-insurance/medfee-analyse/Index.vue'
export default {
  components: { WeiGuiFeiYongFenXi, MedfeeAnalyse },
  setup() {
    const feeTableHeight = (store.state.app.windowSize.h - 200) / 2
    const injuryMode = computed(() => {
      return store.state.ptnt.injuryMode
    })
    const isAdmin = getGreatestRole() < 10
    const patient = computed(() => {
      return baseinfo()
    })
    const fees = initFees()
    const page = initPage()
    const fetchProjectFees = () => {
      const param = {
        patNo: patient.value.inpatientNo,
        times: patient.value.admissTimes,
        currentPage: page.xmPage,
        pageSize: page.xmPageSize,
        zdTable: 'zd_charge_item',
        injuryMode: injuryMode.value,
      }
      fetchNotUploadedFees(param).then((res) => {
        fees.xm = res.list
        fees.xmSum = res.sum
        fees.xmTotal = res.totalSize
      })
    }

    const fetchMedicineFees = () => {
      const param = {
        patNo: patient.value.inpatientNo,
        times: patient.value.admissTimes,
        currentPage: page.ypPage,
        pageSize: page.ypPageSize,
        zdTable: 'yp_zd_dict',
        injuryMode: injuryMode.value,
      }
      fetchNotUploadedFees(param).then((res) => {
        fees.yp = res.list
        fees.ypSum = res.sum
        fees.ypTotal = res.totalSize
      })
    }

    const clearFees = () => {
      fees.xm = []
      fees.yp = []
      fees.xmSum = '0.00'
      fees.ypSum = '0.00'
      fees.xmTotal = 0
      fees.ypTotal = 0
    }

    const actived = ref(false)

    onActivated(() => {
      actived.value = true
      store.commit('app/setCurrentPageName', 'inHospFeeUpload')
      setCallback(socketCallback)
    })

    onDeactivated(() => {
      actived.value = false
      store.commit('app/setCurrentPageName', '')
    })

    watch(
      () => patient.value.inpatientNo,
      () => {
        if (actived.value) {
          if (patient.value.inpatientNo) {
            fetchProjectFees()
            fetchMedicineFees()
            weiGuiTuiFeiFenXiDialogOpen(false)
          } else {
            clearFees()
          }
        }
      }
    )

    const errorMessages = ref([])
    const clearErrorMessages = () => {
      errorMessages.value = []
    }
    const handleXmSizeChange = (val) => {
      page.xmPageSize = val
      fetchProjectFees()
    }
    const handleCurrentXmChange = (val) => {
      page.xmPage = val
      fetchProjectFees()
    }
    const handleYpSizeChange = (val) => {
      page.ypPageSize = val
      fetchMedicineFees()
    }
    const handleCurrentYpChange = (val) => {
      page.ypPage = val
      fetchMedicineFees()
    }

    const preCalculateCost = () => {
      if (nullPatient()) return
      if (injuryMode.value) {
        injuryPrecal(patient.value).then((res) => {
          patient.value.chargeYb = res.fundPay
          ElMessageBox.alert(res, {
            type: 'success',
            confirmButtonText: '确定',
          })
        })
      } else {
        hospitalizationPreSettlement(patient.value).then((res) => {
          ElMessageBox.alert(res, {
            type: 'success',
            confirmButtonText: '确定',
          })
        })
      }
    }

    const patientIndex = ref(1)
    const showProgress = ref(false)
    const percentage = ref(0)

    const selections = computed(() => {
      return store.state.ptnt.selections
    })

    const uploadFees = () => {
      if (selections.value.length === 0) {
        if (nullPatient()) return
      }
      showProgress.value = true
      if (injuryMode.value) {
        const sid = store.getters['user/sid']
        patient.value.sid = sid
        uploadInjuryFees(patient.value)
          .then((res) => {
            fetchProjectFees()
            fetchMedicineFees()
            showProgress.value = false
            percentage.value = 0
            patient.value.chargeYb = res.fundPay
            ElMessageBox.alert(res, '成功', {
              type: 'success',
              confirmButtonText: '确定',
            })
          })
          .catch(() => {
            showProgress.value = false
            percentage.value = 0
            fetchProjectFees()
            fetchMedicineFees()
          })
      } else {
        doSingleUpload()
      }
    }

    const doMultipleUpload = () => {
      selections.value.forEach((item) => {
        item.sid = store.getters['user/sid']
      })
      multipleUpload(selections.value)
        .then((res) => {
          ElMessage({
            message: '处理完成。',
            type: 'success',
            duration: 2500,
            showClose: true,
          })
          showProgress.value = false
          percentage.value = 0
        })
        .catch(() => {
          showProgress.value = false
          percentage.value = 0
        })
    }

    const doSingleUpload = () => {
      const param = {
        inpatientNo: patient.value.inpatientNo,
        admissTimes: patient.value.admissTimes,
        ledgerSn: patient.value.ledgerSn,
        sid: store.getters['user/sid'],
      }
      uploadFeeDetail(param)
        .then((res) => {
          fetchProjectFees()
          fetchMedicineFees()
          showProgress.value = false
          percentage.value = 0
          ElMessageBox.alert(res, '成功', {
            type: 'success',
            confirmButtonText: '确定',
          })
          store.commit('app/closeJdt')
        })
        .catch(() => {
          fetchProjectFees()
          fetchMedicineFees()
          showProgress.value = false
          percentage.value = 0
        })
    }

    const socketCallback = (data) => {
      switch (data.name) {
        case 'uploadFeeResponse':
          errorMessages.value.push(data)
          break
        case 'updatePatientIndex':
          patientIndex.value = data.val
          percentage.value = 0
          break
        case 'updateProgress':
          percentage.value = data.percentage
          break
        default:
          break
      }
    }

    const uploadIndexText = computed(() => {
      let total = selections.value.length
      if (total === 0) {
        total = 1
      }
      return '共 ' + total + ' 人，正在处理第 ' + patientIndex.value + ' 人'
    })
    const cancelFees = () => {
      ElMessageBox.confirm('是否确定取消此患者已上传的费用？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '放弃',
      })
        .then(() => {
          if (injuryMode.value) {
            cancelInjuryFee(patient.value).then(() => {
              ElMessage({
                message: '操作成功。',
                type: 'success',
                duration: 2500,
                showClose: true,
              })
              fetchProjectFees()
              fetchMedicineFees()
            })
          } else {
            revokeUploadFees(patient.value).then(() => {
              ElMessage({
                message: '操作成功。',
                type: 'success',
                duration: 2500,
                showClose: true,
              })
              fetchProjectFees()
              fetchMedicineFees()
            })
          }
        })
        .catch(() => {})
    }

    const showFeeDetl = ref(false)
    const timestamp = ref(0)
    const feeDtle = () => {
      if (nullPatient()) {
        return
      }
      timestamp.value = new Date().getTime()
      showFeeDetl.value = true
    }

    ///////////////////////////////////////////// 违规退费分析 /////////////////////////////////////////////////////////////////////////
    const weiGuiTuiFeiInit = ref(0)
    const weiGuiTuiFeiFenXiDialog = ref(true)

    const weiGuiJiBenXinXi = ref({})

    const weiGui = ref()

    const weiGuiTuiFeiFenXiDialogOpen = (val) => {
      weiGuiTuiFeiInit.value += 1
      weiGuiJiBenXinXi.value.deptCode = ''
      weiGuiJiBenXinXi.value.inpatientNo = typeof patient.value.inpatientNo === 'undefined' ? '' : patient.value.inpatientNo
      weiGuiJiBenXinXi.value.openDialog = val
    }

    const weiGuiTuiFeiOpenDialog = (val) => {
      weiGuiTuiFeiFenXiDialog.value = val
    }

    onMounted(() => {
      if (patient.value.inpatientNo) {
        fetchProjectFees()
        fetchMedicineFees()
      }
      ElNotification({
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'success',
        message: ` 
            1、如果上传不成功或者费用不一致，那么请医保科取消上传，重新上传费用。<br>          
            2、退药品的话（长期医嘱撤销就可以了，如果不能撤销提单子）（临嘱的话使用医保入院登记里面的【医嘱退费】，然后护士执行这个条医嘱就可以了）。<br>
            3、全部的项目都要用本系统来退费。<br>你们终于可以不用向信息科打电话了 ヾ(✿ﾟ▽ﾟ)ノ`,
      })
    })
    return {
      isAdmin,
      patient,
      fees,
      errorMessages,
      clearErrorMessages,
      page,
      handleXmSizeChange,
      handleCurrentXmChange,
      handleYpSizeChange,
      handleCurrentYpChange,
      preCalculateCost,
      percentage,
      uploadFees,
      showProgress,
      patientIndex,
      uploadIndexText,
      cancelFees,
      feeDtle,
      showFeeDetl,
      timestamp,
      feeTableHeight,
      weiGuiTuiFeiFenXiDialog,
      weiGuiTuiFeiFenXiDialogOpen,
      weiGuiJiBenXinXi,
      weiGuiTuiFeiInit,
      weiGuiTuiFeiOpenDialog,
      weiGui,
    }
  },
}

function initFees() {
  const fees = reactive({
    xmSum: '0.00',
    ypSum: '0.00',
    xm: [],
    yp: [],
    xmTotal: 0,
    ypTotal: 0,
  })
  return fees
}

function initPage() {
  const page = reactive({
    xmPage: 1,
    xmPageSize: 10,
    ypPage: 1,
    ypPageSize: 10,
  })
  return page
}
</script>

<style scoped>
.m-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 8888;
  background-color: rgba(0, 0, 0, 0.6);
}
.dj-center-box-wrapper {
  position: fixed;
  inset: 0px;
  text-align: center;
}
.dj-center-box-wrapper::after {
  content: '';
  display: inline-block;
  height: 100%;
  width: 0px;
  vertical-align: middle;
}
</style>
