<template>
  <div class="image-flex-contain">
    <div class="image-flex-image" :style="styles">
      <img
        :src="image.url"
        :alt="image.title"
        @load="resizeImage(initRotate)"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "image-flex-contain",
  props: {
    image: {
      type: Object,
      default() {
        return {};
      }
    },
    initRotate: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      styles: { width: "", height: "", top: "", left: "", transform: "" },
      deg: this.initRotate
    };
  },
  mounted() {
    this.registWinResize();
  },
  beforeDestroy() {
    window.removeEventListener("resize", () => {
      this.resizeImage(this.deg);
    });
  },
  methods: {
    registWinResize() {
      window.addEventListener("resize", () => {
        this.resizeImage(this.deg);
      });
    },
    resizeImage(deg = 0) {
      this.deg = deg;
      const box = this.$el;
      const imgDom = box.firstChild.firstChild;
      const { naturalWidth, naturalHeight } = imgDom;
      const imageSize = this.getImageSizePos({
        win: {
          width: box.clientWidth,
          height: box.clientHeight
        },
        img: {
          width: naturalWidth,
          height: naturalHeight
        },
        rotate: deg
      });
      this.styles = Object.assign(this.styles, {
        width: imageSize.width + "px",
        height: imageSize.height + "px",
        top: imageSize.top + "px",
        left: imageSize.left + "px",
        transform: `rotate(${deg}deg)`
      });
    },
    getImageSizePos({ win, img, rotate }) {
      const imageSize = {
        width: 0,
        height: 0,
        top: 0,
        left: 0
      };
      const isHorizontal = !!(rotate % 180);

      const rateWin = isHorizontal
        ? win.height / win.width
        : win.width / win.height;
      const hwin = isHorizontal
        ? {
            width: win.height,
            height: win.width
          }
        : win;

      const rateImg = img.width / img.height;

      if (rateImg <= rateWin) {
        imageSize.height = Math.min(hwin.height, img.height);
        imageSize.width = Math.floor(
          (imageSize.height * img.width) / img.height
        );
      } else {
        imageSize.width = Math.min(hwin.width, img.width);
        imageSize.height = Math.floor(
          (imageSize.width * img.height) / img.width
        );
      }
      imageSize.left = (win.width - imageSize.width) / 2;
      imageSize.top = (win.height - imageSize.height) / 2;
      return imageSize;
    }
  }
};
</script>
