<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 type="primary" size="mini">点击上传</el-button>

      <div v-if="showTip" 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: "ManualUploader", //用于使用getfiles方法获取文件的父组件
  props: {
    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,
    },
    //建议
    advice: {
      type: String,
    },
    onlyRead: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      fileList: [],
      removedIds: [], //被删除的文件Id集合
    };
  },
  watch: {
    files: {
      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 || item.url,
                url: item.pressUrl || item.url,
                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: {
    getFiles() {
      const isImage = this.fileType.some((item) => {
        return ["jpg", "jpeg", "png"].includes(item);
      });
      // 不能使用JSON.stringify及JSON.parse，因为有File对象
      const tempList = [...this.fileList];
      if (isImage) {
        const newFileList = tempList.map((item) => {
          if (item.status == "ready") {
            return item;
          } else {
            const { highImg, lowImg, name, fileId, status } = item;
            const obj = {
              url: highImg,
              pressUrl: lowImg,
              name,
              fileId,
              status,
            };
            return obj;
          }
        });
        return newFileList;
      } else {
        return tempList;
      }
    },
    // 上传前校检格式和大小
    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) {
      // debugger;
      const { status } = file;
      if (status == "success") {
        this.removedIds.push(file.fileId);
        this.$emit("getRemovedIds", this.removedIds);
      }
      this.fileList = fileList;
      console.log(123, this.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);
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
  },
};
</script>
<style lang="scss">
// .disabled .el-upload--picture-card,
// .el-upload--card {
//   display: none !important;
// }

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