<template>
  <div ref="containerRef" class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
      <el-form-item label="月份" prop="mont">
        <el-date-picker v-model="mont" type="month" value-format="YYYY-MM" placeholder="选择月份" style="width: 200px" @change="handleMonthChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询事故</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleConfirmReport" v-hasPermi="['acci:bisaccimont:add']">确认上报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="CircleClose" @click="handleZeroReport" v-hasPermi="['acci:bisaccimont:add']">零事故上报</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['acci:bisaccimont:export']">导出月报</el-button>
      </el-col>
    </el-row>

    <div class="table-wrapper">
    <el-table :height="tableHeight" v-loading="loading" :data="acciList" @selection-change="handleSelectionChange" style="margin-bottom: 20px;">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="事故名称" align="center" prop="acciName" :show-overflow-tooltip="true" />
      <el-table-column label="死亡人数" align="center" prop="deathNum" width="100" />
      <el-table-column label="重伤人数" align="center" prop="seriInjuNum" width="100" />
      <el-table-column label="经济损失" align="center" prop="econLoss" width="120" />
    </el-table>
    </div>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-divider content-position="left">附件材料</el-divider>

    <div style="margin-bottom: 12px;">
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :data="{ bizGuid: currentMontGuid }"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        accept=".doc,.docx,.xls,.xlsx,.pdf,.zip,.rar"
        :disabled="uploading"
      >
        <el-button type="primary" plain icon="Upload" :loading="uploading">上传附件</el-button>
        <template #tip>
          <div class="el-upload__tip" style="display: inline-block; margin-left: 8px; color: #909399;">
            支持doc/docx/xls/xlsx/pdf/zip/rar格式，单个文件不超过10MB
          </div>
        </template>
      </el-upload>
    </div>

    <el-table v-loading="attachLoading" :data="attachList" empty-text="暂无附件">
      <el-table-column label="文件名" align="center" prop="medName" :show-overflow-tooltip="true" />
      <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button link type="primary" icon="Download" @click="handleDownloadAttach(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="零事故上报" v-model="zeroReportOpen" width="400px" append-to-body>
      <div style="text-align: center; padding: 20px;">
        <el-icon style="font-size: 48px; color: #e6a23c;"><WarningFilled /></el-icon>
        <p style="margin-top: 16px; font-size: 16px;">确认上报月份 "{{ mont }}" 为零事故月报？</p>
        <p style="margin-top: 8px; color: #909399;">零事故上报后将无法再添加事故记录</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitZeroReport">确 定</el-button>
          <el-button @click="zeroReportOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AcciMontReport">
import request from '@/utils/request'
import { useTableHeight } from '@/hooks/useTableHeight'
import { getToken } from '@/utils/auth'
import { listObjAcci } from "@/api/slaj/acci"
import { addBisAcciMont, listBisAcciMont } from "@/api/slaj/acci"

const { tableHeight, containerRef } = useTableHeight()

const { proxy } = getCurrentInstance()

const loading = ref(false)
const attachLoading = ref(false)
const acciList = ref([])
const attachList = ref([])
const total = ref(0)
const ids = ref([])
const mont = ref('')
const currentMontGuid = ref('')
const uploading = ref(false)
const zeroReportOpen = ref(false)

const uploadUrl = import.meta.env.VITE_SERVICE_BASE_TITLE + '/common/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + getToken()
}

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10
  }
})

const { queryParams } = toRefs(data)

function initMonth() {
  const now = new Date()
  const y = now.getFullYear()
  const m = String(now.getMonth() + 1).padStart(2, '0')
  mont.value = `${y}-${m}`
}

function getList() {
  loading.value = true
  listObjAcci(proxy.addDateRange(queryParams.value, [mont.value + '-01', mont.value + '-31'])).then(res => {
    loading.value = false
    acciList.value = res.rows || []
    total.value = res.total || 0
  }).catch(() => {
    loading.value = false
  })
}

function handleMonthChange(val) {
  if (val) {
    mont.value = val
    handleQuery()
  }
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  const now = new Date()
  const y = now.getFullYear()
  const m = String(now.getMonth() + 1).padStart(2, '0')
  mont.value = `${y}-${m}`
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.guid)
}

function handleConfirmReport() {
  if (!mont.value) {
    proxy.$modal.msgError("请先选择月份")
    return
  }
  const acciGuids = ids.value
  proxy.$modal.confirm('是否确认上报月份 "' + mont.value + '" 的事故月报？').then(function () {
    return addBisAcciMont({ mont: mont.value, acciGuids: acciGuids })
  }).then(() => {
    proxy.$modal.msgSuccess("上报成功")
    getList()
  }).catch(() => {})
}

function handleZeroReport() {
  if (!mont.value) {
    proxy.$modal.msgError("请先选择月份")
    return
  }
  zeroReportOpen.value = true
}

function submitZeroReport() {
  addBisAcciMont({ mont: mont.value, acciGuids: [] }).then(response => {
    proxy.$modal.msgSuccess("零事故上报成功")
    zeroReportOpen.value = false
  }).catch(() => {
    zeroReportOpen.value = false
  })
}

function handleExport() {
  proxy.download("acci/bisaccimont/export", {
    mont: mont.value
  }, `acciMont_${mont.value}_${new Date().getTime()}.xlsx`)
}

function fetchAttachList() {
  if (!currentMontGuid.value) return
  attachLoading.value = true
  request({
    url: '/acci/medbase/list',
    method: 'get',
    params: { bizGuid: currentMontGuid.value }
  }).then(res => {
    attachLoading.value = false
    attachList.value = res.rows || []
  }).catch(() => {
    attachLoading.value = false
  })
}

function beforeUpload(file) {
  const maxSize = 10 * 1024 * 1024
  if (file.size > maxSize) {
    proxy.$modal.msgError('文件大小不能超过10MB')
    return false
  }
  uploading.value = true
  return true
}

function handleUploadSuccess(response, file, fileList) {
  uploading.value = false
  if (response.code === 200) {
    proxy.$modal.msgSuccess('上传成功')
    fetchAttachList()
  } else {
    proxy.$modal.msgError(response.msg || '上传失败')
  }
}

function handleUploadError() {
  uploading.value = false
  proxy.$modal.msgError('上传失败')
}

function handleDownloadAttach(row) {
  proxy.download('common/download', { fileName: row.medPath }, row.medName)
}

onMounted(() => {
  initMonth()
  getList()
})
</script>
