<template>
  <el-upload
    class="attach-uploader"
    action="/api/cms/article/upload/attach"
    ref="upload"
    :multiple="true"
    :show-file-list="false"
    :before-upload="handleBeforeUpload"
    :on-success="handleUploadSuccess"
    :on-error="handleUploadError"
  >
    <slot></slot>
  </el-upload>
</template>

<script>

export default {
  name: 'ArticleAttachmentUploader',
  emits: ['add-file', 'success', 'error'],
  methods: {
    handleBeforeUpload (file) {
      this.$emit('add-file', file)
      return true
    },
    // 处理文件上传成功
    handleUploadSuccess (res, file) {
      if (!res.success) {
        this.$emit('error', {
          error: res.message,
          file
        })
        return
      }
      this.$emit('success', {
        file,
        data: res.data
      })
    },
    // 处理文件上传失败
    handleUploadError (error, file) {
      this.$emit('error', {
        error: error.message,
        file
      })
    }
  }
}
</script>

<style scoped lang="scss">
.attach-uploader {
  display: flex;
  :deep(.el-upload-list) {
    width: 100%;
  }
}
</style>
