<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { splitStrLast } from '@/utils/util'
import { importStudent } from '../api'
const emit = defineEmits<Emits>()
const upload = ref()
const fileList = ref([]) // 文件列表

defineProps({
  isShowImportDialog: {
    type: Boolean
  }
})
interface Emits {
  (e: 'update:isShowImportDialog', isShowImportDialog: boolean): void
  (e: 'create'): void
}

// 取消
const handleCancel = () => {
  emit('update:isShowImportDialog', false)
}

const beforeUpload = (file: any) => {
  const suffix = splitStrLast(file.name, '.')
  if (!['xlsx', 'xls'].includes(suffix)) {
    ElMessage.warning('只能上传excel文件')
    return false
  } else {
    return true
  }
}
const fetchFileUpload = (option: any) => {
  return new Promise(() => {
    importStudent({ file: option.file }).then(() => {
      ElMessage.success('导入数据成功')
      emit('update:isShowImportDialog', false)
      emit('create')
    })
  })
}

const handleSubmitUpload = () => {
  upload.value.submit()
}
</script>
<template>
  <el-dialog :model-value="isShowImportDialog" draggable :before-close="handleCancel" title="批量导入学生" width="30%">
    <el-upload
      style="text-align: center"
      class="file-import"
      ref="upload"
      action="#"
      accept=".xls,.xlsx"
      drag
      :auto-upload="false"
      :file-list="fileList"
      :limit="1"
      :before-upload="beforeUpload"
      :http-request="fetchFileUpload">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖至此处，点击上传</div>
    </el-upload>
    <div style="margin-bottom: 10px; text-align: center">
      导入模板下载：<a
        href="/center_resource/%E5%AD%A6%E7%94%9F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
        download="学生模板"
        ><el-link type="primary">学生模板.xlsx</el-link></a
      >
    </div>

    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmitUpload">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
