<template>
  <Upload
    :action="fileUploadURL"
    :headers="uploadHeaders"
    :accept="accept"
    :show-upload-list="false"
    :on-success="importFileSuccess"
    :on-error="importFileError"
    :before-upload="beforeUpload"
    style="display: inline-block"
  >
    <slot></slot>
  </Upload>
</template>
<script>
  import mixinPage from '../../mixins/page';
  import { mapMutations } from 'vuex';

  /**
   * @displayName file-upload 单文件上传
   */
  export default {
    mixins: [mixinPage],
    data() {
      return {
        opened: false, // 是否打开
        sourceFilter: {} // 来源筛选
      };
    },
    created() {},
    props: {
      /**
       * 请求地址
       */
      url: {
        type: String
      },
      /**
       * 上传文件之前的钩子，参数为上传的文件，若返回 false 则停止上传
       */
      beforeUploadFunc: {
        type: Function
      },
      /**
       * 接受上传的文件类型
       */
      accept: {
        type: String
      }
    },
    computed: {
      fileUploadURL() {
        return this.apiBaseURL + this.url;
      }
    },
    methods: {
      ...mapMutations('admin/loader', ['start', 'end']),
      // 导入之前
      beforeUpload(file) {
        if (typeof this.beforeUploadFunc == 'function') {
          if (!this.beforeUploadFunc(file)) {
            return false;
          }
        }

        this.start();
      },
      // 导入成功
      importFileSuccess(res) {
        this.end();
        /**
         * 成功
         * @property {object} res 返回数据
         */
        this.$emit('on-success', res);
      },
      // 导入失败
      importFileError(error) {
        this.end();
        this.error(error.message);
      }
    }
  };
</script>
