<template>
  <div id="e-upload">
    <el-upload
      :action="url"
      :http-request="upload"
      :list-type="type"
      :fileList="fileList"
      :on-remove="onRemove"
      :on-error="onError"
      :on-preview="onPreview"
      :limit="limit"
      :on-exceed="onExceed"
      :before-remove="beforeRemove"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script>
const _ = require('lodash');
import axios from 'axios';
import { mapState, createNamespacedHelpers } from 'vuex';
export default {
  name: 'e-upload',
  props: {
    url: { type: String, required: true },
    type: { type: String, default: 'picture-card' },
    fileList: { type: Array },
    limit: { type: Number },
    remove: { type: Function },
    extra: { type: Object, default: () => {} },
  },
  model: {
    prop: 'fileList',
    event: 'change',
  },
  components: {},
  created() {},
  methods: {
    async upload({ file }) {
      let formdata = new FormData();
      formdata.append('file', file, file.name);
      const res = await axios.post(this.url, formdata, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      if (res.status === 200 && res.data.errcode == 0) {
        const { id, name, uri } = res.data;
        const obj = { url: uri, name: file.name, ...this.extra, uid: id };
        this.fileList.push(obj);
      }
    },
    beforeRemove(file) {
      if (this.remove && _.isFunction(this.remove)) {
        const { result, msg } = this.remove(file);
        if (!result) {
          this.$message.error(msg);
          return false;
        }
      }
      return true;
    },
    onRemove(file) {
      const index = this.fileList.findIndex(f => f.url === file.url);
      this.fileList.splice(index, 1);
    },
    onError(err) {
      this.$message.error(err);
    },
    // 点击事件
    onPreview(file) {
      const { url } = file;
      window.open(url);
    },
    // 超出限制
    onExceed() {
      this.$message.error(`只能上传${this.limit}个文件`);
    },
  },
  computed: {
    ...mapState(['user', 'menuParams']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped>
/deep/.el-upload-list__item.is-ready {
  display: none;
}
</style>
