<template>
  <page-layer>
    <template #header>
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
          style="width: 260px"
      ></el-date-picker>
      <el-select v-model="queryParam.wardCode" placeholder="请选择科室" clearable>
        <el-option v-for="item in allWards" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <el-divider direction="vertical"></el-divider>
      <el-button type="primary" icon="Refresh" @click="fetchReports">检索数据</el-button>
      <el-button type="primary" icon="Upload" @click="exportExcel">导出Excel</el-button>
    </template>
    <template #main>
      <el-table :data="reports" stripe highlight-current-row :height="tableHeight">
        <el-table-column prop="occurDatetime" label="发生时间" sortable></el-table-column>
        <el-table-column prop="category" label="事件类型"></el-table-column>
        <el-table-column prop="submitDatetime" label="提交时间"></el-table-column>
        <el-table-column prop="userName" label="提交人" width="80"></el-table-column>
        <el-table-column prop="department" label="科室" width="120"></el-table-column>
        <el-table-column label="受理" width="60">
          <template v-slot="scope">
            <span v-html="filterAccepted(scope.row.accepted)"></span>
          </template>
        </el-table-column>
        <el-table-column label="处理" width="60">
          <template v-slot="scope">
            <span v-html="filterHandled(scope.row.handled)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="deptDealerName" label="处理人" width="80"></el-table-column>
        <el-table-column label="打印" width="60">
          <template v-slot="scope">
            <span v-html="filterPrinted(scope.row.printed)"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" icon="View" @click="viewReport(scope.row.pid)">查看</el-button>
            <el-button type="danger" icon="Close" @click="deleteReport(scope.row.pid)" :disabled="isNotHlb">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParam.currentPage"
          :page-sizes="[15, 30, 45, 70, 100]"
          :page-size="queryParam.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          style="margin-top: 5px"
      ></el-pagination>
      <el-dialog v-model="showViewReport" title="报告详情" width="60%">
        <view-adverse-event :report="report" :disableHlbDealing="disableHlbDealing"></view-adverse-event>
        <div style="width: 100%; text-align: right; margin: 10px 0">
          <el-button type="primary" icon="Edit" @click="showModifyReport = true" :disabled="disableHlbDealing">
            修改此报告
          </el-button>
          <el-button type="primary" icon="Upload" @click="submitHlbDealing" :disabled="disableHlbDealingBtn">提交处理
          </el-button>
          <el-button type="primary" icon="Printer" @click="toPrintPage">生成打印页面</el-button>
        </div>
      </el-dialog>
      <el-dialog v-model="showModifyReport" title="修改报告" width="70%">
        <modify-adverse-event :report="report" @cancel-modify="cancelModify"
                              @confirm-modify="confirmModify"></modify-adverse-event>
      </el-dialog>
    </template>
  </page-layer>
</template>

<script>
import store from '@/store'
import {shortcuts} from '@/data/shortcuts'
import {computed, onMounted, reactive, ref} from 'vue'
import {
  getAllDepts,
  getAllReports,
  getReportDetail,
  submitNewReport,
  updateDeleted,
  updateFinalHandled
} from '@/api/adverse-event'
import ViewAdverseEvent from '@/components/ViewAdverseEvent.vue'
import ModifyAdverseEvent from '@/components/ModifyAdverseEvent.vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import router from '@/router'
import {formatDatetime} from '@/utils/date'
import {downloadExcel} from '@/utils/excel'
import PageLayer from "@/layout/PageLayer";

export default {
  components: {PageLayer, ViewAdverseEvent, ModifyAdverseEvent},
  setup() {
    const windowSize = store.state.app.windowSize
    const tableHeight = windowSize.h - 55
    const dateRange = ref(null)
    const allWards = ref([])

    const queryParam = reactive({
      start: null,
      end: null,
      wardCode: '',
      currentPage: 1,
      pageSize: 30,
    })

    const reports = ref([])
    const totalSize = ref(0)

    const handleSizeChange = (val) => {
      queryParam.pageSize = val
      fetchReports()
    }
    const handleCurrentChange = (val) => {
      queryParam.currentPage = val
      fetchReports()
    }

    const report = ref({})
    const showViewReport = ref(false)
    const showModifyReport = ref(false)

    const fetchReports = () => {
      if (dateRange.value) {
        queryParam.start = formatDatetime(dateRange.value[0])
        queryParam.end = formatDatetime(dateRange.value[1])
      } else {
        queryParam.start = null
        queryParam.end = null
      }
      getAllReports(queryParam).then((res) => {
        reports.value = res.list
        totalSize.value = res.totalSize
      })
    }

    const roles = store.state.user.info.roles
    const isNotHlb = computed(() => {
      return roles.indexOf(24) === -1 && roles.indexOf(1) === -1 && roles.indexOf(2) === -1
    })
    const disableHlbDealing = computed(() => {
      if (roles.indexOf(24) === -1 && roles.indexOf(1) === -1 && roles.indexOf(2) === -1) {
        return true
      }
      return report.value.finalDealTime !== null
    })
    const disableHlbDealingBtn = computed(() => {
      if (roles.indexOf(24) === -1 && roles.indexOf(1) === -1 && roles.indexOf(2) === -1) {
        return true
      }
      if (report.value.deptDealTime === null) {
        return true
      }
      return report.value.finalDealTime !== null
    })
    const viewReport = (pid) => {
      getReportDetail(pid, 'final').then((res) => {
        report.value = res
        showViewReport.value = true
      })
    }
    const deleteReport = (pid) => {
      ElMessageBox.confirm('是否删除此报告？删除后不可恢复，请谨慎选择。', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '再考虑考虑',
        type: 'warning',
      })
          .then(() => {
            updateDeleted(pid).then(() => {
              ElMessage({
                message: '删除成功',
                type: 'success',
                duration: 2500,
                showClose: true,
              })
              fetchReports()
            })
          })
          .catch(() => {
          })
    }

    const cancelModify = () => {
      showModifyReport.value = false
    }
    const confirmModify = (val) => {
      val.isModify = true
      submitNewReport(val).then(() => {
        ElMessage({
          message: '修改成功',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
      })
      showModifyReport.value = false
    }

    const submitHlbDealing = () => {
      if (report.value.finalDealing === '未处理') {
        ElMessage({
          message: '请填写处理内容！',
          type: 'warning',
          duration: 2500,
          showClose: true,
        })
        return
      }
      const param = {
        pid: report.value.pid,
        dealing: report.value.finalDealing,
      }
      updateFinalHandled(param).then((res) => {
        report.value = res
        ElMessage({
          message: '处理成功',
          type: 'success',
          duration: 2500,
          showClose: true,
        })
      })
    }
    const toPrintPage = () => {
      const route = router.resolve({path: '/printAdverseEvent/' + report.value.pid})
      window.open(route.href, '_blank')
    }
    const exportExcel = () => {
      store.commit('app/setLoading', true)
      const data = {
        param: {
          start: null,
          end: null,
          wardCode: queryParam.wardCode,
        },
        url: '/adverseEvent/exportExcel',
        fileName: '不良事件统计.xlsx',
      }
      if (dateRange.value) {
        data.param.start = formatDatetime(dateRange.value[0])
        data.param.end = formatDatetime(dateRange.value[1])
      }
      setTimeout(() => {
        downloadExcel(data)
      }, 100)
    }
    onMounted(() => {
      getAllDepts().then((res) => {
        allWards.value = res
        fetchReports()
      })
    })

    return {
      tableHeight,
      dateRange,
      shortcuts,
      isNotHlb,
      allWards,
      queryParam,
      reports,
      totalSize,
      handleSizeChange,
      handleCurrentChange,
      filterAccepted,
      filterHandled,
      filterPrinted,
      viewReport,
      deleteReport,
      report,
      disableHlbDealing,
      disableHlbDealingBtn,
      showViewReport,
      showModifyReport,
      submitHlbDealing,
      cancelModify,
      confirmModify,
      toPrintPage,
      fetchReports,
      exportExcel,
    }
  },
}

function filterAccepted(val) {
  return val === 1 ? '<span style="color:green">已受理</span>' : '<span style="color:red">未受理</span>'
}

function filterHandled(val) {
  return val === 1 ? '<span style="color:green">已处理</span>' : '<span style="color:red">未处理</span>'
}

function filterPrinted(val) {
  return val === 1 ? '<span style="color:green">已打印</span>' : '<span style="color:red">未打印</span>'
}
</script>
