<template>
  <div class="upload-container">
    <a-button type="primary" @click="handleClick">选择文件</a-button>
    <input type="file" ref="fileInput" multiple style="display: none" @change="handleFileChange" />
    <div class="file-list" v-if="fileList.length">
      <div v-for="(file, index) in fileList" :key="index" class="file-item">
        <span>{{ file.name }}</span>
        <span>{{ (file.size / 1024 / 1024).toFixed(2) }}MB</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FileUpload',
  data () {
    return {
      fileList: []
    }
  },
  methods: {
    handleClick () {
      this.$refs.fileInput.click()
    },
    handleFileChange (e) {
      const files = Array.from(e.target.files)
      this.fileList = files.map(file => ({
        file,
        name: file.name,
        size: file.size,
        progress: 0
      }))
      this.uploadFiles()
    },
    async uploadFiles () {
      for (let i = 0; i < this.fileList.length; i++) {
        const fileItem = this.fileList[i]
        try {
          await this.uploadFile(fileItem, i)
          // 添加2秒延时,除非是最后一个文件
          if (i < this.fileList.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 2000))
          }
        } catch (error) {
          console.error('上传失败:', error)
        }
      }
    },
    uploadFile (obj, index) {
      this.$api.base.asyncApplyBookUpload(this.uploadHandle(obj.file, obj.name)).then(({ data = {} }) => {
        if (data) {
          this.$message.success('上传成功!')
        } else
          this.$message.error('上传失败1')
      }).catch(() => {
        this.$message.error('上传失败2')
      })
    },
    uploadHandle (file, fileName) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('fileName', fileName)
      return formData
    },
  }
}
</script>

<style scoped>
.upload-container {
  padding: 20px;
}

.file-list {
  margin-top: 20px;
}

.file-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>