<template>
  <div class="app-container">
    <!-- 说明区域 -->
    <el-alert title="导入说明" type="info" :closable="false" show-icon>
      <template #default>
        <div>1. 请先下载导入模板，按照模板格式填写数据。</div>
        <div>2. 支持 .xlsx 和 .xls 格式的Excel文件，文件大小不超过10MB。</div>
        <div>3. 导入数据会自动校验，校验失败的数据不会导入。</div>
      </template>
    </el-alert>

    <el-row :gutter="10" class="mb8 mt16">
      <el-col :span="1.5">
        <el-button type="info" plain icon="Download" @click="handleImportTemplate">下载模板</el-button>
      </el-col>
    </el-row>

    <!-- 上传组件 -->
    <el-upload ref="importRef" :limit="1" accept=".xlsx, .xls" :headers="importHeaders"
      :action="importUrl + '?updateSupport=' + updateSupport"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess" :on-error="handleFileError"
      :auto-upload="false" :show-file-list="true">
      <template #trigger>
        <el-button type="primary" icon="Upload">选择文件</el-button>
      </template>
      <el-button class="ml8" type="success" icon="Check" :loading="uploading" @click="submitUpload">开始导入</el-button>
      <template #tip>
        <div class="el-upload__tip">只能上传 .xlsx / .xls 文件，且不超过 10MB</div>
      </template>
    </el-upload>

    <!-- 是否覆盖已有数据 -->
    <el-row :gutter="10" class="mb8 mt16">
      <el-col :span="1.5">
        <el-checkbox v-model="updateSupport">是否更新已存在的用户数据</el-checkbox>
      </el-col>
    </el-row>

    <!-- 导入结果展示 -->
    <div v-if="importResult.show" class="mt16">
      <el-alert :title="importResult.title" :type="importResult.type" :closable="false" show-icon>
        <template #default>
          <div>成功条数：{{ importResult.successCount }}</div>
          <div>失败条数：{{ importResult.errorCount }}</div>
        </template>
      </el-alert>

      <!-- 错误明细 -->
      <div v-if="importResult.errorList && importResult.errorList.length > 0" class="mt16">
        <el-table :data="importResult.errorList" border size="small">
          <el-table-column label="行号" prop="rowNum" width="80" align="center" />
          <el-table-column label="错误信息" prop="errorMsg" :show-overflow-tooltip="true" />
        </el-table>
      </div>

      <!-- 导入数据预览 -->
      <div v-if="importResult.dataList && importResult.dataList.length > 0" class="mt16">
        <el-table :data="importResult.dataList" border size="small" max-height="400">
          <el-table-column label="隐患名称" prop="hiddName" :show-overflow-tooltip="true" />
          <el-table-column label="隐患等级" prop="hiddGrad" width="100" align="center">
            <template #default="scope">
              <dict-tag :options="hidd_grad" :value="scope.row.hiddGrad" />
            </template>
          </el-table-column>
          <el-table-column label="隐患状态" prop="hiddStat" width="100" align="center">
            <template #default="scope">
              <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
            </template>
          </el-table-column>
          <el-table-column label="涉及部位" prop="proPart" :show-overflow-tooltip="true" />
          <el-table-column label="采集时间" prop="collTime" width="180" align="center" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup name="HiddImport">
import { getToken } from "@/utils/auth"
import { listObjHidd } from "@/api/slaj/hidd"

const { proxy } = getCurrentInstance()
const { hidd_grad, hidd_stat } = proxy.useDict("hidd_grad", "hidd_stat")

const importRef = ref(null)
const uploading = ref(false)
const updateSupport = ref(false)

const upload = ref({ url: import.meta.env.VITE_APP_BASE_API + '/hidd/objhidd/importData' })
const importHeaders = ref({ Authorization: 'Bearer ' + getToken() })
const importUrl = computed(() => upload.value.url)

const importResult = ref({
  show: false,
  title: '',
  type: 'success',
  successCount: 0,
  errorCount: 0,
  errorList: [],
  dataList: []
})

/** 下载模板按钮操作 */
function handleImportTemplate() {
  proxy.download("hidd/objhidd/importTemplate", {}, `隐患导入模板_${new Date().getTime()}.xlsx`)
}

/** 文件上传中处理 */
function handleFileUploadProgress(event, file, fileList) {
  uploading.value = true
}

/** 文件上传成功处理 */
function handleFileSuccess(response, file, fileList) {
  uploading.value = false
  importRef.value.clearFiles()

  if (response.code === 200) {
    importResult.value = {
      show: true,
      title: '导入成功',
      type: 'success',
      successCount: response.data?.successCount || 0,
      errorCount: response.data?.errorCount || 0,
      errorList: response.data?.errorList || [],
      dataList: response.data?.dataList || []
    }
    proxy.$modal.msgSuccess("导入成功")
  } else {
    importResult.value = {
      show: true,
      title: '导入失败',
      type: 'error',
      successCount: 0,
      errorCount: response.data?.errorList?.length || 0,
      errorList: response.data?.errorList || [],
      dataList: []
    }
    proxy.$modal.msgError(response.msg || "导入失败")
  }
}

/** 文件上传失败处理 */
function handleFileError(error, file, fileList) {
  uploading.value = false
  importRef.value.clearFiles()
  proxy.$modal.msgError("文件上传失败")
}

/** 提交上传 */
function submitUpload() {
  importRef.value.submit()
}

onMounted(() => {
  // 初始化
})
</script>

<style scoped>
.mt16 {
  margin-top: 16px;
}
.ml8 {
  margin-left: 8px;
}
</style>