webViewCommon.js 7.48 KB
// pages/webView/webViewCommon.js — 与 webView、h5Full(全屏 web-view)共用逻辑
import commonApi from '~/api/api'

const WEBVIEW_H5_TOKENS_KEY = 'dj_boutique_webview_h5_tokens'

let time

export function createWebViewPage(sharePagePath) {
  return {
    data: {
      flag: true,
			isH5Bind: false,
			shareTitle: '报告详情',
    //   isH5Bind: false,
      shareDisabled: false
    },

    getBaseUrl(url) {
      if (!url || typeof url !== 'string') return ''
      const idx = url.indexOf('?')
      return idx >= 0 ? url.slice(0, idx) : url
    },

    appendParamsToUrl(url, params) {
      if (!params || typeof params !== 'object' || Object.keys(params).length === 0)
        return url
      const searchParams = Object.entries(params)
        .filter(([, v]) => v != null && v !== '')
        .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
        .join('&')
      if (!searchParams) return url
      const separator = url.includes('?') ? '&' : '?'
      return `${url}${separator}${searchParams}`
    },

    getParams(str) {
      let params = str.split('?')
      if (params.length < 2) return {}
      let param = params[1].split('&')
      let obj = {}
      for (let i = 0; i < param.length; i++) {
        let paramsA = param[i].split('=')
        let key = paramsA[0]
        let value = paramsA[1]
        obj[key] = value
      }
      return obj
		},
		
    onLoad: function (options) {
      const shareDisabled = options.noShare === '1' || options.noShare === 'true'
      this.setData({ shareDisabled })
      wx.$util.showLoading('加载中...')
      let decodeUrl = decodeURIComponent(options.url)
			const baseUrl = this.getBaseUrl(decodeUrl)
      if (
        options.openType &&
        !/[?&#]openType=/.test(decodeUrl)
      ) {
        decodeUrl = this.appendParamsToUrl(decodeUrl, {
          openType: options.openType
        })
			}
    //   const baseUrl = this.getBaseUrl(decodeUrl)
      try {
        const stored = wx.getStorageSync(WEBVIEW_H5_TOKENS_KEY)
        if (stored) {
          const tokens = JSON.parse(stored)
          const storedData = tokens[baseUrl]
          if (storedData && typeof storedData === 'object') {
            decodeUrl = this.appendParamsToUrl(decodeUrl, storedData)
          }
        }
      } catch (e) {}
      let param = this.getParams(decodeUrl)
      if (param.urlParam) {
        let query = JSON.parse(param.urlParam)
        this.refresh = query.refresh
      }
      console.log(decodeUrl)
      this.setData({
        url: decodeUrl
      })
      wx.hideLoading()
      if (shareDisabled) {
        // 无参 hideShareMenu 全端隐藏「转发」;带 menus 的能力在部分系统上为 Beta/仅 Android,不能单独依赖
        wx.hideShareMenu()
        wx.hideShareMenu({
          menus: ['shareAppMessage', 'shareTimeline']
        })
      } else {
        wx.showShareMenu({
          withShareTicket: true,
          menus: ['shareAppMessage', 'shareTimeline']
        })
      }
      if (param.needIntercept) {
        wx.enableAlertBeforeUnload &&
          wx.enableAlertBeforeUnload({
            message: '您还没有完成本次短课程学习,是否确定退出?',
            success: modalRes => {
              if (modalRes.confirm) {
                wx.navigateBack()
              }
            }
          })
        this.setTime(param)
			}
			// AI收车报告,特殊处理跳转,将登录人名称带入
			if (decodeUrl.includes('/ai-purchase') && options?.pushed) {
				let userInfo = wx.$util.getUserInfo()
				this.setData({
					url: `${decodeUrl}?pushed=${options.pushed}&source=${options.source}&carConditionCode=${options.carConditionCode}&operator=${userInfo.name}`
				})
			}
			if (decodeUrl.includes('/vehicle-detail')) this.setData({shareTitle: '车况信息'})
    },

    setTime(param) {
      time = setTimeout(() => {
        commonApi
          .getShortCourseDetail({
            id: param?.studyId
          })
          .then(res => {
            let { code, data } = res
            this.setTime()
            if (code == 0) {
              let flag = data?.aiReviewReport.every(item => item.examStatus === 2)
              if (flag) wx.disableAlertBeforeUnload()
            }
          })
      }, 5 * 1000)
    },

    onReady: function () {},

    onShow: function () {
      if (this.data.shareDisabled) {
        wx.hideShareMenu()
        wx.hideShareMenu({
          menus: ['shareAppMessage', 'shareTimeline']
        })
      }
      if (this.refresh) {
        this.setData(
          {
            flag: true
          },
          () => {
            this.setData({
              url: this.data.url
            })
          }
        )
			}
    },

    onHide: function () {
      if (this.refresh) {
        this.setData({
          flag: false
        })
      }
    },

    handleMessage(e) {
      const { data } = e.detail
      console.log(data, 'handleMessage')
      if (data) {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('webViewMessage', data[0])
        this.setData({
          isH5Bind: true
        })
        const msgData = data[0]
        if (msgData && typeof msgData === 'object' && msgData !== null) {
          const baseUrl = this.getBaseUrl(this.data.url)
          if (baseUrl) {
            try {
              const stored = wx.getStorageSync(WEBVIEW_H5_TOKENS_KEY)
              const tokens = stored ? JSON.parse(stored) : {}
              tokens[baseUrl] = msgData
              wx.setStorageSync(WEBVIEW_H5_TOKENS_KEY, JSON.stringify(tokens))
            } catch (err) {}
          }
        }
      }
    },

    onUnload: function () {
      let { url } = this.data
      if (this.refresh) {
        this.setData({
          flag: false
        })
      }
      if (url.includes('zyUpload')) {
        const eventChannel = this.getOpenerEventChannel()
        if (!this.data.isH5Bind) {
          eventChannel.emit('webViewMessage', 'cancel')
        }
      }
      if (url.includes('LearningExamTraineePage')) {
        wx.setStorageSync('FROM_BEISENWEBVIEW', '1')
      }
      time && clearTimeout(time)
    },

    onPullDownRefresh: function () {},

    onReachBottom: function () {},

    onShareAppMessage(options) {
			const { url, shareTitle } = this.data
			if (options?.webviewUrl?.includes('/vehicle-detail')) shareTitle = '车况信息'
    // onShareAppMessage() {
      if (this.data.shareDisabled) return
    //   const { url } = this.data
      const encoded = encodeURIComponent(url || '')
      return {
        title: shareTitle,
        path: `${sharePagePath}?url=${encoded}`
      }
    },

    onShareTimeline() {
			const { url, shareTitle } = this.data
			if (options?.webviewUrl?.includes('/vehicle-detail')) shareTitle = '车况信息'
      if (this.data.shareDisabled) return
    //   const { url } = this.data
      const encoded = encodeURIComponent(url || '')
      return {
        title: shareTitle,
        query: `url=${encoded}`
      }
    }
  }
}

/**
 * 全屏 web-view,且不注册 onShareAppMessage / onShareTimeline。
 * 微信规则:只有定义了这两个回调,右上角才会出现「转发 / 朋友圈」;
 * 仅靠 return {} 或 hideShareMenu 在部分环境下仍可能可转发。
 */
export function createWebViewPageNoShare() {
  const page = createWebViewPage('/pages/webView/h5FullNoShare')
  delete page.onShareAppMessage
  delete page.onShareTimeline
  const origOnLoad = page.onLoad
  page.onLoad = function (options) {
    return origOnLoad.call(this, { ...options, noShare: '1' })
  }
  return page
}