<template>
  <div style="width: 360px;margin: 20px auto;">
    <a-upload-dragger
      multiple
      :headers="header"
      :accept="accept"
      :file-list="fileList"
      :remove="handleRemove"
      :before-upload="beforeUpload"
      ref="upload">
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox" />
      </p>
      <p class="ant-upload-text">
        将文件拖到此处，或<em>点击添加</em>
      </p>
    </a-upload-dragger>
  </div>
</template>

<script>
import request from '../utils/gw_ajax_request';
export default {
  props: ['url', 'accept'],
  data() {
    return {
      fileList: [],
      allurl: '',
      header: {
        persId: localStorage.getItem('persId'),
        accessToken: localStorage.getItem('accessToken'),
      },
    };
  },
  created() {},
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file];
      return false;
    },
    submit() {
      const { fileList } = this;
      const resData = [];
      let flag = 0;

      fileList.forEach((file, index) => {
        const formData = new FormData();
        formData.append('file', file);
        request
          .post(this.allurl, formData)
          .then((res) => {
            flag++;
            if (res.success) {
              resData[index] = res.data;
              if (flag == fileList.length) {
                this.$emit('uploadOver', resData);
              }
            } else {
              this.$message.error(res.message);
              this.$emit('uploadOver');
            }
          })
          .catch(() => {
            this.$message.error('上传文件失败!');
            this.$emit('uploadOver');
          });
      });
    },
    submitUpload(id) {
      this.allurl = `${this.url}${id}`;
      if (this.fileList && this.fileList.length) {
        this.submit();
        return false;
      } else {
        return true;
      }
    },
    init() {
      this.fileList = [];
    },
  },
};
</script>

<style lang='less' scoped>

</style>
