<!--
  批量导入弹窗
  @author pangu
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量导入学生"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-steps :active="currentStep" finish-status="success" align-center style="margin-bottom: 20px;">
      <el-step title="下载模板" />
      <el-step title="上传文件" />
      <el-step title="导入结果" />
    </el-steps>

    <!-- 步骤1：下载模板 -->
    <div v-if="currentStep === 0" class="step-content">
      <el-alert title="请先下载导入模板，按照模板格式填写学生信息" type="info" :closable="false" show-icon />
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" :icon="Download" @click="handleDownloadTemplate">下载导入模板</el-button>
      </div>
    </div>

    <!-- 步骤2：上传文件 -->
    <div v-if="currentStep === 1" class="step-content">
      <el-upload
        ref="uploadRef"
        drag
        :auto-upload="false"
        :limit="1"
        :on-change="handleFileChange"
        :on-exceed="handleExceed"
        accept=".xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">只能上传 xlsx/xls 文件，且不超过 5MB</div>
        </template>
      </el-upload>
    </div>

    <!-- 步骤3：导入结果 -->
    <div v-if="currentStep === 2" class="step-content">
      <el-result :icon="result.failCount > 0 ? 'warning' : 'success'" :title="resultTitle">
        <template #sub-title>
          <div>总数：{{ result.total }} 条，成功：{{ result.successCount }} 条，失败：{{ result.failCount }} 条</div>
        </template>
        <template #extra>
          <el-button v-if="result.failCount > 0" type="primary" @click="showErrorList = !showErrorList">
            {{ showErrorList ? '隐藏' : '查看' }}错误详情
          </el-button>
        </template>
      </el-result>

      <!-- 错误列表 -->
      <el-table v-if="showErrorList && result.errorList.length > 0" :data="result.errorList" border style="margin-top: 20px;">
        <el-table-column prop="rowNum" label="行号" width="80" align="center" />
        <el-table-column prop="studentName" label="学生姓名" width="120" />
        <el-table-column prop="studentNo" label="学号" width="120" />
        <el-table-column prop="errorMsg" label="错误信息" show-overflow-tooltip />
      </el-table>
    </div>

    <template #footer>
      <el-button v-if="currentStep > 0 && currentStep < 2" @click="handlePrev">上一步</el-button>
      <el-button v-if="currentStep < 2" type="primary" @click="handleNext" :loading="uploading">
        {{ currentStep === 1 ? '开始导入' : '下一步' }}
      </el-button>
      <el-button v-if="currentStep === 2" type="primary" @click="handleClose">完成</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Download, Upload } from '@element-plus/icons-vue'
import { importStudent, downloadTemplate } from '@/api/student'

const props = defineProps({
  visible: Boolean
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const currentStep = ref(0)
const uploadRef = ref(null)
const uploadFile = ref(null)
const uploading = ref(false)
const showErrorList = ref(false)

const result = reactive({
  total: 0,
  successCount: 0,
  failCount: 0,
  errorList: []
})

const resultTitle = computed(() => {
  return result.failCount > 0 ? '导入完成，部分失败' : '导入成功'
})

function handleDownloadTemplate() {
  downloadTemplate()
  ElMessage.success('模板下载成功')
}

function handleFileChange(file) {
  uploadFile.value = file.raw
}

function handleExceed() {
  ElMessage.warning('只能上传一个文件')
}

function handlePrev() {
  currentStep.value--
}

async function handleNext() {
  if (currentStep.value === 0) {
    currentStep.value++
  } else if (currentStep.value === 1) {
    if (!uploadFile.value) {
      ElMessage.warning('请先上传文件')
      return
    }
    
    uploading.value = true
    try {
      const res = await importStudent(uploadFile.value)
      if (res.code === 200) {
        Object.assign(result, res.data)
        currentStep.value++
        emit('success')
      } else {
        ElMessage.error(res.msg || '导入失败')
      }
    } catch (error) {
      ElMessage.error('导入失败')
    } finally {
      uploading.value = false
    }
  }
}

function handleClose() {
  currentStep.value = 0
  uploadFile.value = null
  showErrorList.value = false
  Object.assign(result, {
    total: 0,
    successCount: 0,
    failCount: 0,
    errorList: []
  })
  uploadRef.value?.clearFiles()
  dialogVisible.value = false
}
</script>

<style scoped>
.step-content {
  min-height: 200px;
  padding: 20px 0;
}
</style>
