<template>
  <div class="layout_container">
    <header class="round-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 style="width: 160px">
        <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>
    </header>
    <div class="layout_main layout_el-table">
      <el-table :data="reports" stripe highlight-current-row>
        <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"
      ></el-pagination>
    </div>
  </div>
  <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>
  <div id="printArea" style="opacity: 0; position: fixed">
    <normal-event :report="report"/>
  </div>
</template>

<script setup>
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 {formatDatetime} from '@/utils/date'
import {downloadExcel} from '@/utils/excel'
import NormalEvent from "@/components/inpatient/adverse-event-printpage/NormalEvent.vue";
import {getLodop, initLodop} from '@/utils/c-lodop'
import {useUserStore} from "@/pinia/user-store";
import {startLoading} from "@/utils/loading";

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 = useUserStore().userInfo.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 = () => {
  let LODOP = getLodop()
  const prntStyle = `<style>table, tr, th, td {border: 1px solid #c1dbfa;border-collapse: collapse;text-align: left;padding: 0 10px;vertical-align: center;word-break: break-all;font-size: 13px;}</style>`
  const prntContent = document.getElementById('printArea').innerHTML
  let pagePrint = prntStyle + '<body>' + prntContent + '</body>'
  LODOP.PRINT_INIT('normaladverseevent')
  LODOP.SET_PRINT_PAGESIZE(1, '210mm', '297mm', '')
  LODOP.SET_PRINT_MODE('FULL_WIDTH_FOR_OVERFLOW', true) // 整宽不变形
  LODOP.ADD_PRINT_HTM('2mm', '5mm', '100%', '100%', pagePrint)
  LODOP.SET_PRINT_STYLE('ItemType', 3)
  LODOP.PREVIEW()
}
const exportExcel = () => {
  startLoading()
  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(() => {
  initLodop()
  getAllDepts().then((res) => {
    allWards.value = res
    fetchReports()
  })
})

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>
