<template>
  <div class="iframe" v-loading="loading">
    <iframe id="companyIframe" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" width="100%" :src="src" />
  </div>
</template>


<script>
  import { steerScroll } from '@/assets/js/jskplug';
  import { dskAccessToken } from '@/api/common';
  export default {
    name: 'GzscDetail',
    data() {
      return {
        currentUrl:'',
        loading: false,
        iframeHight: 800, // iframe高度-当前页控制
        navigation: { isFixed: true, fixedHeight: 0, totalHeight: 0 }, // iframe之外页面顶部对象，ifFixed:是否浮动；fixedHeight：浮动对象高度；totalHeight：顶部整体高度
        footHeight: 160,  //底部高度，若为0（页面内部嵌套或者没有底部板块）
        src: '', //
        domain: 'https://pre-plug.jiansheku.com',
        uid: '', // 需要携带的uid
        loginDialogVisible: false,
        vipDialogVisible: false,
        dataVip:{},
        minHeight: 0
      }
    },
    computed: {

    },
    created() {
      if(window.location.host === 'http://szh.jiansheku.com' || window.location.host === 'szh.jiansheku.com'){
        this.domain='https://plug.jiansheku.com'
      }else {
        this.domain='https://pre-plug.jiansheku.com'
        // this.domain='http://192.168.60.8:3400'
      }
      this.loading = true
      if(process.browser){
        this.getAccesstoken(true)
      }
    },
    mounted() {
      // this.setInitHeight()  //设置初始相关高度
      this.iframeLoading() // 判断iframe页面是否加载完成-当前页控制
      // steerScroll('companyIframe', this.navigation, this.footHeight, true, '', this) // 监听滚动（iframe的id、页面排除iframe后页面剩下高度[例:80]、增加监听[不传就是移除监听]、父级id[不带默认就是铺满整个页面]]）
      //控制页面内容最低高度
      // this.setMainHeight()
    },
    beforeDestroy() {
      clearInterval(this.iframeTimer) // -当前页控制
      clearInterval(this.tokenTimer) // -当前页控制
      steerScroll('companyIframe', this.navigation, this.footHeight) // 监听滚动（iframe的id、页面排除iframe后页面剩下高度[例:80]、增加监听[不传就是移除监听]、父级id[不带默认就是铺满整个页面]]）
    },
    methods: {
      setInitHeight(){
        let headerHeight = document.getElementById('header').offsetHeight
        this.navigation.fixedHeight = this.navigation.totalHeight = headerHeight + 10
      },
      // 判断iframe页面是否加载完成-当前页控制
      iframeLoading() {
        const iframeHeight = document.getElementById('companyIframe').clientHeight
        let number = 0
        this.iframeTimer = setInterval(() => {
          number = number + 1000
          if (document.getElementById('companyIframe').clientHeight !== iframeHeight || number === 5000) {
            this.loading = false
            clearInterval(this.iframeTimer)
          }
        },1000)
      },
      // 获取accessToken
      async getAccesstoken(init){
        dskAccessToken().then(res => {
          if (res.code == 200) {
            // this.loading = true
            this.timelongs = res.data.expire;
            this.ak = res.data.accessToken;
            if(init){ //首次加载iframe地址
              if(window.location.search){
                this.src = `${this.domain+this.$route.fullPath}&ak=${this.ak}&initTime=${new Date().getTime()}&uid=${this.uid}&origin=${window.location.origin}`
              }else{
                this.src = `${this.domain+this.$route.fullPath}?ak=${this.ak}&initTime=${new Date().getTime()}&uid=${this.uid}&origin=${window.location.origin}`
              }
            }else{  //更新iframe地址的accessToken
              let ifam = document.getElementById('companyIframe')
              ifam.contentWindow.postMessage({ 'accessToken': this.ak, 'initTime': new Date().getTime() }, '*')
            }
            this.refreshtoken();
          } else {
            clearTimeout(this.tokentimer);
          }
        });
      },
      setMainHeight(){
        let cliHight = document.body.clientHeight,
          footerHeight = document.getElementById('footer') ? document.getElementById('footer').offsetHeight : 0
        this.minHeight = cliHight - footerHeight
      },
      refreshtoken() {
        this.tokentimer = setTimeout(() => {
          dskAccessToken().then(res => {
            if (res.code == 200) {
              this.timelongs = res.data.expire;
              this.ak = res.data.accessToken;
              let ifam = document.getElementById('companyIframe');	//iframe的id
              let akObj = res.data.expire;	//accessToken接口的返回值
              let initTime = new Date().getTime(); 	//accessToken接口返回后的当前时间戳
              ifam.contentWindow.postMessage({ 'accessToken': akObj.accessToken, 'initTime': initTime }, '*');
            } else {
              clearTimeout(this.tokentimer);
            }
          });
        }, this.timelongs * 1000);
      },
    },
    watch: {
      '$store.state.akObj.expire' (newValue, oldValue) {
        if(newValue){
          let t = (newValue - 20) * 1000, _this = this
          _this.tokenTimer = setTimeout(function () {
            _this.getAccesstoken()
          }, t)
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .iframe {
    width: 100%;
    padding: 16px 24px;
    padding-right: 15px;
    box-sizing: border-box;

    #companyIframe {
      width: 100%;
      height: 100%;
    }
  }
</style>
