<template>
  <el-upload class="upload-button" action="" :http-request="upload" :show-file-list="false">
    <el-button type="primary">{{ buttonText }}</el-button>
  </el-upload>
</template>
<script lang="ts" setup>
const props = defineProps({
  // 上传接口
  api: {
    type: Function,
    required: true
  },
  // 上传额外参数
  extraData: {
    type: Object,
    default: () => ({})
  },
  // 按钮文字
  buttonText: {
    type: String,
    default: '导入'
  }
})

const emits = defineEmits(['success'])

const upload = async (params) => {
  console.log(params)
  const { file } = params
  const formData = new FormData()
  formData.append('file', file)
  for (const i in props.extraData) {
    formData.append(i, props.extraData[i])
  }
  const res = await props.api(formData)
  console.log(res)
  if (res?.success || res.data.status === 'success') {
    ElMessage({
      type: 'success',
      message: '导入成功，如数据未刷新，请稍后查看'
    })
    setTimeout(() => {
      emits('success')
    }, 1000)
  } else {
    ElMessage({
      type: 'error',
      message: '导入失败'
    })
  }
}
</script>

<style lang="less">
.upload-button {
  display: inline-block;
  margin: 0 12px;
}
</style>
