
<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="ManualUploaderBind" :class="{ disabled: uploadDisabled || onlyRead }">
      <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 &&!onlyRead)" slot="tip" class="el-upload__tip">
        <div v-if="advice" style="color: #f56c6c">建议：{{ advice }}</div>
        提示：只能上传{{ fileTypeName || "jpg/png" }}文件，且不超过
        {{ fileSize }}MB，最多上传{{ fileLimit }}个文件
      </div>
    </el-upload>
  </div>
</template>
<script>
export default {
  name: "ManualUploaderBind",//用于使用双向绑定的父组件
  props: {
    // // 用于v-model绑定
    value: {
      type: [Number, Array, String],
    },
    // 大小限制(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,
    },
    //建议
    advice: {
      type: String,
    },
    onlyRead: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
    };
  },
  watch: {
    value: {
      handler: function (val) {
        // 将回填的字段从url-->pressUrl
        if (val) {
          let tempList = [...val];
          this.fileList = tempList.map((item) => {
            if (item.status == "ready") {
              return item;
            } else {
              return {
                highImg: item.url,
                lowImg: item.pressUrl,
                url: item.pressUrl,
                // pressUrl:item.pressUrl,
                name: item.name,
                fileId: item.fileId,
              };
            }
          });
        } else {
          this.fileList = [];
        }
      },
      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;
    },
    uploadDisabled() {
      return this.fileList.length == this.fileLimit;
    },
  },
  methods: {
    // 上传前校检格式和大小
    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) {
      let that = this;
      that.fileList.map(async (item, index) => {
        if (item.uid === file.uid) {
          that.fileList.splice(index, 1);
        }
      });
      if (
        this.fileType.indexOf("jpg") != -1 ||
        this.fileType.indexOf("jpeg") != -1 ||
        this.fileType.indexOf("png") != -1
      ) {
        let newFileList = that.fileList.map((item) => {
          if (item.status == "ready") {
            return item;
          } else {
            item.url = item.highImg;
            item.pressUrl = item.lowImg;
            item.name = item.name;
            item.fileId = item.fileId;
            return item;
          }
        });
        that.$emit("input", newFileList);
      } else {
        that.$emit("input", that.fileList);
      }
    },

    handleChange(file, fileList) {
      let that = this;
      if (fileList.length == this.fileLimit) {
        this.maxNum = this.fileLimit;
      }
      if (file.status === "ready") {
        this.handleBeforeUpload(file)
          .then((res) => {
            that.fileList.push(res);
            if (
              this.fileType.indexOf("jpg") != -1 ||
              this.fileType.indexOf("jpeg") != -1 ||
              this.fileType.indexOf("png") != -1
            ) {
              let tempList = [...that.fileList];
              let newFileList = tempList.map((item) => {
                if (item.status == "ready") {
                  return item;
                } else {
                  item.url = item.highImg;
                  item.pressUrl = item.lowImg;
                  item.name = item.name;
                  item.fileId = item.fileId;
                  return item;
                }
              });
              that.$emit("input", newFileList);
            } else {
              that.$emit("input", that.fileList);
            }
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
  },
};
</script>
<style lang="scss" >
.disabled .el-upload--picture-card {
  display: none !important;
}

.el-upload-list__item {
  transition: none !important;
}
</style>