<!--
<upload ref="uploadFile" url="/biz/hzz/basic/file/upload?bizId=" @uploadOver="uploadOver"></upload>
if (this.$refs.uploadFile.submitUpload(id)) {
  // true上传列表为空，直接执行结束操作
  this.insertOver()
}
-->

<template>
  <div style="width: 360px;margin: 20px auto;">
    <el-upload
      ref="upload"
      drag
      :action="allurl"
      :headers="header"
      :auto-upload="false"
      multiple
      :on-change="changeFileList"
      :on-success="uploadSuccess"
      :on-error="upError"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击添加</em>
      </div>
    </el-upload>
  </div>
</template>
<script>
export default {
  props: ["url",'type'], // 上传基础路径
  data() {
    return {
      fileList: [],
      resList: [],
      length: 0, // 上传列表长度
      sum: 0, // 上传成功次数
      allurl: "", // 上传完整路径
      header: {
        'persId': localStorage.getItem('userid'),
        'accessToken' : localStorage.getItem('accessToken')
      },
    };
  },
  computed:{
    userid(){
      return localStorage.getItem('userid') ? localStorage.getItem('userid') : ''
    }
  },
  methods: {
    // 初始化，
    init() {
      this.$refs.upload.clearFiles();
      this.length = 0;
      this.sum = 0;
      this.allurl = "";
      this.resList = [];
    },
    // 开始上传，文件列表为空直接返回turn表示结束，不为空触发上传并返回false，由uploadOver判断结束时间
    submitUpload(id) {
      this.allurl = `${this.url}${id}&bizType=${this.type}`;
      if (this.length) {
        this.$nextTick(() => {
          this.$refs.upload.submit();
        });
        return false;
      } else {
        return true;
      }
    },
    // 上传出错，向上触发结束
    upError(err, file, fileList) {
      this.$message.error("上传出错，请修改文件！");
      this.$emit("uploadOver");
      this.init();
    },
    // 全部上传成功，向上触发结束
    uploadSuccess(response, file, fileList) {
      this.resList.push(response.data);
      console.log(this.resList);
      this.sum = this.sum + 1;
      if (this.sum == this.length) {
        this.$emit("uploadOver", this.resList);
        this.init();
      }
    },
    // 及时更新列表长度
    changeFileList(file, fileList) {
      this.length = fileList.length;
    }
  }
};
</script>
