<template>
  <div class="upload-wrapper">
    <el-upload
      ref="upload"
      action="no"
      accept=".jpg,.png,.gif"
      drag
      :show-file-list="false"
      :before-upload="beforeUpload"
      :http-request="upload"
      :on-exceed="handleExceed"
      :limit="limit"
    >
      <div>点击或拖拽图片到此上传</div>
      <div>只有 jpg, png, gif 等格式文件可以上传，文件大小不得超过 5MB</div>
    </el-upload>
  </div>
</template>

<script>
import { fileUpload } from '@/api/app';

export default {
  name: 'UploadAudio',
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    itemIndex: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {};
  },
  watch: {},
  methods: {
    beforeUpload(file) {
      // 可以用来限制文件大小
      if (file.size > 5 * 1024 * 1024) {
        this.$message.warning('上传图片大小不能超过5M');
        return false; // 必须返回false
      }
    },
    upload(file) {
      fileUpload('Mid', file, { isGlobalprogress: true }).then(({ file_info_list }) => {
        if (file_info_list.length > 0) {
          const { file_id, file_url } = file_info_list[0];
          this.$emit('fileUploadSuccess', file_id, file_url, this.itemIndex);
        }
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit ? this.limit : 1} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`,
      );
    },
  },
};
</script>
