<template>
  <el-upload
    class="upload-button"
    :action="uploadUrl"
    :max-size="maxSize"
    :before-upload="handleBeforeUpload"
    :show-file-list="showFileList"
    :auto-upload="autoUpload"
    :disabled="disabled"
    ref="UploadComp"
    :onChange="onChange"
    :onRemove="onRemove"
    :multiple="false"
    :fileList="fileList"
  >
    <el-button :type="theme" :disabled="disabled" :loading="loading">{{
      btnContent
    }}</el-button>
  </el-upload>
</template>

<script>
import { fileMD5 } from "@/plugins/md5";

export default {
  name: "upload-button",
  props: {
    btnContent: {
      type: String,
      default: "选择",
    },
    format: {
      type: Array,
      default() {
        return ["jpg", "png"];
      },
    },
    maxSize: {
      type: Number,
      default: 20 * 1024 * 1024,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    theme: {
      type: String,
      default: "primary",
    },
    showFileList: {
      type: Boolean,
      default: false,
    },
    autoUpload: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      loading: false,
      uploadUrl: "",
      res: {},
      fileList: [],
    };
  },
  methods: {
    checkFileFormat(fileType) {
      const _file_format = fileType.split(".").pop().toLocaleLowerCase();

      if (!this.format.length) return true;

      return this.format.some(
        (item) => item.toLocaleLowerCase() === _file_format
      );
    },
    async handleBeforeUpload(file) {
      this.attachmentName = file.name;

      if (file.size > this.maxSize) {
        this.handleExceededSize();
        return Promise.reject();
      }

      if (!this.checkFileFormat(file.name)) {
        this.handleFormatError();
        return Promise.reject();
      }

      return true;
    },
    handleFormatError() {
      const content = "只支持文件格式为" + this.format.join("/");
      this.res = {
        success: false,
        message: content,
      };
      this.loading = false;
      this.$emit("upload-error", this.res);
    },
    handleExceededSize() {
      const content =
        "文件大小不能超过" + Math.floor(this.maxSize / 1024) + "M";
      this.res = {
        success: false,
        message: content,
      };
      this.loading = false;
      this.$emit("upload-error", this.res);
    },
    async onChange(file, fileList) {
      console.log("onChange", file, fileList);
      this.fileList = [file];
      const md5 = await fileMD5(file.raw);
      this.$emit("file-change", {
        file: file.raw,
        md5,
      });
    },
    onRemove(file, fileList) {
      console.log("remove", file, fileList);
      if (!fileList.length) {
        this.$emit("file-change", { file: null, md5: null });
      }
    },
  },
};
</script>
<style lang="scss">
.upload-button {
  .el-upload {
    width: auto !important;
  }
}
</style>
