<template>
  <iframe v-if="$route.meta.iframeParam.src" :src='$route.meta.iframeParam.src' class="iframe" ref="iframe"></iframe>
  <error v-else></error>
</template>

<script>
import NProgress from 'nprogress';
import error from '@/pages/errorpage/404';
import 'nprogress/nprogress.css';

export default {
  name: 'buitInIframe',
  created() {
    NProgress.configure({ showSpinner: false });
  },
  mounted() {
    this.load();
    this.resize();
  },
  components: {
    error,
  },
  watch: {
    $route() {
      this.load();
    },
  },
  methods: {
    // 显示等待框
    show() {
      NProgress.start();
    },
    // 隐藏等待狂
    hide() {
      NProgress.done();
    },
    // 加载浏览器窗口变化自适应
    resize() {
      window.onresize = () => {
        this.iframeInit();
      };
    },
    // 加载组件
    load() {
      this.show();
      const iframeParam = this.$route.meta.iframeParam;
      if (this.$route.meta.iframeParam) {
        let list = [];
        /* eslint no-restricted-syntax: 0 */
        for (const key in iframeParam) {
          if (key !== 'url' && key !== 'src') {
            list.push(`${key}= ${iframeParam[key]}`);
          }
        }
        list = list.join('&').toString();
        this.$route.meta.iframeParam.src = `${iframeParam.url}${list.length > 0 ? '?list' : ''}`;
      }

      // 超时3s自动隐藏等待狂，加强用户体验
      let time = 3;
      const timeFunc = setInterval(() => {
        time -= 1;
        if (time === 0) {
          this.hide();
          clearInterval(timeFunc);
        }
      }, 1000);
      this.iframeInit();
    },
    // iframe窗口初始化
    iframeInit() {
      const iframe = this.$refs.iframe;
      const clientHeight = document.documentElement.clientHeight - 92;
      if (this.$route.meta.iframeParam && iframe) {
        iframe.style.height = `${clientHeight}px`;
        if (iframe.attachEvent) {
          iframe.attachEvent('onload', () => {
            this.hide();
          });
        } else {
          iframe.onload = () => {
            this.hide();
          };
        }
      }
    },
  },
};
</script>

<style lang="less">
.iframe {
  width: 100%;
  height: 100%;
  border: 0;
  overflow: hidden;
  box-sizing: border-box;
}
</style>
