<template>
  <uni-web-view v-on="$listeners" />
</template>
<script>
import {
  WEBVIEW_INSERTED,
  WEBVIEW_REMOVED,
  WEBVIEW_ID_PREFIX
} from '../../../constants'

import { NAVBAR_HEIGHT } from 'uni-helpers/constants'

let webview = false
const insertHTMLWebView = ({
  webviewStyles,
  htmlId,
  updateTitle
}) => {
  const parentWebview = plus.webview.currentWebview()
  // fixed by hxy web-view 组件所在的 webview 不注入 uni-app 框架
  const styles = Object.assign(
    {
      'uni-app': 'none',
      isUniH5: true,
      // ios 默认绘制到安全区外
      contentAdjust: false
    },
    webviewStyles
  )
  const parentTitleNView = parentWebview.getTitleNView()
  if (parentTitleNView) {
    if (plus.navigator.isImmersedStatusbar()) {
      styles.top = NAVBAR_HEIGHT + plus.navigator.getStatusbarHeight()
    } else {
      styles.top = NAVBAR_HEIGHT
    }
    styles.bottom = 0
  }
  webview = plus.webview.create('', htmlId, styles)
  if (parentTitleNView) {
    webview.addEventListener('titleUpdate', function () {
      if (!updateTitle) return
      const title = webview.getTitle()
      parentWebview.setStyle({
        titleNView: {
          // iOS titleText 为空字符串时 按钮会隐藏
          titleText: (!title || title === 'null') ? ' ' : title
        }
      })
    })
  }
  plus.webview.currentWebview().append(webview)
}

const updateHTMLWebView = ({
  src,
  webviewStyles
}) => {
  // fixed by xxx 非空时才执行更新操作
  const realPath = src || ''
  if (!realPath) {
    return
  }
  if (/^(http|https):\/\//.test(realPath) && webviewStyles.progress) {
    webview.setStyle({
      progress: {
        color: webviewStyles.progress.color
      }
    })
  }
  webview.loadURL(realPath)
}

const removeHTMLWebView = () => {
  plus.webview.currentWebview().remove(webview)
  webview.close('none')
  webview = false
}

export default {
  name: 'WebView',
  props: {
    src: {
      type: String,
      default: ''
    },
    updateTitle: {
      type: Boolean,
      default: true
    },
    webviewStyles: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  watch: {
    src (val, oldVal) {
      webview && updateHTMLWebView({
        src: this.$getRealPath(val),
        webviewStyles: this.webviewStyles
      })
    }
  },
  mounted () {
    this.htmlId = WEBVIEW_ID_PREFIX + this.$page.id
    insertHTMLWebView({
      webviewStyles: this.webviewStyles,
      htmlId: this.htmlId,
      updateTitle: this.updateTitle
    })
    updateHTMLWebView({
      src: this.$getRealPath(this.src),
      webviewStyles: this.webviewStyles
    })
    UniViewJSBridge.publishHandler(WEBVIEW_INSERTED, {}, this.$page.id)
  },
  beforeDestroy () {
    removeHTMLWebView()
    UniViewJSBridge.publishHandler(WEBVIEW_REMOVED, {}, this.$page.id)
  }
}
</script>
<style>
  uni-web-view {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
</style>
