<template>
  <div class="upload-file-view">
    <el-input
      :style="{ width: inputWidth }"
      v-model.trim="attachmentName"
      placeholder="文件名称"
      readonly
    ></el-input>
    <el-upload
      :action="uploadUrl"
      :headers="headers"
      :max-size="maxSize"
      :format="format"
      :data="uploadDataDict"
      :on-change="handleFileChange"
      :before-upload="handleBeforeUpload"
      :on-error="handleError"
      :on-success="handleSuccess"
      :http-request="upload"
      :show-file-list="false"
      :auto-upload="false"
      style="display:inline-block;margin: 0 10px;"
      ref="UploadComp"
    >
      <el-button type="primary">选择</el-button>
    </el-upload>
    <el-button
      type="primary"
      @click="startUpload"
      v-if="canUpload"
      :loading="loading"
      style="margin-right: 10px;"
      >开始上传</el-button
    >
  </div>
</template>

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

export default {
  name: "upload-file-view",
  props: {
    inputWidth: {
      type: String,
      default: "439px"
    },
    format: {
      type: Array,
      default() {
        return ["xls", "xlsx"];
      }
    },
    uploadUrl: {
      type: String,
      required: true
    },
    uploadData: {
      type: Object,
      default() {
        return {};
      }
    },
    maxSize: {
      type: Number,
      default: 10 * 1024 * 1024
    },
    addFilenameParam: {
      type: String,
      default: "filename"
    }
  },
  data() {
    return {
      attachmentName: "",
      canUpload: false,
      loading: false,
      uploadDataDict: {},
      headers: {
        token: this.$ls.get("token"),
        md5: ""
      },
      res: {}
    };
  },
  methods: {
    startUpload() {
      this.loading = true;
      this.$refs.UploadComp.submit();
    },
    checkFileFormat(fileType) {
      const _file_format = fileType
        .split(".")
        .pop()
        .toLocaleLowerCase();
      return this.format.some(
        item => item.toLocaleLowerCase() === _file_format
      );
    },
    handleFileChange(file) {
      this.attachmentName = file.name;
      this.canUpload = file.status === "ready";
    },
    async handleBeforeUpload(file) {
      this.uploadDataDict = {
        ...this.uploadData,
        schoolId: this.$ls.get("schoolId"),
        userId: this.$ls.get("user", { id: "" }).id
      };
      this.uploadDataDict[this.addFilenameParam] = file.name;

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

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

      const md5 = await fileMD5(file);
      this.headers["md5"] = md5;

      return true;
    },
    upload(options) {
      return ajax(options);
    },
    handleError(error) {
      this.canUpload = false;
      this.loading = false;
      this.res = {
        success: false,
        msg: error.message
      };
      this.$emit("upload-error", error);
    },
    handleSuccess(response) {
      this.canUpload = false;
      this.loading = false;
      if (response.code === "200") {
        this.res = {
          success: true,
          msg: "导入成功！"
        };
        this.$emit("upload-success", response);
      } else {
        this.handleError(response);
      }
    },
    handleFormatError() {
      const content = "只支持文件格式为" + this.format.join("/");
      this.res = {
        success: false,
        msg: content
      };
      this.loading = false;
      this.$emit("upload-error", content);
    },
    handleExceededSize() {
      const content =
        "文件大小不能超过" + Math.floor(this.maxSize / 1024) + "M";
      this.res = {
        success: false,
        msg: content
      };
      this.loading = false;
      this.$emit("upload-error", content);
    },
    setAttachmentName(name) {
      this.attachmentName = name;
    }
  }
};
</script>

<style scoped>
.upload-file-view {
  display: inline-block;
}
</style>
