<template>
  <img :src="url" ref="img" :width="realWidth" />
</template>
<script>
import { getToken } from "@/utils/auth";

export default {
  name: "AuthImg",
  props: {
    authSrc: {
      type: String,
      required: false,
      default: "",
    },
  },
  data() {
    return {
      url: "/ajax-loader.gif", // 先加载loading.gif, http://www.lovecode.cc/lib/owlcarousel/assets/ajax-loader.gif, /lib/owlcarousel/assets/ajax-loader.gif
      realWidth: "6%",
    };
  },
  mounted() {
    Object.defineProperty(Image.prototype, "authsrc", {
      writable: true,
      enumerable: true,
      configurable: true,
    });
    let img = this.$refs.img;
    let request = new XMLHttpRequest();
    request.responseType = "blob";
    request.open(
      "get",
      process.env.VUE_APP_BASE_API +
        "/common/download/fast?filePath=" +
        encodeURI(this.authSrc) +
        "&delete=" +
        false,
      true
    );
    request.setRequestHeader("Authorization", "Bearer " + getToken());
    request.onreadystatechange = (e) => {
      if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
        img.src = URL.createObjectURL(request.response);
        img.onload = () => {
          this.realWidth = "100%";
          URL.revokeObjectURL(img.src);
        };
      }
    };
    request.send(null);
  },
};
</script>
