<template>
  <EmbedFrame
    ref="embedFrameView"
    :src="url"
    :options="options"
    :height="frameHeight"
  />
</template>

<script>
import EmbedFrame from "@/components/embed-frame";

export default {
  components: { EmbedFrame },
  data() {
    return {
      url: "",
      options: {},
      frameHeight: 0,

      timer: null,
    };
  },
  mounted() {
    this.init();
    this.installEventHandler();
  },
  beforeDestroy() {
    this.unInstallEventHandler();
    clearInterval(this.timer);
    this.timer = null;
  },
  methods: {
    getParentNode() {
      const el = this.$refs.embedFrameView;
      const parentEl = el.$parent.$el.parentElement;
      return parentEl;
    },
    init() {
      // 从路由的query中获得 url 值
      const { url } = this.$route.query;
      if (url) {
        this.url = url;
      }

      const parentEl = this.getParentNode();
      // 设置 Options
      this.options = {
        log: false,
        inPageLinks: true,
        scrolling: false,
      };

      if (this.url.startsWith("http")) {
        this.frameHeight = parentEl?.offsetHeight || 150;
      } else {
        this.$nextTick(() => {
          const iframe = parentEl.querySelector(".embed-responsive-item");
          if (iframe) {
            const fn = () => {
              const iframeWin =
                iframe.contentWindow || iframe.contentDocument.parentWindow;
              if (iframeWin?.document?.body) {
                const height =
                  iframeWin.document.body.scrollHeight ||
                  iframeWin.document.documentElement.scrollHeight;
                iframe.height =
                  Math.abs(height - iframe.height) < 30
                    ? iframe.height
                    : height;
              }
            };
            setTimeout(fn, 200);
            this.timer = setInterval(fn, 1000);
          }
        });
      }
    },

    installEventHandler() {
      window.addEventListener("resize", this.onResize);
    },
    unInstallEventHandler() {
      window.removeEventListener("resize", this.onResize);
    },
    onResize() {
      this.frameHeight = this.getParentNode().offsetHeight;
    },
  },
};
</script>
