<template>
  <iframe
    ref="iframeContainer"
    :src="url"
    class="online-menu-iframe"
    style="width: 100%"
    height="100%"
    frameborder="no"
    border="0"
    scrolling="auto"
  ></iframe>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getSysMenuById, getUrlTicket } from '@/api/portal.js'
  export default {
    name: 'OnlineMenu',
    computed: {
      ...mapGetters('user', ['accessToken']),
    },
    mounted() {
      let that = this
      //监听url菜单流程页面的取消
      window.addEventListener('message', function (e) {
        // 获取消息内容 data
        const { data } = e
        if (data.message && data.message == 'closeTab') {
          that.$tabs.close()
        }
      })
      const frameWindow = this.$refs.iframeContainer.contentWindow
      let flag = 0
      const this_ = this
      frameWindow.onscroll = function () {
        this_.$nextTick(() => {
          var scrollTop =
            frameWindow.document.documentElement.scrollTop ||
            frameWindow.document.body.scrollTop
          if (scrollTop && flag < 1) {
            frameWindow.document.documentElement.scrollTop = 0
            frameWindow.document.body.scrollTop = 0
          }
          flag += 1
        })
      }
      this.iframeSrc()
    },
    beforeDestroy() {
      window.removeEventListener('message', () => {})
    },
    data() {
      return {
        url: '',
      }
    },
    methods: {
      iframeSrc() {
        let href = this.$route.meta.href
        //获取url菜单id
        var varsPath = this.$route.path.split('/')
        if (varsPath && varsPath.length > 0) {
          const dataId = varsPath[varsPath.length - 1]
          if (dataId && dataId != '') {
            this.appendUrlTicket(href, dataId)
            return
          }
        }
        this.url = this.checkUrlPrev(href, true)
      },
      checkUrlPrev(href, isAddToken) {
        let srcUrl = ''
        if (!(href.startsWith('http://') || href.startsWith('https://'))) {
          href = window.context.front + this.$route.meta.href
          const isQuery = href && href.indexOf('?')
          if (isAddToken) {
            srcUrl = `${href}${isQuery > -1 ? '&' : '?'}token=${
              this.accessToken
            }&__isFull__=true`
          } else {
            srcUrl = `${href}${isQuery > -1 ? '&' : '?'}__isFull__=true`
          }
        } else {
          srcUrl = href
        }
        return srcUrl
      },
      appendUrlTicket(url, dataId) {
        getSysMenuById(dataId)
          .then((menu) => {
            if (!menu || !menu.tokenEnabled) {
              this.url = this.checkUrlPrev(url, true)
              return
            }
            var tokenType = menu.tokenType
            var tokenKey = menu.tokenKey || 'token'
            if (tokenType == 0) {
              url = this.handleUrlToken(url, tokenKey, this.accessToken)
              this.url = this.checkUrlPrev(url, false)
            } else if (tokenType == 1) {
              var tokenApiObj = JSON.parse(Base64.decode(menu.tokenApi) || '{}')
              if (tokenApiObj && tokenApiObj != {}) {
                //通过接口获取token
                getUrlTicket(tokenApiObj)
                  .then((res) => {
                    if (!res || !res.value) {
                      this.$message.error(
                        `未获取到页面跳转的票据，请检查配置信息！`
                      )
                      this.url = this.checkUrlPrev(url, true)
                    }
                    url = this.handleUrlToken(url, tokenKey, res.value)
                    this.url = this.checkUrlPrev(url, false)
                  })
                  .catch((err) => {
                    console.error(`获取页面跳转票据失败，${err}`)
                    this.$message.error(`获取页面跳转票据失败！`)
                    this.url = this.checkUrlPrev(url, true)
                  })
              } else {
                this.url = this.checkUrlPrev(url, true)
              }
            } else {
              this.url = this.checkUrlPrev(url, true)
            }
          })
          .catch((err) => {
            console.error(`根据id【${dataId}】获取菜单信息失败，${err}`)
            this.$message.error(`根据id【${dataId}】获取菜单信息失败！`)
            this.url = this.checkUrlPrev(url, true)
          })
      },
      handleUrlToken(url, tokenKey, tokenValue) {
        if (
          typeof tokenKey === 'undefined' ||
          tokenKey == null ||
          tokenKey === ''
        ) {
          return url
        }
        if (url.indexOf('?') != -1) {
          url = `${url}&${tokenKey}=${tokenValue}`
        } else {
          url = `${url}?${tokenKey}=${tokenValue}`
        }
        return url
      },
    },
  }
</script>

<style lang="scss" scoped>
  .online-menu-iframe {
    height: 100%;
    background: #fff;
  }
</style>
