Track.js 8.77 KB
/**
 * 使用方法 wx.$Track.setTrack({
 *  参数1:val,
 *  参数2:val,
 *  参数...
 * }, act_id)
 * act_id :{
 *  1:点击,
 *  2:页面离开,
 *  3:登陆
 *  4:退出登录
 *  5:地理位置授权
 *  6:页面预览
 *  7:业务行为
 *
 * }
 */
import mapApi from '~/utils/mapapi/mapapi'
import api from '~/utils/request/request'
let TRACK_TIME = null,
  ADDRESS_INFO = null
const track_interval_time = 60 * 1e3
// 实例化对象存储
import {
  Storage
} from '~/utils/cache/storage'
const $Storage = new Storage()

class TRACK {
  _customObject = {}
  constructor(options, customObject = {
    onLoadFun: [],
    onShowFun: [],
    onHideFun: []
  }) {
    if (options.scene == 1154 && options.mode == 'singlePage') return //朋友圈单页模式
    console.log('---------------- 埋点初始化 ----------------')
    this.initPageProxy()
    this.sendTrack()
    this.getAddressInfo().then(res => (ADDRESS_INFO = res))
    this.appHide()
    this._customObject = customObject
  }
  /**监听页面 */
  pageLeaveProxy(thisPage) {
    let _this = this,
      onHide = thisPage.onHide,
      onUnload = thisPage.onUnload,
      onLoad = thisPage.onLoad,
      onShow = thisPage.onShow,
      onTabItemTap = thisPage.onTabItemTap
    thisPage.onTabItemTap = function (options) {
      onTabItemTap && onTabItemTap.apply(this, arguments), _this.setTrack({}, 1)
    }
    thisPage.onLoad = function () {
      _this.customPageFun({
        options: arguments[0],
        thisPage: this
      }, 'onLoadFun')
      onLoad && onLoad.apply(this, arguments)
      //, _this.setTrack({
      //   enterTime: new Date().format('yyyy-MM-dd hh:mm:ss')
      // })
    }
    thisPage.onShow = function () {
      _this.customPageFun({
        thisPage: this
      }, 'onShowFun')
      onShow && onShow.apply(this, arguments), (_this.getPageInstance().page_show_time = Date.now())
    }
    thisPage.onHide = function () {
      let {
        page_show_time
      } = _this.getPageInstance()
      _this.customPageFun({
        thisPage: this
      }, 'onHideFun')
      onHide && onHide.apply(this, arguments),
        _this.setTrack({
            duration: getDuration(page_show_time)
          },
          2
        )
    }
    thisPage.onUnload = function () {
      let {
        page_show_time
      } = _this.getPageInstance()
      _this.customPageFun({
        thisPage: this
      }, 'onHideFun')
      onUnload && onUnload.apply(this, arguments),
        _this.setTrack({
            duration: getDuration(page_show_time)
          },
          2
        )
    }
    const getDuration = page_show_time => (Date.now() - page_show_time) / 1e3
  }
  /**全局注册事件 */
  initPageProxy() {
    let thisPage = Page
    let _this = this
    Page = function (el) {
      try {
        el || (el = {}), _this.pageLeaveProxy(el), thisPage.apply(this, arguments)
      } catch (el) {
        thisPage.apply(this, arguments)
      }
    }
  }
  appShow() {
    wx.onAppShow(() => {
      if (TRACK_TIME) clearInterval(TRACK_TIME)
      this.sendTrack()
      wx.offAppShow()
      this.appHide()
      // console.log('---------------- 重新打开埋点 ----------------')
    })
  }
  appHide() {
    wx.onAppHide(() => {
      if (TRACK_TIME) clearInterval(TRACK_TIME)
      wx.offAppHide()
      this.appShow()
      // console.log('---------------- APP隐藏 埋点停止推送 ----------------')
    })
  }
  /**设置埋点数据 */
  setTrack(e, act_id = 1) {
    // console.log('---------------- 获取小程序启动时的参数 ----------------', wx.getLaunchOptionsSync())
    let {
      route
    } = this.getPageInstance(), {
        query
      } = wx.getLaunchOptionsSync(),
      prepare_data = wx.getStorageSync('prepare_data'),
      last_time = wx.getStorageSync('track_last_time'),
      now = new Date().format('yyyy-MM-dd hh:mm:ss'),
      merchantInfo = this.getMerchantInfo(),
      userInfo = wx.$util.getUserInfo(),
      systemInfo = this.getSystemInfo(),
      page_title = this.getPageTitle(),
      guest_no = this.getGuestNo(),
      storageQuery = wx.getStorageSync('track_query')
    if (!last_time) last_time = now
    let data = {
      burying_pointa: 'DJ_MINIPROGRAM',
      plateform: 'miniprogram',
      create_time: now,
      ...merchantInfo,
      add_way: '104',
      page_id: route,
      act_status: 0,
      last_time,
      guest_no,
      act_id,
      ext: {
        ...systemInfo,
        page_title,
        ...e
      }
    }
    wx.setStorageSync('track_last_time', now)
    if (userInfo) {
      /**用户信息 */
      if (userInfo.openId) data.open_id = userInfo.openId
      if (userInfo.unionId) data.union_id = userInfo.unionId
      if (userInfo.phone) data.customer_phone = userInfo.phone
    }
    if (ADDRESS_INFO) {
      data.addr = ADDRESS_INFO.address
      data.gps = ADDRESS_INFO.location
    }

    if (Object.keys(query).length) {
      data.entry_id = query
      wx.setStorageSync('storageQuery', query)
    } else data.entry_id = storageQuery
    // console.log('---------------- 触发了埋点 ----------------', data)
    if (!prepare_data) prepare_data = []
    prepare_data.push(JSON.stringify(data))
    wx.setStorageSync('prepare_data', prepare_data)
  }
  getGuestNo() {
    let guest_no = wx.getStorageSync('guest_no')
    if (!guest_no) {
      guest_no = this.setGuestNo()
      wx.setStorageSync('guest_no', guest_no)
    }
    return guest_no
  }
  /**定时发送埋点数据 */
  sendTrack() {
    TRACK_TIME = setInterval(() => {
      let prepare_data = wx.getStorageSync('prepare_data')
      let data = {
        method: 'entmicro.api.customercollect.reportCustomerList',
        jsonList: prepare_data
      }
      if (prepare_data && prepare_data.length)
        api.reportTrack(data).then(({
          code,
          data,
          message
        }) => {
          if (code == 0 && data) {
            wx.setStorageSync('prepare_data', [])
            // console.log('---------------- 埋点定时推送成功 ----------------', new Date().format('yyyy-MM-dd hh:mm:ss'), ':', prepare_data)
          } else console.log('---------------- 埋点定时推送失败 ----------------', new Date().format('yyyy-MM-dd hh:mm:ss'), ':', message)
        })
    }, track_interval_time)
  }
  /**获取页面对象实例 */
  getPageInstance = (size = 1) => {
    const pages = getCurrentPages()
    return pages[pages.length - size]
  }
  /**获取页面标题 */
  getPageTitle() {
    let {
      route,
      navigationBarTitleText
    } = this.getPageInstance()
    if ('\u672a\u53d6\u5230' === route || !route) return ''
    let title = ''
    if (__wxConfig && __wxConfig.page) {
      let {
        window
      } = __wxConfig.page[`${route}.html`] || {}
      title = window.navigationStyle == 'custom' ? navigationBarTitleText : window.navigationBarTitleText
    }
    if (!title) title = '嘀加智享车生活'
    return title
  }
  /**获取设备信息 */
  getSystemInfo() {
    let {
      SDKVersion,
      brand,
      model,
      system,
      version
    } = $Storage.get('system_info')
    return {
      SDK_version: SDKVersion,
      brand,
      model,
      system,
      version
    }
  }
  /**获取门店信息 */
  getMerchantInfo() {
    let {
      merchantId
    } = wx.getStorageSync('merchant_info')
    return {
      merchant_id: merchantId
    }
  }
  /**获取用户位置信息 */
  getAddressInfo(options) {
    let addressInfo = wx.getStorageSync('address_info')
    return new Promise(resolve => {
      if (addressInfo && Date.now() - addressInfo.createTime < 2 * 60 * 1e3) resolve(addressInfo)
      else
        wx.getLocation({
          type: 'gcj02'
        }).then(({
          latitude,
          longitude
        }) => {
          if (!addressInfo) this.setTrack({}, 5)
          console.log('---------------- 更新地理位置 ----------------')
          mapApi.detailedAdrress([latitude, longitude]).then(detail => {
            let info = {
              ...detail,
              createTime: Date.now()
            }
            resolve(info)
            wx.setStorageSync('address_info', info)
          })
        }).catch(err => {
          console.log(err)
        })
    })
  }
  /**获取游客ID */
  setGuestNo(length = 30) {
    let name = '',
      n = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    for (let i = 0; i < Number(length); i++) {
      name += n[Math.round(Math.random() * (n.length - 1))]
    }
    return `DJ_${name}_${Date.now()}`
  }

  /**在全局埋点onShow增加自定义埋点事件 */
  customPageFun(options, name) {
    this._customObject[name]?.map(e => {
      e && e(options)
    })
  }
}
export default TRACK