Track.js 5.28 KB
/**

 */
// import mapApi from '../mapapi/mapapi'
import api from "~/api/request/http";
import { getUserInfo } from "~/utils/cache/userInfo";
// 实例化对象存储
// import { Storage } from "~/utils/cache/storage";
// const $Storage = wx.p.storage

let TRACK_TIME = null,
  ADDRESS_INFO = null;
const track_interval_time = 30 * 1e3;

class TRACK {
  constructor() {
    console.log("---------------- 埋点初始化 ----------------");
    this.initPageProxy();
    this.appShow();
    this.appHide();
    this.startInterval();
  }

  startInterval() {
    if (TRACK_TIME) clearInterval(TRACK_TIME);
    TRACK_TIME = setInterval(() => {
      this.sendEventData();
    }, track_interval_time);
  }

  stopInterval() {
    if (TRACK_TIME) {
      clearInterval(TRACK_TIME);
      TRACK_TIME = null;
    }
  }
  /**监听页面 */
  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 () {
      onLoad && onLoad.apply(this, arguments);
      //, _this.setTrack({
      //   enterTime: new Date().format('yyyy-MM-dd hh:mm:ss')
      // })
    };
    thisPage.onShow = function () {
      (onShow && onShow.apply(this, arguments),
        (_this.getPageInstance().page_show_time = Date.now()));
    };
    thisPage.onHide = function () {
      let { page_show_time } = _this.getPageInstance();
      onHide && onHide.apply(this, arguments);
      // ,_this.setTrack(
      //     {
      //       duration: getDuration(page_show_time)
      //     },
      //     2
      //   )
    };
    thisPage.onUnload = function () {
      let { page_show_time } = _this.getPageInstance();
      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(() => {
      this.stopInterval();
      this.startInterval();
      console.log("---------------- 重新打开埋点定时器 ----------------");
    });
  }
  appHide() {
    wx.onAppHide(() => {
      this.sendEventData(); // 隐藏时顺便兜底发一次
      this.stopInterval();
      console.log(
        "---------------- APP隐藏 埋点停止推送定时器 ----------------",
      );
    });
  }

  /**
   * 上报埋点事件
   * @param {String} eventCode 事件代码
   * @param {Array} businessKeys 业务对象键值 [{businessType: "xxx", businessKey: "xxx"}]
   */
  reportEvent(eventCode, businessKeys = []) {
    if (!eventCode) return;

    let eventTime = "";
    if (Date.prototype.format) {
      eventTime = new Date().format("yyyy-MM-dd hh:mm:ss");
    }

    const eventItem = {
      eventCode,
      eventTime,
      businessKeys,
    };

    let recordList = wx.p.storage.get("eventRecordList") || [];
    recordList.push(eventItem);
    wx.p.storage.set("eventRecordList", recordList);

    // 超过指定条数,触发发送
    if (recordList.length > 9) {
      this.sendEventData();
    }
  }

  /**
   * 将缓存中的埋点数据批量发送给服务端
   */
  sendEventData() {
    let recordList = wx.p.storage.get("eventRecordList");
    if (!recordList || !recordList.length) return;

    // 接口:/vr-api/rest/eventTracking/batchSave
    api
      .post(
        {
          method: "/rest/eventTracking/batchSave",
          projectName: "vr",
          events: recordList,
        },
        false,
      )
      .then((res) => {
        // 发送成功后清空队列
        wx.p.storage.set("eventRecordList", []);
        console.log(
          "---------------- 埋点定时推送成功 ----------------",
          recordList,
        );
      })
      .catch((err) => {
        console.log("---------------- 埋点推定时送失败 ----------------", err);
      });
  }

  /**获取页面对象实例 */
  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) {
      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 } =
      wx.p.storage.get("system_info");
    return {
      SDK_version: SDKVersion,
      brand,
      model,
      system,
      version,
    };
  }
}

wx.$Track = new TRACK();