<template>
  <view>
    <web-view :src="url" @message="handleMessage"></web-view>
  </view>
</template>
<script>
import {
  hideTabBar,
  showTabBar,
  loadLocation,
  Face_UP,
  Camera_UP,
} from './utils'
import { CheckContactPermission, SelectContact } from './authPermission'
import storage from '@/utils/storage'
export default {
  data() {
    return {
      wv: null,
      url: null,
      canBack: false,
    }
  },
  async onShow() {
    if (!this.$options.filters.isLogin('auth')) {
      this.$options.filters.navigateToLogin()
    }
    if (this.wv) {
      this.wv.evalJS(`callback({ 'action': 'OnShow' })`)
      this.wv.reload()
    }
  },
  onLoad() {
    
  },
  onBackPress(e) {
    if (this.wv && this.canBack) {
      this.wv.back()
      return true
    }
    return false
  },
  onReady() {
    const _that = this
    // #ifdef APP-PLUS
    let statusBarHeight = parseInt(uni.getSystemInfoSync().statusBarHeight)
    let currentWebview = _that.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
    setTimeout(() => {
      this.wv = currentWebview.children()[0]
      this.wv.setStyle({
        top: statusBarHeight, // + plus.navigator.getStatusbarHeight() //设置web-view距离顶部的距离以及自己的高度，单位为px
        bottom: 0, // 如果不把bottom设置为0，可能会与pages.json定义的tabBar，产生一些问题，具体的代码效果，可以去除bottom:0，自行查看一下
      })
      this.wv.setPullToRefresh(
        {
          support: true,
          height: '50px',
          range: '200px',
          contentdown: {
            caption: '下拉刷新',
          },
          contentover: {
            caption: '释放刷新',
          },
          contentrefresh: {
            caption: '正在刷新...',
          },
        },
        _that.onRefresh
      )
      // 物理按键返回
      _that.wv.addEventListener(
        'loaded',
        () => {
          _that.wv.canBack((e) => {
            _that.canBack = e.canBack
          })
        },
        false
      )
    }, 1000) //如果是页面初始化调用时，需要延时一下
    // #endif
  },
  onTabItemTap(e) {
    console.log('点击tabbar', JSON.stringify(e))
  },
  methods: {
    // 刷新页面
    onRefresh() {
      this.wv.evalJS(`callback({ 'action': 'OnRefresh' })`)
      setTimeout(() => {
        uni.showToast({
          title: '刷新成功',
          icon: 'none',
        })
        this.wv.endPullToRefresh()
      }, 1200)
    },
    async handleMessage(e) {
      console.log('接收到网页发来的消息', JSON.stringify(e.detail.data[0]))
      const message = e.detail.data[0]
      switch (message.action) {
        case 'hideTabBar': // 隐藏tabbar
          hideTabBar()
          break
        case 'showTabBar': // 显示tabbar
          showTabBar()
          break
        case 'GetUserIsLogin': // 用户是否登陆
          const subNVue = uni.getSubNVueById('loan-popup') //  对应page.json的id
          // 1:子窗体从顶部进入（动画效果）, 2:显示原生子窗体的动画持续时间
          subNVue.show('slide-in-bottom', 300, () => {
            // 向子窗体传递参数
            uni.$emit('loan-from-popup', {
              appName: '多典花',
              mobile: storage.getUserInfo().mobile,
            })
          })
          break
        case 'DeviceInfo': // 设备信息 m-device-info
          const res = await loadLocation()
          this.wv.evalJS(
            `callback(${JSON.stringify({ action: 'DeviceInfo', result: res })})`
          )
          break
        case 'GetALLContact': // 全部通讯录信息 m-contact
          CheckContactPermission((res) => {
            this.wv.evalJS(
              `callback(${JSON.stringify({
                action: 'GetALLContact',
                result: res,
              })})`
            )
          })
          break
        case 'GetContact': // 选择通讯录
          CheckContactPermission(() => {
            SelectContact((res) => {
              this.wv.evalJS(
                `callback(${JSON.stringify({
                  action: 'GetContact',
                  result: res,
                })})`
              )
            })
          })
          break
        case 'Face_UP':
          /**
           * 人脸验证
           * token
           * requestId
           */
          Face_UP(message.token, message.requestId, (res) => {
            this.wv.evalJS(`callback({action: 'Face_UP', 'result': ${res}})`)
          })
          break
        case 'Camera_UP':
          /**
           * OCR识别
           * token
           * type
           * key
           * secret
           */
          Camera_UP(message.token, message.type, (res) => {
            this.wv.evalJS(
              `callback({action: 'Camera_UP', 'type': ${type}, 'result': ${res}})`
            )
          })
          break
        default:
          break
      }
    },
  },
  onHide() {
    this.wv.evalJS(`callback({ 'action': 'OnHide' })`)
    // 页面销毁之前 移除监听器
    uni.$off('to-popup')
  },
}
</script>
