import Vue from 'vue'
import { isAfterIphoneX, addXSupport } from '../../src/utils/env'
// 为了生成空的index.css文件，可防止「babel-plugin-component」按需加载解析时报错
import './index.css'

const patchBlock = {
  node: null,
  windowHeight: null,
  getWindowHeight() {
    if (!this.windowHeight) {
      this.windowHeight = window.outerHeight
    }
    return this.windowHeight
  },
  createAndAppendBody(height) {
    if (!this.node) {
      const div = document.createElement('div')
      div.style.width = '100%'
      div.style.height = `${height}px`
      this.node = div
      document.body.append(this.node)
    }
  },
  update(height) {
    if (this.node) {
      this.node.style.height = `${height}px`
    }
  },
  reset() {
    if (this.node) {
      this.node.style.height = 0
    }
  },
  remove() {
    if (this.node) {
      document.body.removeChild(this.node)
      this.node = null
    }
  },
}

const getRemainHeight = () => {
  const windowHeight = patchBlock.getWindowHeight()
  const bodyHeight = document.body.clientHeight
  return {
    remainHeight: windowHeight - bodyHeight,
    // bodyHeight与windowHeight相等时，也会出现该bug，因此+1强制body超出window
    computedHeight: windowHeight - bodyHeight + 1,
  }
}

export default {
  // 自动探测viewport-fit，并添加
  addXSupport,
  // 判断是否是iphoneX之后的机型
  isAfterIphoneX,
  // 添加安全区域补丁
  create() {
    if (isAfterIphoneX()) {
      addXSupport()
      const { remainHeight, computedHeight } = getRemainHeight()
      if (remainHeight > 0) {
        if (patchBlock.node) {
          patchBlock.update(computedHeight)
        } else {
          patchBlock.createAndAppendBody(computedHeight)
        }
      }
    }
    return patchBlock.node
  },
  // 更新安全区域补丁
  update() {
    if (patchBlock.node && isAfterIphoneX()) {
      // 重置node高度，以正确计算内容是否满一屏
      patchBlock.reset()
      Vue.nextTick(() => {
        const { remainHeight, computedHeight } = getRemainHeight()
        if (remainHeight > 0) {
          patchBlock.update(computedHeight)
        }
      })
    }
  },
  // 移除安全区域补丁
  remove() {
    patchBlock.remove()
  },
  // 供Vue.use使用
  install(vueGlobal) {
    /* eslint no-param-reassign: ["error", { "props": false }] */
    vueGlobal.prototype.$safeAreaPatch = this
  },
}
