<template>
  <div v-if="valid" class="embed-responsive" :class="[prefixCls]">
    <iframe
      v-resize="iframeResizerOptions"
      :src="url"
      :width="width"
      :height="height"
      scrolling="no"
      loading="lazy"
      frameborder="0"
      sandbox="allow-modals allow-forms allow-popups allow-scripts allow-pointer-lock allow-same-origin allow-top-navigation allow-presentation"
      class="embed-responsive-item"
      allowfullscreen
    />
  </div>
</template>

<script>
import iframeResize from "iframe-resizer/js/iframeResizer.min.js";

// 导出组件
export default {
  name: "EmbedFrame",
  directives: {
    resize: {
      bind(el, { value = {} }) {
        el.addEventListener("load", () => {
          iframeResize(value, el);
        });
      },
      unbind(el) {
        el.iFrameResizer.removeListeners();
      },
    },
  },
  props: {
    // 组件前缀 class name
    prefixCls: { type: String, default: "" },
    // iframe 的 url
    src: { type: String },

    // 为后面拼接附加参数作准备
    params: { type: Object },
    // iframeResize 的初始化参数及扩展参数
    // eslint-disable-next-line vue/require-valid-default-prop
    options: {
      type: Object,
      default: () => {
        return {
          // 源iframeResize 的初始化参数
          log: true, // 扩展参数
          height: 150, // 默认初始化iframe的高度
        };
      },
    },
    width: { type: String, default: "100%" },
    height: { type: Number, default: 150 },
  },
  data() {
    return {
      valid: false,
      url: "",
      iframeResizerOptions: {},
    };
  },
  watch: {
    src(val) {
      this.parseSrc();
    },
    options() {
      this.parseOptions();
    },
  },
  mounted() {
    this.parseSrc();
    this.parseOptions();
  },
  methods: {
    parseSrc() {
      if (this.src) {
        this.url = this.src;
        this.valid = true;
        return;
      }
      this.valid = false;
    },
    parseOptions() {
      this.iframeResizerOptions = {
        ...this.iframeResizerOptions,
        ...(this.options || {}),
      };
    },
  },
};
</script>

<style scoped>
.embed-responsive {
  width: 100%;
}
</style>
