<template>
  <el-upload
    class="upload-demo"
    :action="doUpload"
    :http-request="doUploadFile"
    :on-remove="handleRemove"
    :before-upload="beforeAvatarUpload"
    :on-preview="handlePreview"
    multiple
    :limit="limit"
    :file-list="fileVal"
    :show-file-list="false"
    accept=".pdf, .doc, .docx, .xls, .xlsx"
  >
    <el-button class="el-icon-paperclip" type="primary">上传附件</el-button>
    <span>最多支持{{limit}}个附件，类型可为word，excel, pdf, txt</span>
  </el-upload>
</template>

<script>
import { uploadOther } from "@/api/user";
export default {
  props: {
    fileVal: {
      type: Array,
      default: function () {
        return [];
      },
    },
    type: {
      type: String,
      default: "",
    },
    index: {
      type: Number,
      default: -1,
    },
    limit:{
      type: Number,
      default: 1,
    }
  },
  data() {
    return {
      doUpload: "",
      fileType: ["pdf", "doc", "docx", "xls", "xlsx", "txt"],
    };
  },
  created() {},
  watch: {},
  methods: {
    doUploadFile(obj) {
      var avatar = new FormData();
      avatar.append("file", obj.file);
      uploadOther(avatar).then((res) => {
        let data = {
          name: obj.file.name,
          url: res.data,
        };
        this.fileVal.push(data);
        this.$emit("fileFun", this.fileVal, this.type);
      });
    },
    // 移除文件
    handleRemove(file, fileVal) {
      this.$emit("fileFun", fileVal, this.type);
    },
    // 下载文件
    handlePreview(file) {
      window.location.href = file.url;
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 50; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$showMessage("上传文件大小不能超过 50MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
  },
};
</script>
<style scoped>
/*去除upload组件过渡效果*/
::v-deep.el-upload-list__item {
  transition: none !important;
}
</style>
<style scoped lang="scss">
.el-upload {
  text-align: left;
}
.avatar {
  height: 100px;
  width: 100px;
}
.el-button {
  cursor: pointer;
}
span {
  margin-left: 10px;
}
.upload-demo {
  width: 500px;
}
</style>


