<!-- 导入excel按钮组件 前端传二进制文件  -->
<script setup lang="tsx" generic="T">
import type { BackendServiceResult } from '@/utils/request/types'
const props = defineProps<{
  api: (file: File, onProgress?: (progress: number) => void) => Promise<BackendServiceResult<T[]>>
}>()

const emit = defineEmits<{
  success: []
  error: [errorList: T[]]
}>()
const fileInput = useTemplateRef<HTMLInputElement>('fileInput')
const uploadProgress = ref(0)

const handleChange = async (e: Event) => {
  uploadProgress.value = 0
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return

  const notificationInstance = ElNotification({
    title: '上传文件进度',
    message: () => (
      <div>
        <el-progress
          indeterminate
          percentage={uploadProgress.value}
          duration={0}
          status={uploadProgress.value === 100 ? 'success' : ''}
        />
      </div>
    ),

    duration: 0,
  })

  try {
    await props.api(file, (progress) => {
      uploadProgress.value = progress
    })
    setTimeout(() => {
      ElMessage.success('上传成功')
    }, 1000)
    emit('success')
  } catch (error: any) {
    // 解析失败信息
    console.error(error)
    if (error.code === 501) {
      // 部分上传的数据不对 有错误
      emit('error', error.data as T[])
    } else {
      console.error(error)
      emit('error', [])
    }
  } finally {
    ;(e.target as HTMLInputElement).value = ''
    setTimeout(() => {
      notificationInstance.close()
      setTimeout(() => {
        uploadProgress.value = 0
      }, 300)
    }, 1500)
  }
}
</script>

<template>
  <el-button :loading="uploadProgress > 0" type="primary" @click="fileInput?.click()">
    <input type="file" accept=".xlsx" ref="fileInput" @change="handleChange" class="hidden" />

    <el-icon v-show="uploadProgress === 0"><IEpUpload /></el-icon>
    导入
  </el-button>
</template>
