<template>
  <page-layer>
    <template #header>
      <span style="margin-left: 0">日期范围：</span>
      <el-date-picker
          v-model="requestParam.datePeriod"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
          style="width: 240px"
      >
      </el-date-picker>
      <span>科室：</span>
      <el-select v-model="requestParam.depts" multiple collapse-tags style="width: 245px" placeholder="请选择" @change="handleSelect">
        <el-checkbox v-model="data.selectAll" @change="selectAllWards" style="float: right; margin-right: 20px">全选</el-checkbox>
        <el-option v-for="item in data.allWards" :key="item.code" :value="item.code" :label="item.name"></el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 10px" icon="Search" @click="queryDeptData"> 查询 </el-button>
      <el-button type="primary" icon="Upload" @click="exportExcel(1)"> 导出 Excel </el-button>
    </template>
    <template #main>
      <el-table
          :data="data.deptEarn.list.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
          stripe
          highlight-current-row
          empty-text="没有数据"
          :height="mainTableHeight"
          @row-dblclick="queryDoctorData"
      >
        <el-table-column prop="deptName" label="科室" sortable></el-table-column>
        <el-table-column prop="doctorName" label="姓名"></el-table-column>
        <el-table-column prop="doctorCode" label="编号"></el-table-column>
        <el-table-column prop="totalCharge" label="营收额" sortable></el-table-column>
      </el-table>
      <div style="margin: 5px 10px; display: flex">
        <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"
            background
            :total="data.deptEarn.list.length"
        >
        </el-pagination>
        <el-tag type="danger" style="margin-left: 30px; font-size: 14px; font-weight: bold"> 合计：￥{{ data.deptEarn.sum }} </el-tag>
      </div>
      <div v-show="showDoctorEarn" class="wrapper">
        <div class="center-box" style="width: 75%">
          <div>
            <el-tag type="success" effect="dark">{{ doctorEarnTitle }}</el-tag>
            <el-button type="warning" icon="Close" style="margin-left: 10px" @click="showDoctorEarn = false"> 关闭 </el-button>
            <el-button type="primary" icon="Upload" @click="exportExcel(2)"> 导出 Excel </el-button>
          </div>
          <el-table :data="data.doctorEarn.list" stripe highlight-current-row :height="mainTableHeight - 150" empty-text="没有数据" @row-dblclick="queryPatientBill">
            <el-table-column prop="inpatientNo" label="住院号"></el-table-column>
            <el-table-column prop="admissTimes" label="住院次数"></el-table-column>
            <el-table-column prop="patientName" label="姓名"></el-table-column>
            <el-table-column prop="chargeFee" label="发生费用" sortable></el-table-column>
          </el-table>
          <el-tag type="danger" style="margin-top: 15px; font-size: 14px; font-weight: bold" v-show="data.doctorEarn.sum > 0"> 合计：￥{{ data.doctorEarn.sum }} </el-tag>
        </div>
      </div>
      <div v-show="showPatientBill" class="wrapper">
        <div class="center-box" style="width: 50%">
          <div>
            <el-tag type="success" effect="dark">{{ patientBillTitle }}</el-tag>
            <el-button type="warning" icon="Close" style="margin-left: 10px" @click="showPatientBill = false"> 关闭 </el-button>
            <el-button type="primary" icon="Upload" @click="exportExcel(3)"> 导出 Excel </el-button>
          </div>
          <el-table :data="data.patientBill.list" stripe highlight-current-row :height="mainTableHeight - 200" empty-text="没有数据">
            <el-table-column prop="chargeName" label="项目/药品"></el-table-column>
            <el-table-column prop="orderNo" label="医嘱号"></el-table-column>
            <el-table-column prop="amount" label="数量"></el-table-column>
            <el-table-column prop="chargeFee" label="金额" sortable></el-table-column>
          </el-table>
          <el-tag type="danger" style="margin-top: 15px; font-size: 14px; font-weight: bold" v-show="data.patientBill.sum > 0"> 合计：￥{{ data.patientBill.sum }} </el-tag>
        </div>
      </div>
    </template>
  </page-layer>
</template>

<script>
import store from '@/store'
import {computed, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {getAllWards, getDeptEarn, getDoctorEarn, getPatientBill} from '@/api/reports/dept-period-report'
import {createWorkSheet, writeExcelFile} from '@/utils/excel'
import {formatDate, getOneMonthOffset} from '@/utils/date'
import {shortcuts} from '@/data/shortcuts'
import PageLayer from "@/layout/PageLayer";

export default {
  components: {PageLayer},
  setup() {
    const windowSize = store.state.app.windowSize
    const requestParam = initRequestParam()
    const { data, doctorEarnTitle, patientBillTitle } = initData()
    const { showDoctorEarn, showPatientBill } = initVisibilities()

    const mainTableHeight = windowSize.h - 50

    const handleSelect = (val) => {
      data.selectAll = val.length === data.allWards.length
    }
    const selectAllWards = () => {
      requestParam.depts = []
      if (data.selectAll) {
        data.allWards.forEach((item) => {
          requestParam.depts.push(item.code)
        })
      } else {
        requestParam.depts = []
      }
    }

    const pageSize = ref(15)
    const currentPage = ref(1)
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }
    const handleSizeChange = (val) => {
      pageSize.value = val
    }

    const queryDeptData = () => {
      if (requestParam.depts.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请先选择要查询的科室！',
          showClose: true,
        })
      } else {
        requestParam.start = formatDate(requestParam.datePeriod[0])
        requestParam.end = formatDate(requestParam.datePeriod[1])
        getDeptEarn(requestParam).then((res) => {
          data.deptEarn = res
        })
      }
    }

    const queryDoctorData = (row) => {
      row.start = requestParam.start
      row.end = requestParam.end
      getDoctorEarn(row).then((res) => {
        data.doctorEarn = res
        showDoctorEarn.value = true
      })
    }

    const queryPatientBill = (row) => {
      row.start = requestParam.start
      row.end = requestParam.end
      getPatientBill(row).then((res) => {
        data.patientBill = res
        showPatientBill.value = true
      })
    }

    const exportExcel = (flag) => {
      if (flag === 1 && data.deptEarn.list.length > 0) {
        store.commit('app/setLoading', true)
        setTimeout(() => {
          const title = {
            deptCode: '科室编码',
            deptName: '科室名称',
            doctorCode: '医生编号',
            doctorName: '医生姓名',
            totalCharge: '营收额',
          }
          const fields = ['deptCode', 'deptName', 'doctorCode', 'doctorName', 'totalCharge']
          const workSheet = createWorkSheet(data.deptEarn.list, fields, title)
          const fileName = '科室时段报表（' + requestParam.start + ' - ' + requestParam.end + '）.xlsx'
          writeExcelFile(workSheet, fileName)
        }, 50)
      } else if (flag === 2 && data.doctorEarn.list.length > 0) {
        store.commit('app/setLoading', true)
        setTimeout(() => {
          const title = {
            deptCode: '科室编码',
            deptName: '科室名称',
            doctorCode: '医生编号',
            doctorName: '医生姓名',
            inpatientNo: '住院号',
            admissTimes: '住院次数',
            patientName: '姓名',
            chargeFee: '发生费用',
          }
          const fields = ['deptCode', 'deptName', 'doctorName', 'doctorCode', 'inpatientNo', 'admissTimes', 'patientName', 'chargeFee']
          const workSheet = createWorkSheet(data.doctorEarn.list, fields, title)
          const fileName = '医生报表（' + data.doctorEarn.doctorName + '）（' + requestParam.start + ' - ' + requestParam.end + '）.xlsx'
          writeExcelFile(workSheet, fileName)
        }, 50)
      } else if (flag === 3 && data.patientBill.list.length > 0) {
        store.commit('app/setLoading', true)
        setTimeout(() => {
          const title = {
            chargeName: '项目/药品名称',
            orderNo: '医嘱号',
            amount: '数量',
            chargeFee: '金额',
          }
          const fields = ['chargeName', 'orderNo', 'amount', 'chargeFee']
          const workSheet = createWorkSheet(data.patientBill.list, fields, title)
          const fileName = '患者费用报表（' + data.patientBill.patientName + '）（' + requestParam.start + ' - ' + requestParam.end + '）.xlsx'
          writeExcelFile(workSheet, fileName)
        }, 50)
      } else {
        store.commit('app/setLoading', false)
        ElMessage({
          type: 'warning',
          message: '没有数据！',
          showClose: true,
        })
      }
    }
    return {
      windowSize,
      shortcuts,
      mainTableHeight,
      showDoctorEarn,
      showPatientBill,
      requestParam,
      handleSelect,
      selectAllWards,
      data,
      queryDeptData,
      queryDoctorData,
      queryPatientBill,
      exportExcel,
      doctorEarnTitle,
      patientBillTitle,
      pageSize,
      currentPage,
      handleCurrentChange,
      handleSizeChange,
    }
  },
}

function initRequestParam() {
  const { start, end } = getOneMonthOffset()
  return reactive({
    datePeriod: [start, end],
    start: start,
    end: end,
    depts: [],
  })
}

function initData() {
  const data = reactive({
    selectAll: false,
    allWards: [],
    deptEarn: {
      list: [],
      sum: 0,
    },
    doctorEarn: {
      list: [],
      sum: 0,
      doctorName: '',
    },
    patientBill: {
      list: [],
      sum: 0,
      doctorName: '',
      patientName: '',
    },
  })
  getAllWards().then((res) => {
    data.allWards = res
  })
  const doctorEarnTitle = computed(() => {
    return '收治病人' + data.doctorEarn.list.length + '位（医生：' + data.doctorEarn.doctorName + ' ，营收额：￥' + data.doctorEarn.sum + '）'
  })
  const patientBillTitle = computed(() => {
    return (
      '共' +
      data.patientBill.list.length +
      '条（患者：' +
      data.patientBill.patientName +
      ' ，医生：' +
      data.patientBill.doctorName +
      ' ，诊疗费用：￥' +
      data.patientBill.sum +
      '）'
    )
  })

  return { data, doctorEarnTitle, patientBillTitle }
}

function initVisibilities() {
  const showDoctorEarn = ref(false)
  const showPatientBill = ref(false)
  return { showDoctorEarn, showPatientBill }
}
</script>

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

.center-box {
  display: inline-block;
  padding: 15px 20px 10px 20px;
  vertical-align: middle;
  background-color: #fff;
  border-radius: 10px;
  border: 1px solid #ebeef5;
  box-shadow: 0 3px 5px #fff;
  text-align: left;
  overflow: hidden;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}
</style>
