<template>
  <a-image
    :width="width" :style="{ height: imgHeight }" :src="src" :preview="isPreview ? {
      src: previewUrl || src
    } : false" @onload="onload"
  />
</template>

<script>
export default {
  props: {
    authSrc: {
      type: String,
      default: null,
    },
    previewSrc: {
      type: String,
      default: null,
    },
    width: {
      type: [Number, String],
      default: '100%',
    },
    height: {
      type: [Number, String],
      default: 'auto',
    },
    isPreview: {
      type: Boolean,
      default: true,
    },
  },
  emits: ['click'],

  data() {
    return {
      src: '',
      previewUrl: '',
      noImage: '',
      errorImage: '',
      loadingImage: '',
    };
  },

  computed: {
    imgHeight() {
      return typeof this.height === 'number' ? `${this.height}px` : this.height;
    },
  },

  watch: {
    authSrc(newValue) {
      this.loadImage(newValue, 'authSrc');
    },
    previewSrc(newValue) {
      this.loadImage(newValue, 'previewSrc');
    },
  },

  mounted() {
    this.noImage = '/static/assets/client-base-v4/image/no-image.png';
    this.errorImage = '/static/assets/client-base-v4/image/load-error.png';
    this.loadingImage = '/static/assets/client-base-v4/image/loading.gif';
    this.src = this.loadingImage;
    this.loadImage(this.authSrc, 'authSrc');
    this.loadImage(this.previewSrc, 'previewSrc');
  },

  beforeUnmount() {
    if (this.previewUrl) {
      URL.revokeObjectURL(this.previewUrl);
    }
  },

  methods: {
    loadImage: function (url, type) {
      let _self = this;

      if (url == null || url == '') {
        if (type === 'authSrc') _self.src = this.noImage;
        return;
      }
      if (type === 'authSrc') _self.src = this.loadingImage;

      fetch(url, {
        method: 'GET',
        headers: {
          'token': localStorage.getItem('#token'),
        },
      }).then(res => res.blob())
        .then(blob => {
          const objectURL = URL.createObjectURL(blob);
          if (type === 'authSrc') {
            _self.src = objectURL;
          } else {
            _self.previewUrl = objectURL;
          }
        })
        .catch(err => {
          console.error(err);
          if (type === 'authSrc') _self.src = this.errorImage;
        });
    },

    onload() {
      URL.revokeObjectURL(this.src);
    },
  },
};
</script>