<template>
  <div>
    <input
      ref="inputer"
      :accept="accept"
      :multiple="multiple"
      class="fileUp"
      type="file"
      name="file"
      @change="handleChange($event)"
    />
  </div>
</template>

<script>
import urlConfig from "@/apis/url-config";
import { getToken } from "@/utils/auth";
//Uploadcondition 用于判断个性化文件 //返回 false 就不会上传文件
//UploadErrorEvent 上传成功
//UploadErrorEvent 上传失败

export default {
  name: "fileUploadPdf",
  props: {
    //@reject 默认值
    accept: String, //上传文件类型
    multiple: {
      //是否可以上传多张图片
      type: Boolean,
      default: false,
    },
    uploadcondition: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      loading: false,
      imgAPI: urlConfig.baseURL,
    };
  },
  methods: {
    async handleChange(event) {
      let that = this;
      let inputDOM1 = that.$refs.inputer;
      const files = inputDOM1.files;
      let length = files.length;
      if (length === 0) return;
      that.loading = that.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      for (let i = 0; i <= length; i++) {
        if (i === length) {
          this.loading.close();
          that.$refs.inputer.value = "";
        } else {
          let str = await that.httpupLoad(files, i);
          if (str === "error") {
            that.$emit("UploadErrorEvent",true);
          } else if (str === "token") {
            that.$emit("UploadErrorEvent", false);
          } else {
            that.$emit("UploadSuccessEvent", {
              url: str,
            });
          }
        }
      }
    },
    async httpupLoad(files, i) {
      return new Promise((resolve, reject) => {
        let that = this;
        if (!this.uploadcondition(files[i])) {
          resolve("break");
        } else {
          let form = new FormData();
          form.append("files", files[i]);
          form.append("token", getToken());
          axios
            .post(`${that.imgAPI}admin/uploadfile`, form)
            .then((res) => {
              if (res && res.data && res.status === 200) {
                const { data, code } = res.data;
                if (code === 0) {
                  const { url, name } = data[0];
                  resolve({
                    url: `${that.imgAPI}storage/${url}`,
                    name: name,
                  });
                } else if (code >= 100 && code <= 104) {
                  resolve("token");
                } else {
                  resolve("error");
                }
              } else {
                reject();
              }
            })
            .catch((error) => {
              reject();
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.fileUp {
  opacity: 0;
  width: 100%;
  height: 100%;
  outline: none;
  position: absolute;
  top: 0;
  left: 0;
  &:hover {
    cursor: pointer;
  }
}
</style>
