
<template>
  <div class="images-list">
    <el-upload
      action="#"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :file-list="fileList"
      :multiple="fileLimit > 1"
      :limit="fileLimit"
      :list-type="listType"
      :accept="fileAccept"
      :auto-upload="false"
      ref="ManualUploader"
    >
      <i
        v-if="listType === 'picture-card'"
        class="el-icon-plus"
        slot="trigger"
      ></i>
      <el-button v-else size="small" type="primary">点击上传</el-button>

      <div v-if="showTip" slot="tip" class="el-upload__tip">
        提示：只能上传{{ fileTypeName || "jpg/png" }}文件，且不超过
        {{ fileSize }}MB，最多上传{{ fileLimit }}个文件
      </div>
    </el-upload>
  </div>
</template>
<script>
export default {
  name: "ManualUploader",
  props: {
    // // 用于v-model绑定
    value: {
      type: [Number, Array, String],
    },
    files: {
      type: Array,
      default: () => [],
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如["doc", "xls", "ppt", "txt", "pdf"]
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 文件列表类型 text/picture/picture-card
    listType: {
      type: String,
      default: "picture",
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
    // 最大允许上传个数
    fileLimit: {
      type: Number,
      default: 99,
    },
  },
  data() {
    return {
      fileList: [],
    };
  },
  watch: {
    files: {
      handler: function (val) {
        this.fileList = JSON.parse(JSON.stringify(val));
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    fileTypeName() {
      let typeName = "";
      this.fileType.forEach((item) => {
        typeName += `${item}，`;
      });
      return typeName;
    },
    fileAccept() {
      let fileAccept = "";
      this.fileType.forEach((element) => {
        fileAccept += `.${element},`;
      });
      return fileAccept;
    },
  },
  methods: {
    getFiles() {
      return this.fileList;
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      return new Promise((resolve, reject) => {
        var isValidated = true;
        if (this.fileType && file) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          const isTypeOk = this.fileType.some((type) => {
            if (file.raw.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
          if (!isTypeOk & file) {
            this.$message.error(
              `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
            );
            isValidated = false;
          }
        }
        // 校检文件大小
        if (this.fileSize && file) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            isValidated = false;
          }
        }
        if (isValidated) {
          resolve(file);
        } else {
          reject("验证失败");
        }
      });
    },
    handleUploadError(err) {
      this.$message.error("上传失败, 请重试");
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`超出上传文件个数,请删除以后再上传！`);
    },

    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.fileList.map(async (item, index) => {
        if (item.uid === file.uid) {
          this.fileList.splice(index, 1);
          // TODO:调用删除接口
          // const { fileId } = file;
          // let res = await deleteFiles([fileId]);
          // if (res.code == 0) {
          //   this.$message.success("删除成功！");
          // }
        }
      });
    },

    handleChange(file, fileList) {
      let that = this;
      if (file.status === "ready") {
        this.handleBeforeUpload(file)
          .then((res) => {
            that.fileList.push(res);
            // that.$emit('input',that.fileList)
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
  },
};
</script>
<style lang="scss" >
.disabled .el-upload--picture-card {
  display: none !important;
}
</style>