<template>
  <input
    ref="file"
    multiple="multiple"
    type="file"
    name="file"
    id
    style="display: none"
    :accept="accept"
  />
</template>
<script>
import * as fileInfo from "@/utils/file";
export default {
  props: {
    limit: Number,
    mediaType: String,
    acceptType: String,
    failString: String,
    limitFailStr: String,
  },
  computed: {
    accept() {
      if (this.acceptType) {
        return this.acceptType;
      }
      return fileInfo.mediaMimes[this.mediaType]
        .map((item) => this.mediaType + "/" + item)
        .join(",");
    },
  },
  mounted() {
    this.$el.addEventListener("change", (e) => {
      if (!window.FileReader) {
        this.$msg.warning("无法上传");
        e.target.value = "";
        return;
      }

      if (e.target.files.length === 0) {
        e.target.value = "";
        return;
      }

      this.files = e.target.files;

      // 对选中的文件按照格式限制和尺寸限制做过滤
      this.files = Array.from(this.files).filter((item, i) => {
        if (!fileInfo.checkMediaMime(this.mediaType, item.name)) {
          setTimeout(() => {
            if (this.failString) {
              this.$msg.warning(`“${item.name}”` + this.failString);
            } else {
              this.$msg.warning("不支持该文件格式");
            }
          }, i * 100);
          return;
        }
        if (this.limit > 0) {
          if (!fileInfo.checkSizeLimitFree(item.size, this.limit)) {
            e.target.value = "";
            setTimeout(() => {
              if (this.limitFailStr) {
                this.$msg.warning(`“${item.name}”` + this.limitFailStr);
              }
              else{
                this.$msg.warning(`文件大小不能超过${this.limit}MB`);
              }
            }, i * 100);
            return;
          }
        } else if (!fileInfo.checkSizeLimit(this.mediaType, item.size)) {
          setTimeout(() => {
            if (this.limitFailStr) {
              this.$msg.warning(`“${item.name}”` + this.limitFailStr);
            }
            else{
              this.$msg.warning(
                `上传文件太大，不能超过${fileInfo.mediaMaxSize[this.mediaType]}MB`
              );
            }
            
          }, i * 100);
          return;
        }
        return item
      });

      this.$emit("file-change", this);
      e.target.value = "";
    });
  },
  beforeDestroy() {
    // this.clear();
  },
  methods: {
    click() {
      this.$el.click();
    },
    clear() {
      this.dataURL && window.URL.revokeObjectURL(this.dataURL);
      this.name = null;
      this.type = null;
      this.size = null;
      this.files = null;
      this.dataURL = null;
      this.base64 = null;
      this.poster = null;
    },
    upload() {},
  },
};
</script>
