/*
*
* 1、url地址，如企业详情：https://pre-plug.jiansheku.com/enterprise?ak=aec7b3ff2y2q8x6t49a7e2c463ce21912&uid=a704fb35bca54707b9b5f8c9bba57815（ak：平台唯一标识；uid：用户标识）
*
* */
const steerScroll = function(iframeId, navigation, state, parentId) { // state:监听or移除监听；navigation:页面排除iframe后剩下高度；iframeId: iframe的id
  let dom = window
  if (parentId) { // 默认页面可以滚动
    dom = document.getElementById(parentId)
    if (!dom) {
      return
    }
    dom.style.overflow = 'auto'
  } else {
    document.body.style.overflow = 'visible'
  }
  if (state) {
    window.addEventListener('message', function(e) {
      const data = e.data
      const sct = parentId ? dom.scrollTop : document && document.documentElement.scrollTop || document && document.body.scrollTop
      if (data && typeof data === 'object') {
        // 动态设置iFrame高度
        if (data.height) {
          document.getElementById(iframeId).style.height = data.height + 'px'
          scrolling(iframeId, navigation, parentId) // 初始加载获取滚动条距离顶部高度
        }
        // 点击企业详情页 栏目名动态设置滚动高度
        if (data.scrollHeight) {
          const navHeight = navigation.isFixed && !parentId ? navigation.totalHeight - navigation.fixedHeight : !parentId ? navigation.totalHeight : 0
          dom.scrollTo(sct, parseInt(data.scrollHeight) + navHeight)
        }
        // 点击企业详情页 栏目下拉子标签动态设置滚动高度
        if (data.clientHeight) {
          dom.scrollTo(sct, sct - parseInt(data.clientHeight))
        }
        // 点击下拉子标签动态设置滚动高度
        if (data.initHeight >= 0) {
          dom.scrollTo(sct, data.initHeight)
        }
        // 根据子页面弹窗显示隐藏控制当前页面是否固定不可滚动
        if (data.scrollDisabled || data.scrollDisabled === false) {
          if (parentId) {
            dom.style.overflow = data.scrollDisabled ? 'hidden' : 'auto'
          } else {
            document.body.style.overflow = data.scrollDisabled ? 'hidden' : 'visible'
          }
        }
      }
    })
    dom.addEventListener('scroll', (event) => {
      scrolling(iframeId, navigation, parentId)
    })
  } else {
    dom.removeEventListener('scroll', (event) => {
      scrolling(iframeId, navigation, parentId)
    })
  }
}

const scrolling = function(iframeId, navigation, parentId) {
  // 滚动条距文档顶部的距离
  let scrollTop = parentId ? document.getElementById(parentId).scrollTop : window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  // 将滚动距离传入子组件
  const ifa = document.getElementById(iframeId)
  scrollTop = scrollTop + navigation.totalHeight
  const bodyHeight = document.body.clientHeight - navigation.totalHeight
  ifa.contentWindow.postMessage({ 'scrollTop': scrollTop, 'navHeight': navigation.totalHeight, 'bodyHeight': bodyHeight }, '*')
}

export {
  steerScroll
}
