yas.js 6.45 KB
import udid from './udid';
import Taro from '@tarojs/taro';
import config from '../config';
import rules from '../router/rules';
import { MD5 } from './crypto';
import { parse, stringify } from 'querystringify';
import { getGlobalData } from '../libs/login/login.js'
import pathReport from '../router/path-report';

export default class yas {
    constructor(app) {
        let self = this;

        this.app = app;
        this.pvid = MD5(`${new Date().getTime()}${udid.get()}`).toString();
        this.deviceInfo = {
            os: '', // 系统类型
            dm: '', // 设备型号
            res: '', // 屏幕大小
            osv: '', // 系统版本
            ak: 'yohoufo_mp',
            ch: '',
            udid: udid.get()
        };

        // 获取设备信息
        Taro.getSystemInfo({
            success(res) {
                self.language = res.language;

                if (res.platform === 'devtools') {
                    // self.devEnv = true; //判断开发环境
                }

                Object.assign(self.deviceInfo, {
                    os: res.platform,
                    dm: res.model,
                    res: `${res.screenWidth}*${res.screenHeight}`,
                    osv: res.system,
                });
            }
        });
    }
    uploadData(params) {
        let self = this;
        let sid = '';
        let globalData = getGlobalData() || {};

        sid = self.app.globalData && self.app.globalData.sid || globalData.sid || '';

        return Taro.request({
            url: config.domains.yasHost,
            data: { _mlogs: JSON.stringify(params) },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                'x-yoho-sid': MD5(sid).toString(),
            },
        });
    }
    report(event, info = {}) {
        let self = this;

        for (let key in info) {
            if (info[key]) {
                info[key] = decodeURIComponent(info[key]);
            }
        }

        const pageNameMap = {};

        for (let i in rules) {
            if (rules.hasOwnProperty(i) && rules[i].path) {
                pageNameMap[rules[i].path] = i;
            }
        }

        if (event === 'YB_SHARE_RESULT_L') {
            info.PAGE_NAME = pageNameMap['/' + info.PATH];
        }

        let userInfo = info || {};
        let statusInfo = { ln: this.language };

        let user = Taro.getStorageSync('userInfo') || {};

        userInfo.UNION_ID = user.unionid || user.union_id || Taro.getStorageSync('unionid') || '';
        userInfo.APP_ID = config.appid || '';

        if (!userInfo.PV_ID) {
            userInfo.PV_ID = info.PV_ID;
        }

        return new Promise(resolve => {
            Taro.getNetworkType({
                success(res) {
                    switch (res.networkType) {
                        case 'wifi':
                            statusInfo.net = '1';
                            break;
                        case '2g':
                            statusInfo.net = '2';
                            break;
                        case '3g':
                            statusInfo.net = '3';
                            break;
                        case '4g':
                            statusInfo.net = '4';
                            break;
                        default:
                            statusInfo.net = '0';
                            break;
                    }
                },
                complete() {
                  let globalData = getGlobalData() || {};
                  let userData = globalData.userInfo || {};

                  if (!Object.keys(userData).length) {
                    userData = Taro.getStorageSync('userInfo') || {};
                  }

                  let ch = self.app.globalData && self.app.globalData.ch || globalData.ch || '';
                  let uid = userData.uid || '';

                  self.deviceInfo.ch = ch;
                  return resolve(self.uploadData({
                      status: statusInfo,
                      device: self.deviceInfo,
                      events: [{
                          param: userInfo,
                          ts: new Date().getTime(),
                          op: event,
                          uid: uid,
                          sid: self.app.globalData && self.app.globalData.sid ||globalData.sid || ''
                      }]
                  }));
                }
            });
        });
    }
    _pageName(options, path) {
      let hasConf = pathReport[path];

      // 多入口页面依据参数设定上报页面名称
      if (hasConf && hasConf.multiEntry) {
        let pathName = '';

        Object.keys((hasConf.multiName || {})).forEach(key => {
          if (options[key]) {
            pathName = hasConf.multiName[key];
            return false;
          }
        });
        return pathName;
      }
      return hasConf ? hasConf.pathName : '';
    }
    _pageParam(options = {}, fromPath) {
      if (!options) return '';

      let hasConf = pathReport[fromPath];
      if (hasConf && hasConf.multiEntry) {
        let param = '';

        Object.keys((hasConf.multiName || {})).forEach(key => {
          if (options[key]) {
            param = options[key];
            return false;
          }
        });
        return param;
      }

      if (pathReport[fromPath] && pathReport[fromPath].paramKey) {
        return `${decodeURIComponent(options[pathReport[fromPath].paramKey])}` || '';
      }
      return stringify(options, '');
    }
    pageOpenReport(pvid, extra) {
        let self = this;
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1];
        let path = `${currentPage.route}`,
            options = currentPage.options || {}; // 拷贝options对象,用于获取当前页面参数

        let info = { PV_ID: pvid || this.pvid };

        // from page relevant
        let fromPage, fromPath, fromOptions;
        if (pages.length > 1) {
          fromPage = pages[pages.length - 2];
          fromPath = `${fromPage.route}`;
          fromOptions = fromPage.options || {};
        }

        Object.assign(info, {
          PAGE_PATH: path,
          PAGE_PARAM: self._pageParam(options, path),
          PAGE_NAME: self._pageName(options, path),
          FROM_PAGE_NAME: self._pageName(options, fromPath),
          FROM_PAGE_PARAM: self._pageParam(fromOptions, fromPath)
        });

        this.report('YB_PAGE_OPEN_L', Object.assign(info, extra || {}));
    }
}