<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,
  },
  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.$alert({ content: "无法上传" });
        e.target.value = "";
        return;
      }

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

      this.files = e.target.files;

      // if(this.name === this.file.name){
      //      e.target.value = "";
      //      return
      // }

      this.files.forEach((item) => {
        if (!fileInfo.checkMediaMime(this.mediaType, item.name)) {
          e.target.value = "";
          if (this.failString) {
            return this.$alert({
              content: this.failString,
            });
          }
          return this.$alert({
            content: "不支持该文件格式",
          });
        }
        if (this.limit > 0) {
          if (!fileInfo.checkSizeLimitFree(item.size, this.limit)) {
            e.target.value = "";
            return this.$alert({
              content: `文件大小不能超过${this.limit}MB`,
            });
          }
        } else if (!fileInfo.checkSizeLimit(this.mediaType, item.size)) {
          e.target.value = "";
          return this.$alert({
            content: `上传文件太大，不能超过${
              fileInfo.mediaMaxSize[this.mediaType]
            }MB`,
          });
        }
      });

      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>
