<template>
  <div class="upload-file-view">
    <el-input
      :style="{ width: inputWidth }"
      v-model.trim="attachmentName"
      placeholder="文件名称"
      readonly
    ></el-input>
    <el-upload
      action="upload-url"
      :on-change="handleFileChange"
      :show-file-list="false"
      :auto-upload="false"
      :disabled="disabled"
      style="display:inline-block;margin: 0 10px;"
      ref="UploadComp"
    >
      <el-button type="primary" :disabled="disabled" :loading="loading"
        >选择</el-button
      >
    </el-upload>
  </div>
</template>

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

export default {
  name: "upload-file-view",
  props: {
    inputWidth: {
      type: String,
      default: "200px"
    },
    format: {
      type: Array,
      default() {
        return ["xls", "xlsx"];
      }
    },
    maxSize: {
      type: Number,
      default: 20 * 1024 * 1024
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      attachmentName: "",
      canUpload: false,
      loading: false,
      res: {}
    };
  },
  methods: {
    checkFileFormat(fileType) {
      const _file_format = fileType
        .split(".")
        .pop()
        .toLocaleLowerCase();
      return this.format.some(
        item => item.toLocaleLowerCase() === _file_format
      );
    },
    async handleFileChange(file) {
      console.log(file);
      this.attachmentName = file.name;
      this.canUpload = file.status === "ready";

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

      if (!this.checkFileFormat(file.name)) {
        this.handleFormatError();
        return Promise.reject();
      }
      this.$emit("valid-change", { success: true });

      const md5 = await fileMD5(file.raw);

      this.$emit("file-change", {
        md5,
        filename: file.name,
        file: file.raw
      });
    },
    // upload(options) {
    //   let formData = new FormData();
    //   Object.entries(options.data).forEach(([k, v]) => {
    //     formData.append(k, v);
    //   });
    //   formData.append("file", options.file);
    //   this.$emit("uploading");

    //   return $post(options.action, formData, { headers: options.headers });
    // },
    handleFormatError() {
      const content = "只支持文件格式为" + this.format.join("/");
      this.res = {
        success: false,
        message: content
      };
      this.$emit("valid-change", this.res);
    },
    handleExceededSize() {
      const content =
        "文件大小不能超过" + Math.floor(this.maxSize / 1024) + "M";
      this.res = {
        success: false,
        message: content
      };
      this.$emit("valid-change", this.res);
    },
    setAttachmentName(name) {
      this.attachmentName = name;
    }
  }
};
</script>

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