<template>
  <div class="select-file" style="display: inline-block;">
    <el-input
      :style="{ width: inputWidth }"
      v-model.trim="attachmentName"
      :placeholder="placeholder"
      readonly
    ></el-input>
    <el-upload
      :action="uploadUrl"
      :before-upload="() => false"
      :show-file-list="false"
      :disabled="disabled"
      :on-change="fileChange"
      style="display:inline-block;margin: 0 10px;"
    >
      <el-button type="primary" :disabled="disabled">选择</el-button>
    </el-upload>
  </div>
</template>

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

export default {
  name: "select-file",
  props: {
    inputWidth: {
      type: String,
      default: "340px"
    },
    placeholder: {
      type: String,
      default: "请选择文件"
    },
    format: {
      type: Array,
      default() {
        return ["pdf"];
      }
    },
    maxSize: {
      type: Number,
      default: 20 * 1024 * 1024
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      attachmentName: "",
      uploadUrl: "",
      errorMsg: ""
    };
  },
  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 fileChange(file) {
      console.log(file);
      this.errorMsg = "";
      this.attachmentName = "";

      if (file.size > this.maxSize) {
        this.errorMsg =
          "文件大小不能超过" + Math.floor(this.maxSize / 1024) + "M";
        this.$emit("file-change", { errorMsg: this.errorMsg });
        return;
      }

      if (!this.checkFileFormat(file.name)) {
        this.errorMsg = "只支持文件格式为" + this.format.join("/");
        this.$emit("file-change", { errorMsg: this.errorMsg });
        return;
      }

      this.attachmentName = file.name;
      const md5 = await fileMD5(file.raw);
      this.$emit("file-change", {
        file: file.raw,
        md5
      });
    },
    setAttachmentName(name) {
      this.attachmentName = name;
    }
  }
};
</script>
