<template>
  <el-dialog
    v-model="visible"
    title="批量导入学生"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-alert
      title="导入说明"
      type="info"
      :closable="false"
      style="margin-bottom: 16px"
    >
      <template #default>
        <div style="line-height: 1.8">
          1. 请先下载导入模板，按模板格式填写数据<br>
          2. 支持 xlsx、xls 格式文件，单次最多导入500条<br>
          3. 必填字段：姓名、学校、年级、班级
        </div>
      </template>
    </el-alert>

    <div style="margin-bottom: 16px;">
      <el-button type="primary" :icon="Download" @click="handleDownloadTemplate">下载模板</el-button>
    </div>

    <el-upload
      ref="uploadRef"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="true"
      :limit="1"
      accept=".xlsx,.xls"
      drag
    >
      <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 文件</div>
      </template>
    </el-upload>

    <!-- 导入结果 -->
    <div v-if="importResult" style="margin-top: 16px;">
      <el-alert
        :title="`导入完成：成功 ${importResult.successCount} 条，失败 ${importResult.failCount} 条`"
        :type="importResult.failCount > 0 ? 'warning' : 'success'"
        :closable="false"
      />
      <div v-if="importResult.failList && importResult.failList.length > 0" style="margin-top: 12px;">
        <el-table :data="importResult.failList" border size="small" max-height="200">
          <el-table-column prop="row" label="行号" width="80" />
          <el-table-column prop="reason" label="失败原因" min-width="200" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 学生批量导入弹窗
 * @author pangu
 */
import { Download, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

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

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

const uploadRef = ref(null)
const importResult = ref(null)

// 上传地址
const uploadUrl = '/api/student/import'

// 上传请求头
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { Authorization: 'Bearer ' + token } : {}
})

// 下载模板
const handleDownloadTemplate = () => {
  // 实际应该调用后端接口下载模板
  ElMessage.info('模板下载功能需要对接后端下载接口')
}

// 上传前校验
const beforeUpload = (file) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件')
    return false
  }
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB')
    return false
  }
  importResult.value = null
  return true
}

// 上传成功
const handleSuccess = (response) => {
  if (response.code === 200) {
    importResult.value = response.data
    if (response.data.failCount === 0) {
      ElMessage.success('导入成功')
      emit('success')
    } else {
      ElMessage.warning('部分数据导入失败，请查看失败原因')
    }
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

// 上传失败
const handleError = () => {
  ElMessage.error('文件上传失败，请重试')
}
</script>

<style scoped>
.el-icon--upload {
  font-size: 48px;
  color: #c0c4cc;
}
</style>
