<template>
  <page-layer>
    <template #header>
      <el-select v-model="slctSetlPrm.mode" style="width: 146px" @change="handleModeChange">
        <el-option :value="1" label="本院医保与医保中心"></el-option>
        <el-option :value="2" label="本院医保与本院HIS"></el-option>
      </el-select>
      <el-select v-model="slctSetlPrm.clrType" placeholder="清算类别" style="width: 100px" @change="setlinfos = []">
        <el-option v-for="item in clrTypes" :key="item.code" :value="item.code" :label="item.name" :disabled="item.disabled"></el-option>
      </el-select>
      <el-date-picker v-model="dateRange" type="daterange" :shortcuts="setlShtcuts" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" style="width: 220px" @change="setlinfos = []"></el-date-picker>
      <el-select v-model="slctSetlPrm.insutype" placeholder="险种类型" filterable clearable style="width: 120px"
        @change="currentPage = 1">
        <el-option v-for="item in insutypes" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-select v-model="slctSetlPrm.setlOptins" placeholder="清算机构" filterable clearable
        :disabled="setlinfos.length === 0" style="width: 120px" @change="currentPage = 1">
        <el-option v-for="item in optins" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-input v-model="patNo" clearable placeholder="住院号\门诊号\姓名" style="width: 140px" />
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Search" @click="getSetlInfos">检索</el-button>
      <el-button type="primary" icon="Coin" @click="bfrChkSetl">对总账</el-button>
      <el-button type="primary" icon="DataAnalysis" @click="setlDtlCheck">明细对账</el-button>
      <el-button type="warning" icon="Download" @click="exportExcel">导出Excel</el-button>
    </template>
    <template #main>
      <el-table :data="cptSetlinfos.slice(pageSize * (currentPage - 1), pageSize * currentPage)" stripe
        :height="tableHeight" highlight-current-row>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="patNo" label="住院号/门诊号"></el-table-column>
        <el-table-column prop="times" label="次数"></el-table-column>
        <el-table-column prop="psnName" label="姓名"></el-table-column>
        <el-table-column prop="gendName" label="性别"></el-table-column>
        <el-table-column prop="brdy" label="出生日期"></el-table-column>
        <el-table-column prop="insutypeName" label="险种类型"></el-table-column>
        <el-table-column prop="psnTypeName" label="人员类别"></el-table-column>
        <el-table-column prop="mdtrtId" label="就诊ID"></el-table-column>
        <el-table-column prop="setlId" label="结算ID"></el-table-column>
        <el-table-column prop="setlTime" label="结算时间"></el-table-column>
        <el-table-column prop="medTypeName" label="医疗类别"></el-table-column>
        <el-table-column prop="medfeeSumamt" label="总费用"></el-table-column>
        <el-table-column prop="fundPaySumamt" label="报销金额"></el-table-column>
        <el-table-column prop="acctPay" label="个人账户支出"></el-table-column>
        <el-table-column prop="psnCashPay" label="个人现金支出"></el-table-column>
        <el-table-column prop="clrOptinsName" label="清算机构"></el-table-column>
        <el-table-column fixed="right" label="操作" :width="ldWidth" header-align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="setlListInfo(scope.row)">结算单</el-button>
            <el-button type="primary" size="small" @click="selectSetlDetail(scope.row)">结算明细</el-button>
            <el-button v-if="mzFlag === '11'" type="primary" size="small" @click="selectBlInfo(scope.row)">门诊病历
            </el-button>
            <el-button type="primary" size="small" @click="selectJyjcInfo(scope.row)">检验检查
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[15, 30, 45, 60]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="cptSetlinfos.length" style="margin-top: 5px"></el-pagination>
      <el-dialog v-model="showSetlDtlCheckRslt" title="明细对账结果" :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-table :data="setlDtlCheckRslt" stripe :height="300" highlight-current-row>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column label="就诊ID">
            <template #default="scope">
              {{ scope.row.visitId || scope.row.mdtrtId}}
            </template>
          </el-table-column>
          <el-table-column prop="setlId" label="结算ID"></el-table-column>
          <el-table-column prop="msgId" label="结算报文ID"></el-table-column>
          <el-table-column prop="memo" label="对账结果"></el-table-column>
          <el-table-column label="总费用">
            <template #default="scope">
              <span v-html="scope.row.medfeeSumamt"></span>
            </template>
          </el-table-column>
          <el-table-column label="报销金额">
            <template #default="scope">
              <span v-html="scope.row.fundPaySumamt"></span>
            </template>
          </el-table-column>
          <el-table-column>
            <template #default="scope">
              <el-button text icon="Document" @click="getSetlinfo(scope.row)">结算信息</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog v-model="showSetlinfo" title="结算信息" :close-on-click-modal="false" width="70%">
        <Setlinfo :setlinfo="setlinfo" />
      </el-dialog>
      <el-dialog v-model="showSetlPrescription" title="结算详情" :close-on-click-modal="false" width="82%">
        <el-table :data="setlDetails" stripe :height="500" highlight-current-row>
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column prop="mdtrtId" label="就诊ID"></el-table-column>
          <el-table-column prop="setlId" label="结算ID" width="80"></el-table-column>
          <el-table-column prop="hilistName" label="收费医保目录名称" width="280" align="left" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="feeOcurTime" label="发生时间" width="120" sortable></el-table-column>
          <el-table-column prop="totalFee" label="费用" sortable></el-table-column>
          <el-table-column prop="pric" label="单价" sortable></el-table-column>
          <el-table-column prop="cnt" label="数量" sortable></el-table-column>
          <el-table-column prop="chrgitmLvName" label="收费目录等级"></el-table-column>
          <el-table-column prop="bilgDeptName" label="开单科室"></el-table-column>
          <el-table-column prop="bilgDrName" label="开单医生"></el-table-column>
          <el-table-column prop="opterName" label="经办人"></el-table-column>
          <el-table-column prop="optTime" label="经办时间" width="120"></el-table-column>
        </el-table>
      </el-dialog>
      <el-dialog v-model="showSetlList" title="医保结算单" :close-on-click-modal="false" fullscreen>
        <div style="width: 856px; padding: 20px; background: white; text-align: center">
          <div style="width: 100%; text-align: center; font-size: 22px; font-weight: bold; margin-bottom: 4px">
            {{ listTitle }}
          </div>
          <div style="width: 100%; display: flex; font-size: 15px; margin-bottom: 8px">
            <div style="width: 50%; text-align: left">统筹区划：{{ setlListDetail.insuplcAdmdvsName }}</div>
            <div style="width: 50%; text-align: right">打印日期：{{ nowdate }}</div>
          </div>
          <InpatientSetlList v-if="settleType === '21'" :setlinfo="setlListDetail" />
          <OtherOutpatientSetlList v-if="settleType === '11' && !isEmployeeOutpatient" :setlinfo="setlListDetail" />
          <EmployeeOutpatientSetlList v-if="settleType === '11' && isEmployeeOutpatient" :setlinfo="setlListDetail" />
        </div>
      </el-dialog>
      <el-dialog v-model="showBl" title="病历详情" :close-on-click-modal="false" width="70%">
        <div id="reportDetail" style="width: 100%; height: 100%; padding: 0 2px">
          <el-row :gutter="6">
            <el-col :span="6">门诊号：{{ blInfoList.patientId }}</el-col>
            <el-col :span="6">次数：{{ blInfoList.times }}</el-col>
            <el-col :span="6">病历号：{{ blInfoList.emrNo }}</el-col>
            <el-col :span="6">就诊时间：{{ blInfoList.visitDate }}</el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="24">主诉：{{ blInfoList.emrCC }}</el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="24">现病史：{{ blInfoList.emrHpi }}</el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="24">既往史：{{ blInfoList.emrPs }}</el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="24">体格检查：{{ blInfoList.emrPe }}</el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="24">辅助检查：{{ blInfoList.emrFzjc }}</el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="24">治疗过程：
              <p v-html="blInfoList.emrProcess"></p>
            </el-col>
          </el-row>
          <div style="margin: 5px 0; border-top: 1px solid gray"></div>
          <el-row :gutter="6">
            <el-col :span="6">科室：{{ blInfoList.deptName }}</el-col>
            <el-col :span="6">医生：{{ blInfoList.doctorName }}</el-col>
            <el-col :span="12">初步诊断：{{ blInfoList.tentativeDiagnosis }}</el-col>
          </el-row>
        </div>
      </el-dialog>
      <el-dialog v-model="showJyjc" title="检验检查" :close-on-click-modal="false" fullscreen destroy-on-close>
        <JyjcPage :jyjcInfo="jyjcInfo" />
      </el-dialog>
    </template>
  </page-layer>
</template>

<script>
import { computed, onMounted, reactive, ref } from '@vue/runtime-core'
import store from '@/store'
import { getClrTypes, getInsutypes } from '@/api/medical-insurance/si-dict'
import { setlShtcuts } from '@/data/shortcuts'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  institutionSettlementDetailCheck,
  institutionSettlementLedgerCheck,
  selectSetlinfos,
  selectSetlPrescription,
  queryBlInfo
} from '@/api/medical-insurance/si-manage'
import { querySettlementInfo, querySiSetlList } from '@/api/medical-insurance/si-query'
import {formatDate, formatYear, getDate} from '@/utils/date'
import Setlinfo from '../../../components/medical-insurance/setlinfo/Index.vue'
import InpatientSetlList from '@/components/medical-insurance/settle-detail-list/InpatientSetlList.vue'
import OtherOutpatientSetlList from '@/components/medical-insurance/settle-detail-list/OtherOutpatientSetlList.vue'
import EmployeeOutpatientSetlList
  from '@/components/medical-insurance/settle-detail-list/EmployeeOutpatientSetlList.vue'
import JyjcPage from '@/components/medical-insurance/inspect/InspectionReport.vue'
import PageLayer from "@/layout/PageLayer";
import {Export} from "@/utils/ExportExcel";

export default {
  components: {
    PageLayer,
    Setlinfo,
    JyjcPage,
    InpatientSetlList,
    OtherOutpatientSetlList,
    EmployeeOutpatientSetlList,
  },
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 55
    const insutypes = ref([])
    const clrTypes = ref([])
    const dateRange = ref(null)
    const setlinfos = ref([])
    const optins = ref([])
    const patNo = ref('')
    const slctSetlPrm = reactive({
      mode: 1,
      insutype: '',
      clrType: null,
      setlOptins: null,
      stmtBegndate: null,
      stmtEnddate: null,
      patNo: ''
    })
    const pageSize = ref(30)
    const currentPage = ref(1)
    const handleSizeChange = (val) => {
      pageSize.value = val
    }
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }
    const cptSetlinfos = computed(() => {
      return setlinfos.value.filter((item) => {
        if (!slctSetlPrm.insutype && !slctSetlPrm.setlOptins) {
          return true
        }

        if (slctSetlPrm.insutype && !slctSetlPrm.setlOptins) {
          return item.insutype === slctSetlPrm.insutype
        }

        if (!slctSetlPrm.insutype && slctSetlPrm.setlOptins) {
          return item.clrOptins === slctSetlPrm.setlOptins
        }

        return item.insutype === slctSetlPrm.insutype && item.clrOptins === slctSetlPrm.setlOptins
      })
    })
    const mzFlag = ref('')
    const ldWidth = ref(160)
    const getSetlInfos = () => {
      if (!slctSetlPrm.clrType) {
        ElMessage({
          message: '请选择结算类别！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      if (!dateRange.value) {
        ElMessage({
          message: '请选择日期范围！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      if (slctSetlPrm.clrType === '11' || slctSetlPrm.clrType === '14' || slctSetlPrm.clrType === '53' || slctSetlPrm.clrType === '9901') {
        mzFlag.value = '11'
      } else {
        mzFlag.value = '21'
      }
      if (mzFlag.value === '11') {
        ldWidth.value = 320
      } else {
        ldWidth.value = 240
      }
      slctSetlPrm.stmtBegndate = formatDate(dateRange.value[0])
      slctSetlPrm.stmtEnddate = formatDate(dateRange.value[1])
      slctSetlPrm.patNo = patNo.value
      selectSetlinfos(slctSetlPrm)
        .then((res) => {
          setlinfos.value = res.list
          optins.value = res.optins
        })
        .catch(() => {
          setlinfos.value = []
          optins.value = []
        })
    }

    const bfrChkSetl = () => {
      if (setlinfos.value.length === 0) {
        ElMessage({
          message: '没有数据！请先检索。',
          type: 'warning',
          showClose: true,
        })
        return
      }
      if (!slctSetlPrm.insutype && slctSetlPrm.mode === 1) {
        ElMessage({
          message: '对总账时险种类型不能为空！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      if (!slctSetlPrm.setlOptins && slctSetlPrm.mode === 1) {
        ElMessage({
          message: '请选择清算机构！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      institutionSettlementLedgerCheck(slctSetlPrm).then((res) => {
        ElMessageBox.alert(res, {
          type: 'success',
        })
      })
    }

    const setlDtlCheckRslt = ref([])
    const showSetlDtlCheckRslt = ref(false)
    const setlDtlCheck = () => {
      if (slctSetlPrm.mode === 2 && slctSetlPrm.clrType === '11') {
        ElMessage({
          message: '门诊暂不支持HIS与医保的明细对账。',
          type: 'warning',
          showClose: true
        })
        return;
      }
      if (setlinfos.value.length === 0) {
        ElMessage({
          message: '没有数据！请先检索。',
          type: 'warning',
          showClose: true,
        });
        return;
      }
      if (slctSetlPrm.insutype && slctSetlPrm.mode === 1) {
        ElMessage({
          message: '明细对账时请不要选择险种类型！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      if (!slctSetlPrm.setlOptins && slctSetlPrm.mode === 1) {
        ElMessage({
          message: '请选择清算机构！',
          type: 'warning',
          showClose: true,
        })
        return
      }
      institutionSettlementDetailCheck(slctSetlPrm).then((res) => {
        setlDtlCheckRslt.value = res
        showSetlDtlCheckRslt.value = true
      })
    }

    const setlinfo = ref({})
    const showSetlinfo = ref(false)
    const getSetlinfo = (row) => {
      const param = {
        psnNo: row.psnNo,
        mdtrtId: row.mdtrtId,
      }
      querySettlementInfo(param).then((res) => {
        setlinfo.value = res
        showSetlinfo.value = true
      })
    }

    const exportExcel = () => {
      if (cptSetlinfos.value.length === 0) {
        ElMessage({
          message: '没有可以导出的数据。',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      const title = {
        patNo: '住院号/门诊号',
        times: '次数',
        psnName: '姓名',
        gendName: '性别',
        brdy: '出生日期',
        insutypeName: '险种类型',
        psnTypeName: '人员类别',
        mdtrtId: '就诊ID',
        setlId: '结算ID',
        setlTime: '结算时间',
        medTypeName: '医疗类别',
        medfeeSumamt: '总费用',
        fundPaySumamt: '报销金额',
        acctPay: '个人账户支出',
        psnCashPay: '个人现金支出',
        clrOptinsName: '清算机构',
      }
      const prefix = slctSetlPrm.stmtBegndate + '至' + slctSetlPrm.stmtEnddate
      Export(cptSetlinfos.value, title, `【${prefix}】结算与对账导出`)
    }

    // -----------------------查询结算单明细----------------------------
    const setlDetails = ref([])
    const showSetlPrescription = ref(false)

    const selectSetlDetail = (row) => {
      selectSetlPrescription(row.mdtrtId)
        .then((res) => {
          setlDetails.value = res
          showSetlPrescription.value = true
        })
        .catch(() => {
          setlDetails.value = []
        })
    }

    // --------------------------查询结算清单-------------------------------------
    const showSetlList = ref(false)
    const isEmployeeOutpatient = ref(false)
    const isProvincial = ref(false)
    const nowdate = getDate()
    const settleType = ref('21')
    const setlListDetail = ref({})
    const listTitle = computed(() => {
      if (settleType.value === '21') {
        return '湖南省长沙市住院费用结算单'
      }
      if (!isEmployeeOutpatient.value) {
        return '湖南省长沙市(普通、特殊)门诊费用结算单'
      }
      return isProvincial.value ? '湖南省省本级门诊统筹费用结算单' : '湖南省长沙市门诊统筹费用结算单'
    })
    const setlListInfo = (row) => {
      settleType.value = row.setlType
      isEmployeeOutpatient.value = row.insutype === '310'
      isProvincial.value = row.insuplcAdmdvs === '439900'
      const params = {
        type: row.setlType,
        patNo: row.patNo,
        label: row.setlId + '_' + row.times + '_' + row.ledgerSn,
      }
      querySiSetlList(params).then((res) => {
        setlListDetail.value = res
        showSetlList.value = true
      })
    }

    // ---------------------------查询病历明细----------------------------------------------
    const showBl = ref(false)
    const blInfoList = ref({})
    const selectBlInfo = (row) => {
      queryBlInfo(row.patNo, row.times).then((res) => {
        if (!res || res.length === 0) {
          ElMessage({
            message: '没有病历报告数据',
            type: 'warning',
            duration: 2000,
            showClose: true,
          })
          return
        }
        blInfoList.value = res
        showBl.value = true
      })
    }

    // ---------------------------查询检验检查----------------------------------------------
    const showJyjc = ref(false)
    const jyjcInfo = ref({})
    const selectJyjcInfo = (row) => {
      if (mzFlag.value === '11') {
        jyjcInfo.value.type = 0
      } else {
        jyjcInfo.value.type = 1
      }
      jyjcInfo.value.content = row.patNo
      jyjcInfo.value.start = slctSetlPrm.stmtBegndate
      jyjcInfo.value.end = slctSetlPrm.stmtEnddate
      showJyjc.value = true
    }

    const handleModeChange = (val) => {
      if (slctSetlPrm.clrType !== '11' && slctSetlPrm.clrType !== '21') {
        slctSetlPrm.clrType = null
      }
      clrTypes.value.forEach(item => {
        if (item.code !== '11' && item.code !== '21') {
          item.disabled = val === 2
        }
      });
    }

    onMounted(() => {
      getInsutypes().then((res) => {
        insutypes.value = res
        getClrTypes().then((res2) => {
          clrTypes.value = res2
        })
      })
    })

    return {
      tableHeight,
      insutypes,
      clrTypes,
      dateRange,
      nowdate,
      patNo,
      listTitle,
      slctSetlPrm,
      setlShtcuts,
      setlinfos,
      cptSetlinfos,
      setlDetails,
      showSetlPrescription,
      selectSetlDetail,
      pageSize,
      currentPage,
      setlDtlCheckRslt,
      optins,
      showSetlDtlCheckRslt,
      setlinfo,
      showSetlinfo,
      getSetlinfo,
      setlListInfo,
      showSetlList,
      isEmployeeOutpatient,
      settleType,
      setlListDetail,
      mzFlag,
      ldWidth,
      showBl,
      blInfoList,
      showJyjc,
      jyjcInfo,
      exportExcel,
      selectJyjcInfo,
      selectBlInfo,
      handleCurrentChange,
      handleSizeChange,
      getSetlInfos,
      bfrChkSetl,
      setlDtlCheck,
      handleModeChange,
    }
  },
}

function calSumamt(list) {
  let medSum = 0
  let fundSum = 0
  let acctSum = 0
  let psnCashPay = 0
  list.forEach((item) => {
    medSum += item.medfeeSumamt
    fundSum += item.fundPaySumamt
    acctSum += item.acctPay
    psnCashPay += item.psnCashPay
  })
  medSum = medSum.toFixed(2)
  fundSum = fundSum.toFixed(2)
  acctSum = acctSum.toFixed(2)
  psnCashPay = psnCashPay.toFixed(2)
  return { medSum, fundSum, acctSum, psnCashPay }
}
</script>

<style scoped>
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center;
}
</style>