uni-stat.es.js 35.1 KB
Newer Older
M
mehaotian 已提交
1 2 3 4 5 6
/**
 * 获取系统信息
 */
const sys = uni.getSystemInfoSync();

// 访问开始即启动小程序,访问结束结分为:进入后台超过5min、在前台无任何操作超过30min、在新的来源打开小程序;
M
mehaotian 已提交
7
const STAT_VERSION = process.env.UNI_COMPILER_VERSION;
M
mehaotian 已提交
8 9 10 11 12 13 14
const STAT_URL = 'https://tongji.dcloud.io/uni/stat';
const STAT_H5_URL = 'https://tongji.dcloud.io/uni/stat.gif';
const PAGE_PVER_TIME = 1800; // 页面在前台无操作结束访问时间 单位s
const APP_PVER_TIME = 300; // 应用在后台结束访问时间 单位s
const OPERATING_TIME = 10; // 数据上报时间 单位s
const DIFF_TIME = 60 * 1000 * 60 * 24;

M
mehaotian 已提交
15 16
// 获取 manifest.json 中统计配置
const uniStatisticsConfig = process.env.UNI_STATISTICS_CONFIG;
M
mehaotian 已提交
17
let statConfig = {
M
mehaotian 已提交
18 19 20 21 22 23
  appid: process.env.UNI_APP_ID,
};
let titleJsons = {};
let debug = !!process.env.UNI_STAT_DEBUG || false;
// #ifdef VUE3
titleJsons = process.env.UNI_STAT_TITLE_JSON;
M
mehaotian 已提交
24
// #endif
25

M
mehaotian 已提交
26
// #ifndef VUE3
27

M
mehaotian 已提交
28 29
// eslint-disable-next-line no-restricted-globals
const pagesTitle = require('uni-pages?{"type":"style"}').default;
M
mehaotian 已提交
30
let pagesData = pagesTitle.pages;
M
mehaotian 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43
for (let i in pagesData) {
  const style = pagesData[i];
  const titleText =
    // MP
    style.navigationBarTitleText ||
    // ali
    style.defaultTitle ||
    // H5 || App
    style.navigationBar?.titleText ||
    '';
  if (titleText) {
    titleJsons[i] = titleText;
  }
M
mehaotian 已提交
44
}
M
mehaotian 已提交
45
// #endif
M
mehaotian 已提交
46

M
mehaotian 已提交
47
// TODO 在云函数中获取,暂时注释
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
const UUID_KEY = '__DC_STAT_UUID';
const UUID_VALUE = '__DC_UUID_VALUE';
function getUuid() {
  let uuid = '';
  if (get_platform_name() === 'n') {
    try {
      uuid = plus.runtime.getDCloudId();
    } catch (e) {
      uuid = '';
    }
    return uuid
  }

  try {
    uuid = uni.getStorageSync(UUID_KEY);
  } catch (e) {
    uuid = UUID_VALUE;
  }

  if (!uuid) {
    uuid = Date.now() + '' + Math.floor(Math.random() * 1e7);
    try {
      uni.setStorageSync(UUID_KEY, uuid);
    } catch (e) {
      uni.setStorageSync(UUID_KEY, UUID_VALUE);
    }
  }
  return uuid
}

const get_uuid = (statData) => {
  // 有可能不存在 deviceId(一般不存在就是出bug了),就自己生成一个
  return sys.deviceId || getUuid()
};
M
mehaotian 已提交
82

M
mehaotian 已提交
83 84
/**
 * 获取配置信息 如 appid
M
mehaotian 已提交
85
 */
M
mehaotian 已提交
86
const stat_config = statConfig;
M
mehaotian 已提交
87 88

const get_sgin = (statData) => {
M
mehaotian 已提交
89 90 91 92 93 94 95 96
  let arr = Object.keys(statData);
  let sortArr = arr.sort();
  let sgin = {};
  let sginStr = '';
  for (var i in sortArr) {
    sgin[sortArr[i]] = statData[sortArr[i]];
    sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&';
  }
M
mehaotian 已提交
97

M
mehaotian 已提交
98 99 100 101 102 103 104 105 106 107 108 109
  return {
    sign: '',
    options: sginStr.substr(0, sginStr.length - 1),
  }
};

const get_encodeURIComponent_options = (statData) => {
  let data = {};
  for (let prop in statData) {
    data[prop] = encodeURIComponent(statData[prop]);
  }
  return data
M
mehaotian 已提交
110 111 112
};

/**
M
mehaotian 已提交
113
 * 获取当前平台
M
mehaotian 已提交
114 115 116 117 118 119 120 121 122
 * 移动端  : 'n',
 * h5	  : 'h5',
 * 微信	  : 'wx',
 * 阿里	  : 'ali',
 * 百度	  : 'bd',
 * 头条	  : 'tt',
 * qq	  : 'qq',
 * 快应用  : 'qn',
 * 快手	  : 'ks',
M
mehaotian 已提交
123 124
 * 飞书	  : 'lark',
 * 快应用  : 'qw',
M
mehaotian 已提交
125 126 127
 * 钉钉	  : 'dt'
 */
const get_platform_name = () => {
M
mehaotian 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  // 苹果审核代码中禁止出现 alipay 字样 ,需要特殊处理一下
  const aliArr = ['y', 'a', 'p', 'mp-ali'];
  const platformList = {
    app: 'n',
    'app-plus': 'n',
    h5: 'h5',
    'mp-weixin': 'wx',
    [aliArr.reverse().join('')]: 'ali',
    'mp-baidu': 'bd',
    'mp-toutiao': 'tt',
    'mp-qq': 'qq',
    'quickapp-native': 'qn',
    'mp-kuaishou': 'ks',
    'mp-lark': 'lark',
    'quickapp-webview': 'qw',
  };
  if (platformList[process.env.VUE_APP_PLATFORM] === 'ali') {
    if (my && my.env) {
      const clientName = my.env.clientName;
      if (clientName === 'ap') return 'ali'
      if (clientName === 'dingtalk') return 'dt'
      // TODO 缺少 ali 下的其他平台
    }
  }
  return platformList[process.env.VUE_APP_PLATFORM]
M
mehaotian 已提交
153 154 155 156 157 158
};

/**
 * 获取小程序 appid
 */
const get_pack_name = () => {
M
mehaotian 已提交
159 160 161 162 163 164 165 166 167
  let packName = '';
  if (get_platform_name() === 'wx' || get_platform_name() === 'qq') {
    // 兼容微信小程序低版本基础库
    if (uni.canIUse('getAccountInfoSync')) {
      packName = uni.getAccountInfoSync().miniProgram.appId || '';
    }
  }
  if (get_platform_name() === 'n') ;
  return packName
M
mehaotian 已提交
168 169 170 171 172 173
};

/**
 * 应用版本
 */
const get_version = () => {
M
mehaotian 已提交
174
  return get_platform_name() === 'n' ? plus.runtime.version : ''
M
mehaotian 已提交
175 176 177 178 179 180
};

/**
 * 获取渠道
 */
const get_channel = () => {
M
mehaotian 已提交
181 182 183 184 185 186
  const platformName = get_platform_name();
  let channel = '';
  if (platformName === 'n') {
    channel = plus.runtime.channel;
  }
  return channel
M
mehaotian 已提交
187 188 189 190 191 192 193
};

/**
 * 获取小程序场景值
 * @param {Object} options 页面信息
 */
const get_scene = (options) => {
M
mehaotian 已提交
194 195 196 197 198 199 200 201 202
  const platformName = get_platform_name();
  let scene = '';
  if (options) {
    return options
  }
  if (platformName === 'wx') {
    scene = uni.getLaunchOptionsSync().scene;
  }
  return scene
M
mehaotian 已提交
203 204 205 206 207 208
};

/**
 * 获取拼接参数
 */
const get_splicing = (data) => {
M
mehaotian 已提交
209 210 211 212 213
  let str = '';
  for (var i in data) {
    str += i + '=' + data[i] + '&';
  }
  return str.substr(0, str.length - 1)
M
mehaotian 已提交
214 215 216 217 218
};

/**
 * 获取页面url,不包含参数
 */
M
mehaotian 已提交
219
const get_route$1 = (pageVm) => {
M
mehaotian 已提交
220 221 222 223 224 225
  let _self = pageVm || get_page_vm();
  if (get_platform_name() === 'bd') {
    let mp_route = _self.$mp && _self.$mp.page && _self.$mp.page.is;
    let scope_route = _self.$scope && _self.$scope.is;
    return mp_route || scope_route || ''
  } else {
M
mehaotian 已提交
226 227 228 229 230
    return (
      _self.route ||
      (_self.$scope && _self.$scope.route) ||
      (_self.$mp && _self.$mp.page.route)
    )
M
mehaotian 已提交
231 232 233 234 235 236 237 238 239 240
  }
};

/**
 * 获取页面url, 包含参数
 */
const get_page_route = (pageVm) => {
  // 从 app 进入应用 ,没有 $page ,获取不到路由 ,需要获取页面 尝试从 getCurrentPages 获取也页面实例
  // FIXME 尽量不使用 getCurrentPages ,大部分获取路由是从 onHide 获取 ,这时可以获取到,如果是 onload ,则可能获取不到,比如 百度

M
mehaotian 已提交
241
  let page = pageVm && (pageVm.$page || (pageVm.$scope && pageVm.$scope.$page));
M
mehaotian 已提交
242
  let lastPageRoute = uni.getStorageSync('_STAT_LAST_PAGE_ROUTE');
M
mehaotian 已提交
243
  if (!page) return lastPageRoute || ''
M
mehaotian 已提交
244
  // 如果找不到 fullPath 就取 route 的值
M
mehaotian 已提交
245
  return page.fullPath === '/' ? page.route : page.fullPath || page.route
M
mehaotian 已提交
246 247
};

M
mehaotian 已提交
248 249
/**
 * 获取页面实例
M
mehaotian 已提交
250 251
 */
const get_page_vm = () => {
M
mehaotian 已提交
252 253 254 255
  let pages = getCurrentPages();
  let $page = pages[pages.length - 1];
  if (!$page) return null
  return $page.$vm
M
mehaotian 已提交
256 257 258 259 260 261
};

/**
 * 获取页面类型
 */
const get_page_types = (self) => {
M
mehaotian 已提交
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  // XXX 百度有问题 ,获取的都是 componet ,等待修复
  if (
    self.mpType === 'page' ||
    self.$mpType === 'page' ||
    (self.$mp && self.$mp.mpType === 'page') ||
    self.$options.mpType === 'page'
  ) {
    return 'page'
  }
  if (
    self.mpType === 'app' ||
    self.$mpType === 'app' ||
    (self.$mp && self.$mp.mpType === 'app') ||
    self.$options.mpType === 'app'
  ) {
    return 'app'
  }
  return null
M
mehaotian 已提交
280 281 282 283 284 285 286
};

/**
 * 处理上报参数
 * @param {Object}  需要处理的数据
 */
const handle_data = (statData) => {
M
mehaotian 已提交
287 288 289 290 291 292
  let firstArr = [];
  let contentArr = [];
  let lastArr = [];
  for (let i in statData) {
    const rd = statData[i];
    rd.forEach((elm) => {
M
mehaotian 已提交
293 294
      let newData = '';
      {
295
        newData = get_splicing(elm);
M
mehaotian 已提交
296
      }
M
mehaotian 已提交
297 298 299 300 301 302 303 304 305
      if (i === 0) {
        firstArr.push(newData);
      } else if (i === 3) {
        lastArr.push(newData);
      } else {
        contentArr.push(newData);
      }
    });
  }
M
mehaotian 已提交
306

M
mehaotian 已提交
307 308 309
  firstArr.push(...contentArr, ...lastArr);
  // 参数需要处理成字符串,方便上传
  return JSON.stringify(firstArr)
M
mehaotian 已提交
310 311 312 313 314 315
};

/**
 * 自定义事件参数校验
 */
const calibration = (eventName, options) => {
M
mehaotian 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  //  login 、 share 、pay_success 、pay_fail 、register 、title
  if (!eventName) {
    console.error(`uni.report Missing [eventName] parameter`);
    return true
  }
  if (typeof eventName !== 'string') {
    console.error(
      `uni.report [eventName] Parameter type error, it can only be of type String`
    );
    return true
  }
  if (eventName.length > 255) {
    console.error(
      `uni.report [eventName] Parameter length cannot be greater than 255`
    );
    return true
  }
M
mehaotian 已提交
333

M
mehaotian 已提交
334 335 336 337 338 339
  if (typeof options !== 'string' && typeof options !== 'object') {
    console.error(
      'uni.report [options] Parameter type error, Only supports String or Object type'
    );
    return true
  }
M
mehaotian 已提交
340

M
mehaotian 已提交
341 342 343 344 345 346
  if (typeof options === 'string' && options.length > 255) {
    console.error(
      `uni.report [options] Parameter length cannot be greater than 255`
    );
    return true
  }
M
mehaotian 已提交
347

M
mehaotian 已提交
348 349 350 351 352 353
  if (eventName === 'title' && typeof options !== 'string') {
    console.error(
      `uni.report [eventName] When the parameter is title, the [options] parameter can only be of type String`
    );
    return true
  }
M
mehaotian 已提交
354 355 356
};

const get_page_name = (routepath) => {
M
mehaotian 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
  return (titleJsons && titleJsons[routepath]) || ''
};

const Report_Data_Time = 'Report_Data_Time';
const Report_Status = 'Report_Status';
const is_report_data = () => {
  return new Promise((resolve, reject) => {
    let start_time = '';
    let end_time = new Date().getTime();
    let diff_time = DIFF_TIME;
    let report_status = 1;
    try {
      start_time = uni.getStorageSync(Report_Data_Time);
      report_status = uni.getStorageSync(Report_Status);
    } catch (e) {
      start_time = '';
      report_status = 1;
    }

    if (report_status === '') {
      requestData(({ enable }) => {
        uni.setStorageSync(Report_Data_Time, end_time);
        uni.setStorageSync(Report_Status, enable);
        if (enable === 1) {
          resolve();
        }
      });
      return
    }

    if (report_status === 1) {
      resolve();
    }

    if (!start_time) {
      uni.setStorageSync(Report_Data_Time, end_time);
      start_time = end_time;
    }

    if (end_time - start_time > diff_time) {
      requestData(({ enable }) => {
        uni.setStorageSync(Report_Data_Time, end_time);
        uni.setStorageSync(Report_Status, enable);
      });
    }
  })
};

const requestData = (done) => {
  const appid = process.env.UNI_APP_ID;
  let formData = {
    usv: STAT_VERSION,
    conf: JSON.stringify({
      ak: appid,
    }),
  };
  uni.request({
    url: STAT_URL,
    method: 'GET',
    data: formData,
    success: (res) => {
      const { data } = res;
      if (data.ret === 0) {
        typeof done === 'function' &&
          done({
            enable: data.enable,
          });
      }
    },
    fail: (e) => {
      let report_status_code = 1;
      try {
        report_status_code = uni.getStorageSync(Report_Status);
      } catch (e) {
        report_status_code = 1;
      }
      if (report_status_code === '') {
        report_status_code = 1;
      }
      typeof done === 'function' &&
        done({
          enable: report_status_code,
        });
    },
  });
};

/**
 * 是否开启 debug 模式
 */
const is_debug = debug;

/**
 * 日志输出
 * @param {*} data
 */
M
mehaotian 已提交
453 454
const log = (data, type) => {

M
mehaotian 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  let msg_type = '';
  switch (data.lt) {
    case '1':
      msg_type = '应用启动';
      break
    case '3':
      msg_type = '应用进入后台';
      break

    case '11':
      msg_type = '页面切换';
      break
    case '21':
      msg_type = '事件触发';
      break
    case '31':
      msg_type = '应用错误';
      break
473 474 475
    case '101':
      msg_type = 'PUSH';
      break
M
mehaotian 已提交
476
  }
M
mehaotian 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

  // #ifdef APP
  // 在 app 中,日志转为 字符串
  if(typeof data === 'object') {
    data = JSON.stringify(data);
  }
  // #endif

  if (type) {
    console.log(`=== 统计队列数据上报 ===`);
    console.log(data);
    console.log(`=== 上报结束 ===`);
    return
  }

M
mehaotian 已提交
492 493 494 495 496
  if (msg_type) {
    console.log(`=== 统计数据采集:${msg_type} ===`);
    console.log(data);
    console.log(`=== 采集结束 ===`);
  }
M
mehaotian 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
};

/**
 * 获取上报时间间隔
 * @param {*} defaultTime 默认上报间隔时间 单位s
 */
const get_report_Interval = (defaultTime) => {
  let time = uniStatisticsConfig.reportInterval;
  // 如果上报时间配置为0 相当于立即上报
  if (Number(time) === 0) return 0
  time = time || defaultTime;
  let reg = /(^[1-9]\d*$)/;
  // 如果不是整数,则默认为上报间隔时间
  if (!reg.test(time)) return defaultTime
  return Number(time)
M
mehaotian 已提交
512 513
};

M
mehaotian 已提交
514
const appid = process.env.UNI_APP_ID; // 做应用隔离
M
mehaotian 已提交
515
const dbSet = (name, value) => {
M
mehaotian 已提交
516 517
  let data = uni.getStorageSync('$$STAT__DBDATA:'+appid) || {};

M
mehaotian 已提交
518 519 520 521
  if (!data) {
    data = {};
  }
  data[name] = value;
M
mehaotian 已提交
522
  uni.setStorageSync('$$STAT__DBDATA:'+appid, data);
M
mehaotian 已提交
523 524 525
};

const dbGet = (name) => {
M
mehaotian 已提交
526
  let data = uni.getStorageSync('$$STAT__DBDATA:'+appid) || {};
M
mehaotian 已提交
527
  if (!data[name]) {
M
mehaotian 已提交
528
    let dbdata = uni.getStorageSync('$$STAT__DBDATA:'+appid);
M
mehaotian 已提交
529 530 531 532 533 534 535 536 537
    if (!dbdata) {
      dbdata = {};
    }
    if (!dbdata[name]) {
      return undefined
    }
    data[name] = dbdata[name];
  }
  return data[name]
M
mehaotian 已提交
538 539 540
};

const dbRemove = (name) => {
M
mehaotian 已提交
541
  let data = uni.getStorageSync('$$STAT__DBDATA:'+appid) || {};
M
mehaotian 已提交
542 543
  if (data[name]) {
    delete data[name];
M
mehaotian 已提交
544
    uni.setStorageSync('$$STAT__DBDATA:'+appid, data);
M
mehaotian 已提交
545
  } else {
M
mehaotian 已提交
546
    data = uni.getStorageSync('$$STAT__DBDATA:'+appid);
M
mehaotian 已提交
547 548
    if (data[name]) {
      delete data[name];
M
mehaotian 已提交
549
      uni.setStorageSync('$$STAT__DBDATA:'+appid, data);
M
mehaotian 已提交
550 551
    }
  }
M
mehaotian 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
};

// 首次访问时间
const FIRST_VISIT_TIME_KEY = '__first__visit__time';
// 最后访问时间
const LAST_VISIT_TIME_KEY = '__last__visit__time';
/**
 * 获取当前时间
 */
const get_time = () => {
	return parseInt(new Date().getTime() / 1000)
};

/**
 * 获取首次访问时间
 */
const get_first_visit_time = () => {
	const timeStorge = dbGet(FIRST_VISIT_TIME_KEY);
	let time = 0;
	if (timeStorge) {
		time = timeStorge;
	} else {
		time = get_time();
575
		dbSet(FIRST_VISIT_TIME_KEY, time);
M
mehaotian 已提交
576 577 578 579 580
		// 首次访问需要 将最后访问时间置 0
		dbRemove(LAST_VISIT_TIME_KEY);
	}
	return time
};
581 582 583

/**
 * 最后访问时间
M
mehaotian 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
 */
const get_last_visit_time = () => {
	const timeStorge = dbGet(LAST_VISIT_TIME_KEY);
	let time = 0;
	if (timeStorge) {
		time = timeStorge;
	}
	dbSet(LAST_VISIT_TIME_KEY, get_time());
	return time
};

// 页面停留时间记录key
const PAGE_RESIDENCE_TIME = '__page__residence__time';
let First_Page_Residence_Time = 0;
let Last_Page_Residence_Time = 0;

/**
 * 设置页面停留时间
 */
const set_page_residence_time = () => {
	First_Page_Residence_Time = get_time();
	dbSet(PAGE_RESIDENCE_TIME, First_Page_Residence_Time);
	return First_Page_Residence_Time
};

/**
 * 获取页面停留时间
 */
const get_page_residence_time = () => {
	Last_Page_Residence_Time = get_time();
614
	First_Page_Residence_Time = dbGet(PAGE_RESIDENCE_TIME);
M
mehaotian 已提交
615 616
	return Last_Page_Residence_Time - First_Page_Residence_Time
};
617 618 619

/**
 * 获取总访问次数
M
mehaotian 已提交
620
 */
621
const TOTAL_VISIT_COUNT = '__total__visit__count';
M
mehaotian 已提交
622 623
const get_total_visit_count = () => {
	const timeStorge = dbGet(TOTAL_VISIT_COUNT);
624
	let count = 1;
M
mehaotian 已提交
625 626
	if (timeStorge) {
		count = timeStorge;
627
		count++;
M
mehaotian 已提交
628 629 630 631 632
	}
	dbSet(TOTAL_VISIT_COUNT, count);
	return count
};

633

M
mehaotian 已提交
634
const FIRST_TIME = '__first_time';
635
/**
M
mehaotian 已提交
636
 * 设置页面首次访问时间,用户获取页面/应用停留时常
M
mehaotian 已提交
637
 */
M
mehaotian 已提交
638 639 640 641
const set_first_time = () => {
	const time = new Date().getTime();
	const timeStorge = dbSet(FIRST_TIME,time);
	return timeStorge
M
mehaotian 已提交
642 643
};

644
/**
M
mehaotian 已提交
645
 * 获取最后一次时间 ,暂时用不到,直接获取当前时间即可
M
mehaotian 已提交
646
 */
M
mehaotian 已提交
647 648 649 650 651
// export const get_last_time = () => {
// 	let time = new Date().getTime()
// 	Set__Last__Time = time
// 	return time
// }
M
mehaotian 已提交
652

653 654
/**
 * 获取页面 \ 应用停留时间
M
mehaotian 已提交
655 656
 */
const get_residence_time = (type) => {
657
	let residenceTime = 0;
M
mehaotian 已提交
658 659 660 661
	const first_time = dbGet(FIRST_TIME);
	const last_time = get_time();
	if (first_time !== 0) {
		residenceTime = last_time - first_time;
M
mehaotian 已提交
662 663
	}

664
	residenceTime = parseInt(residenceTime / 1000);
M
mehaotian 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
	residenceTime = residenceTime < 1 ? 1 : residenceTime;
	if (type === 'app') {
		let overtime = residenceTime > APP_PVER_TIME ? true : false;
		return {
			residenceTime,
			overtime,
		}
	}
	if (type === 'page') {
		let overtime = residenceTime > PAGE_PVER_TIME ? true : false;
		return {
			residenceTime,
			overtime,
		}
	}
	return {
		residenceTime,
	}
};

M
mehaotian 已提交
685
const eport_Interval = get_report_Interval(OPERATING_TIME);
M
mehaotian 已提交
686 687
// 统计数据默认值
let statData = {
688 689 690
  uuid: get_uuid(), // 设备标识
  ak: stat_config.appid, // uni-app 应用 Appid
  p: sys.platform === 'android' ? 'a' : 'i', // 手机系统
M
mehaotian 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
  ut: get_platform_name(), // 平台类型
  mpn: get_pack_name(), // 原生平台包名、小程序 appid
  usv: STAT_VERSION, // 统计 sdk 版本
  v: get_version(), // 应用版本,仅app
  ch: get_channel(), // 渠道信息
  cn: '', // 国家
  pn: '', // 省份
  ct: '', // 城市
  t: get_time(), // 上报数据时的时间戳
  tt: '',
  brand: sys.brand || '', // 手机品牌
  md: sys.model, // 手机型号
  sv: sys.system.replace(/(Android|iOS)\s/, ''), // 手机系统版本
  mpsdk: sys.SDKVersion || '', // x程序 sdk version
  mpv: sys.version || '', // 小程序平台版本 ,如微信、支付宝
  lang: sys.language, // 语言
  pr: sys.pixelRatio, // pixelRatio 设备像素比
  ww: sys.windowWidth, // windowWidth 可使用窗口宽度
  wh: sys.windowHeight, // windowHeight 可使用窗口高度
  sw: sys.screenWidth, // screenWidth 屏幕宽度
  sh: sys.screenHeight, // screenHeight 屏幕高度
M
mehaotian 已提交
712 713
};
class Report {
M
mehaotian 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  constructor() {
    // 页面实例
    this.self = '';
    // 进入应用标识
    this.__licationShow = false;
    // 离开应用标识
    this.__licationHide = false;
    // 统计默认值
    this.statData = statData;
    // 标题默认值
    this._navigationBarTitle = {
      config: '',
      page: '',
      report: '',
      lt: '',
    };

    // 页面参数
    this._query = {};
    // 页面最后停留页面的 url
    // this._lastPageRoute = ''

    // 注册拦截器
    let registerInterceptor = typeof uni.addInterceptor === 'function';
    if (registerInterceptor) {
      this.addInterceptorInit();
      this.interceptLogin();
      this.interceptShare(true);
      this.interceptRequestPayment();
    }
  }
M
mehaotian 已提交
745

M
mehaotian 已提交
746 747 748 749 750 751 752 753
  addInterceptorInit() {
    let self = this;
    uni.addInterceptor('setNavigationBarTitle', {
      invoke(args) {
        self._navigationBarTitle.page = args.title;
      },
    });
  }
M
mehaotian 已提交
754

M
mehaotian 已提交
755 756 757 758 759 760 761 762
  interceptLogin() {
    let self = this;
    uni.addInterceptor('login', {
      complete() {
        self._login();
      },
    });
  }
M
mehaotian 已提交
763

M
mehaotian 已提交
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
  interceptShare(type) {
    let self = this;
    if (!type) {
      self._share();
      return
    }
    uni.addInterceptor('share', {
      success() {
        self._share();
      },
      fail() {
        self._share();
      },
    });
  }
M
mehaotian 已提交
779

M
mehaotian 已提交
780 781 782 783 784 785 786 787 788 789 790
  interceptRequestPayment() {
    let self = this;
    uni.addInterceptor('requestPayment', {
      success() {
        self._payment('pay_success');
      },
      fail() {
        self._payment('pay_fail');
      },
    });
  }
M
mehaotian 已提交
791

M
mehaotian 已提交
792 793 794 795 796 797 798 799
  _login() {
    this.sendEventRequest(
      {
        key: 'login',
      },
      0
    );
  }
M
mehaotian 已提交
800

M
mehaotian 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
  _share() {
    this.sendEventRequest(
      {
        key: 'share',
      },
      0
    );
  }
  _payment(key) {
    this.sendEventRequest(
      {
        key,
      },
      0
    );
  }
M
mehaotian 已提交
817

M
mehaotian 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830
  /**
   * 进入应用触发
   */
  applicationShow() {
    // 通过 __licationHide 判断保证是进入后台后在次进入应用,避免重复上报数据
    if (this.__licationHide) {
      const time = get_residence_time('app');
      // 需要判断进入后台是否超过时限 ,默认是 30min ,是的话需要执行进入应用的上报
      if (time.overtime) {
        let lastPageRoute = uni.getStorageSync('_STAT_LAST_PAGE_ROUTE');
        let options = {
          path: lastPageRoute,
          scene: this.statData.sc,
831
          cst: 2,
M
mehaotian 已提交
832 833 834 835 836 837 838
        };
        this.sendReportRequest(options);
      }
      // 状态重置
      this.__licationHide = false;
    }
  }
M
mehaotian 已提交
839

M
mehaotian 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
  /**
   * 离开应用触发
   * @param {Object} self
   * @param {Object} type
   */
  applicationHide(self, type) {
    if (!self) {
      // 表示应用切换到后台 ,此时需要从页面栈获取页面实例
      self = get_page_vm();
    }
    // 进入应用后台保存状态,方便进入前台后判断是否上报应用数据
    this.__licationHide = true;
    const time = get_residence_time();
    const route = get_page_route(self);
    uni.setStorageSync('_STAT_LAST_PAGE_ROUTE', route);
    this.sendHideRequest(
      {
        urlref: route,
        urlref_ts: time.residenceTime,
      },
      type
    );
M
mehaotian 已提交
862 863
    // 更新页面首次访问时间
    set_first_time();
M
mehaotian 已提交
864
  }
M
mehaotian 已提交
865

M
mehaotian 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878
  /**
   * 进入页面触发
   */
  pageShow(self) {
    // 清空值 ,初始化 ,避免污染后面的上报数据
    this._navigationBarTitle = {
      config: '',
      page: '',
      report: '',
      lt: '',
    };

    const route = get_page_route(self);
M
mehaotian 已提交
879
    const routepath = get_route$1(self);
M
mehaotian 已提交
880 881 882 883

    this._navigationBarTitle.config = get_page_name(routepath);
    // 表示应用触发 ,页面切换不触发之后的逻辑
    if (this.__licationShow) {
M
mehaotian 已提交
884 885
      // 更新页面首次访问时间
      set_first_time();
M
mehaotian 已提交
886 887 888 889 890 891 892 893 894 895 896 897
      // this._lastPageRoute = route
      uni.setStorageSync('_STAT_LAST_PAGE_ROUTE', route);
      this.__licationShow = false;
      return
    }

    const time = get_residence_time('page');
    // 停留时间
    if (time.overtime) {
      let options = {
        path: route,
        scene: this.statData.sc,
898
        cst: 3,
M
mehaotian 已提交
899 900 901
      };
      this.sendReportRequest(options);
    }
M
mehaotian 已提交
902 903
    // 更新页面首次访问时间
    set_first_time();
M
mehaotian 已提交
904
  }
M
mehaotian 已提交
905

M
mehaotian 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
  /**
   * 离开页面触发
   */
  pageHide(self) {
    if (!this.__licationHide) {
      const time = get_residence_time('page');
      let route = get_page_route(self);
      let lastPageRoute = uni.getStorageSync('_STAT_LAST_PAGE_ROUTE');
      if (!lastPageRoute) {
        lastPageRoute = route;
      }
      uni.setStorageSync('_STAT_LAST_PAGE_ROUTE', route);
      this.sendPageRequest({
        url: route,
        urlref: lastPageRoute,
        urlref_ts: time.residenceTime,
      });
      // this._lastPageRoute = route
      return
    }
  }
M
mehaotian 已提交
927

M
mehaotian 已提交
928 929 930
  /**
   * 发送请求,应用维度上报
   * @param {Object} options 页面信息
931
   * @param {Boolean} type 是否立即上报
M
mehaotian 已提交
932
   */
933
  sendReportRequest(options, type) {
M
mehaotian 已提交
934 935 936 937 938 939 940 941 942 943 944 945
    this._navigationBarTitle.lt = '1';
    this._navigationBarTitle.config = get_page_name(options.path);
    let is_opt = options.query && JSON.stringify(options.query) !== '{}';
    let query = is_opt ? '?' + JSON.stringify(options.query) : '';
    Object.assign(this.statData, {
      lt: '1',
      url: options.path + query || '',
      t: get_time(),
      sc: get_scene(options.scene),
      fvts: get_first_visit_time(),
      lvts: get_last_visit_time(),
      tvc: get_total_visit_count(),
946 947
      // create session type  上报类型 ,1 应用进入 2.后台30min进入 3.页面30min进入
      cst: options.cst || 1,
M
mehaotian 已提交
948 949
    });
    if (get_platform_name() === 'n') {
950
      this.getProperty(type);
M
mehaotian 已提交
951
    } else {
952
      this.getNetworkInfo(type);
M
mehaotian 已提交
953 954
    }
  }
M
mehaotian 已提交
955

M
mehaotian 已提交
956 957 958 959 960 961 962 963
  /**
   * 发送请求,页面维度上报
   * @param {Object} opt
   */
  sendPageRequest(opt) {
    let { url, urlref, urlref_ts } = opt;
    this._navigationBarTitle.lt = '11';
    let options = {
964 965 966
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      p: this.statData.p,
M
mehaotian 已提交
967 968 969 970 971 972 973 974 975 976 977 978
      lt: '11',
      ut: this.statData.ut,
      url,
      tt: this.statData.tt,
      urlref,
      urlref_ts,
      ch: this.statData.ch,
      usv: this.statData.usv,
      t: get_time(),
    };
    this.request(options);
  }
M
mehaotian 已提交
979

M
mehaotian 已提交
980 981 982 983 984 985 986 987
  /**
   * 进入后台上报数据
   * @param {Object} opt
   * @param {Object} type
   */
  sendHideRequest(opt, type) {
    let { urlref, urlref_ts } = opt;
    let options = {
988 989 990
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      p: this.statData.p,
M
mehaotian 已提交
991 992 993 994 995 996 997 998 999 1000
      lt: '3',
      ut: this.statData.ut,
      urlref,
      urlref_ts,
      ch: this.statData.ch,
      usv: this.statData.usv,
      t: get_time(),
    };
    this.request(options, type);
  }
M
mehaotian 已提交
1001

M
mehaotian 已提交
1002 1003 1004 1005
  /**
   * 自定义事件上报
   */
  sendEventRequest({ key = '', value = '' } = {}) {
M
mehaotian 已提交
1006 1007 1008 1009 1010 1011
    let routepath = '';

    try {
      routepath = get_route$1();
    } catch (error) {
      const launch_options = dbGet('__launch_options');
1012
      routepath = launch_options.path;
M
mehaotian 已提交
1013
    }
1014

M
mehaotian 已提交
1015 1016 1017
    this._navigationBarTitle.config = get_page_name(routepath);
    this._navigationBarTitle.lt = '21';
    let options = {
1018 1019 1020
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      p: this.statData.p,
M
mehaotian 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
      lt: '21',
      ut: this.statData.ut,
      url: routepath,
      ch: this.statData.ch,
      e_n: key,
      e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(),
      usv: this.statData.usv,
      t: get_time(),
    };
    this.request(options);
  }
M
mehaotian 已提交
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
  sendPushRequest(options, cid) {
    let time = get_time();

    const statData = {
      lt: '101',
      cid: cid,
      t: time,
      ut: this.statData.ut,
    };

    // debug 打印打点信息
    if (is_debug) {
      log(statData);
    }

    const stat_data = handle_data({
      101: [statData],
    });
    let optionsData = {
      usv: STAT_VERSION, //统计 SDK 版本号
      t: time, //发送请求时的时间戮
      requests: stat_data,
    };

    {
      if (statData.ut === 'h5') {
        this.imageRequest(optionsData);
        return
      }
    }

    // XXX 安卓需要延迟上报 ,否则会有未知错误,需要验证处理
    if (get_platform_name() === 'n' && this.statData.p === 'a') {
      setTimeout(() => {
        this.sendRequest(optionsData);
      }, 200);
      return
    }

    this.sendRequest(optionsData);
  }

M
mehaotian 已提交
1075 1076 1077
  /**
   * 获取wgt资源版本
   */
1078
  getProperty(type) {
M
mehaotian 已提交
1079 1080
    plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
      this.statData.v = wgtinfo.version || '';
1081
      this.getNetworkInfo(type);
M
mehaotian 已提交
1082 1083
    });
  }
M
mehaotian 已提交
1084

M
mehaotian 已提交
1085 1086 1087
  /**
   * 获取网络信息
   */
1088
  getNetworkInfo(type) {
M
mehaotian 已提交
1089 1090 1091
    uni.getNetworkType({
      success: (result) => {
        this.statData.net = result.networkType;
1092
        this.getLocation(type);
M
mehaotian 已提交
1093 1094 1095
      },
    });
  }
M
mehaotian 已提交
1096

M
mehaotian 已提交
1097 1098 1099
  /**
   * 获取位置信息
   */
1100
  getLocation(type) {
M
mehaotian 已提交
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    if (stat_config.getLocation) {
      uni.getLocation({
        type: 'wgs84',
        geocode: true,
        success: (result) => {
          if (result.address) {
            this.statData.cn = result.address.country;
            this.statData.pn = result.address.province;
            this.statData.ct = result.address.city;
          }

          this.statData.lat = result.latitude;
          this.statData.lng = result.longitude;
1114
          this.request(this.statData, type);
M
mehaotian 已提交
1115 1116 1117 1118 1119
        },
      });
    } else {
      this.statData.lat = 0;
      this.statData.lng = 0;
1120
      this.request(this.statData, type);
M
mehaotian 已提交
1121 1122
    }
  }
M
mehaotian 已提交
1123

M
mehaotian 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
  /**
   * 发送请求
   * @param {Object} data 上报数据
   * @param {Object} type 类型
   */
  request(data, type) {
    let time = get_time();
    const title = this._navigationBarTitle;
    Object.assign(data, {
      ttn: title.page,
      ttpj: title.config,
      ttc: title.report,
    });

    let uniStatData = dbGet('__UNI__STAT__DATA') || {};
    if (!uniStatData[data.lt]) {
      uniStatData[data.lt] = [];
    }
    // 加入队列
    uniStatData[data.lt].push(data);
    dbSet('__UNI__STAT__DATA', uniStatData);

    let page_residence_time = get_page_residence_time();
    // debug 打印打点信息
    if (is_debug) {
      log(data);
    }
    // 判断时候到达上报时间 ,默认 10 秒上报
M
mehaotian 已提交
1152
    if (page_residence_time < eport_Interval && !type) return
M
mehaotian 已提交
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

    // 时间超过,重新获取时间戳
    set_page_residence_time();
    const stat_data = handle_data(uniStatData);
    let optionsData = {
      usv: STAT_VERSION, //统计 SDK 版本号
      t: time, //发送请求时的时间戮
      requests: stat_data,
    };

    // 重置队列
    dbRemove('__UNI__STAT__DATA');

    {
      if (data.ut === 'h5') {
        this.imageRequest(optionsData);
        return
      }
    }

    // XXX 安卓需要延迟上报 ,否则会有未知错误,需要验证处理
    if (get_platform_name() === 'n' && this.statData.p === 'a') {
      setTimeout(() => {
        this.sendRequest(optionsData);
      }, 200);
      return
    }

    this.sendRequest(optionsData);
  }
M
mehaotian 已提交
1183

M
mehaotian 已提交
1184 1185 1186
  getIsReportData() {
    return is_report_data()
  }
M
mehaotian 已提交
1187

M
mehaotian 已提交
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
  /**
   * 数据上报
   * @param {Object} optionsData 需要上报的数据
   */
  sendRequest(optionsData) {

    {
      this.getIsReportData().then(() => {
        uni.request({
          url: STAT_URL,
          method: 'POST',
          data: optionsData,
          success: () => {
            if (is_debug) {
M
mehaotian 已提交
1202
              log(optionsData, true);
M
mehaotian 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
            }
          },
          fail: (e) => {
            if (++this._retry < 3) {
              if (is_debug) {
                console.warn('=== 统计上报错误,尝试重新上报!');
                console.error(e);
              }
              setTimeout(() => {
                this.sendRequest(optionsData);
              }, 1000);
            }
          },
        });
      });
    }
  }
M
mehaotian 已提交
1220

M
mehaotian 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229
  /**
   * h5 请求
   */
  imageRequest(data) {
    this.getIsReportData().then(() => {
      let image = new Image();
      let options = get_sgin(get_encodeURIComponent_options(data)).options;
      image.src = STAT_H5_URL + '?' + options;
      if (is_debug) {
M
mehaotian 已提交
1230
        log(data, true);
M
mehaotian 已提交
1231 1232 1233
      }
    });
  }
M
mehaotian 已提交
1234

M
mehaotian 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
  sendEvent(key, value) {
    // 校验 type 参数
    if (calibration(key, value)) return

    if (key === 'title') {
      this._navigationBarTitle.report = value;
      return
    }
    this.sendEventRequest(
      {
        key,
        value: typeof value === 'object' ? JSON.stringify(value) : value,
      },
      1
    );
  }
M
mehaotian 已提交
1251 1252
}

M
mehaotian 已提交
1253 1254 1255 1256 1257
class Stat extends Report {
  static getInstance() {
    if (!uni.__stat_instance) {
      uni.__stat_instance = new Stat();
    }
M
mehaotian 已提交
1258

M
mehaotian 已提交
1259 1260 1261 1262 1263
    return uni.__stat_instance
  }
  constructor() {
    super();
  }
M
mehaotian 已提交
1264

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
  /**
   * 获取推送id
   */
  pushEvent(options) {
    if (uni.getPushClientId) {
      uni.getPushClientId({
        success: (res) => {
          const cid = res.cid || false;
          //  只有获取到才会上传
          if (cid) {
            this.sendPushRequest(options,cid);
          }
        },
      });
    }
  }

M
mehaotian 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290
  /**
   * 进入应用
   * @param {Object} options 页面参数
   * @param {Object} self	当前页面实例
   */
  launch(options, self) {
    // 初始化页面停留时间  start
    set_page_residence_time();
    this.__licationShow = true;
M
mehaotian 已提交
1291
    dbSet('__launch_options', options);
1292
    // 应用初始上报参数为1
1293
    options.cst = 1;
M
mehaotian 已提交
1294 1295 1296 1297 1298 1299
    this.sendReportRequest(options, true);
  }
  load(options, self) {
    this.self = self;
    this._query = options;
  }
M
mehaotian 已提交
1300

M
mehaotian 已提交
1301 1302 1303
  appHide(self) {
    this.applicationHide(self, true);
  }
M
mehaotian 已提交
1304

M
mehaotian 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
  appShow(self) {
    this.applicationShow(self);
  }

  show(self) {
    this.self = self;
    if (get_page_types(self) === 'page') {
      this.pageShow(self);
    }

    // #ifdef VUE3
M
mehaotian 已提交
1316
    if (get_platform_name() === 'h5' || get_platform_name() === 'n') {
M
mehaotian 已提交
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
      if (get_page_types(self) === 'app') {
        this.appShow();
      }
    }
    // #endif

    // #ifndef VUE3
    if (get_page_types(self) === 'app') {
      this.appShow();
    }
    // #endif
  }

  hide(self) {
    this.self = self;
    if (get_page_types(self) === 'page') {
      this.pageHide(self);
    }

    // #ifdef VUE3
M
mehaotian 已提交
1337
    if (get_platform_name() === 'h5' || get_platform_name() === 'n') {
M
mehaotian 已提交
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
      if (get_page_types(self) === 'app') {
        this.appHide();
      }
    }
    // #endif

    // #ifndef VUE3
    if (get_page_types(self) === 'app') {
      this.appHide();
    }
    // #endif
  }

  error(em) {
    // 开发工具内不上报错误
M
mehaotian 已提交
1353 1354 1355 1356 1357 1358
    // if (this._platform === 'devtools') {
    //   if (process.env.NODE_ENV === 'development') {
    //     console.info('当前运行环境为开发者工具,不上报数据。')
    //     return
    //   }
    // }
M
mehaotian 已提交
1359 1360 1361 1362 1363 1364
    let emVal = '';
    if (!em.message) {
      emVal = JSON.stringify(em);
    } else {
      emVal = em.stack;
    }
M
mehaotian 已提交
1365 1366 1367

    let route = '';
    try {
1368 1369
      route = get_route();
    } catch (e) {
M
mehaotian 已提交
1370 1371 1372 1373
      // 未获取到页面路径
      route = '';
    }

M
mehaotian 已提交
1374
    let options = {
1375 1376 1377
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      p: this.statData.p,
M
mehaotian 已提交
1378
      lt: '31',
1379
      url: route,
M
mehaotian 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
      ut: this.statData.ut,
      ch: this.statData.ch,
      mpsdk: this.statData.mpsdk,
      mpv: this.statData.mpv,
      v: this.statData.v,
      em: emVal,
      usv: this.statData.usv,
      t: parseInt(new Date().getTime() / 1000),
    };
    this.request(options);
  }
}
M
mehaotian 已提交
1392 1393 1394 1395 1396 1397 1398 1399
var Stat$1 = Stat;

const stat = Stat$1.getInstance();

// 用于判断是隐藏页面还是卸载页面
let isHide = false;

const lifecycle = {
M
mehaotian 已提交
1400 1401 1402
  onLaunch(options) {
    // 进入应用上报数据
    stat.launch(options, this);
1403 1404
    // 上报push推送id
    stat.pushEvent(options);
M
mehaotian 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
  },
  onLoad(options) {
    stat.load(options, this);
    // 重写分享,获取分享上报事件
    if (this.$scope && this.$scope.onShareAppMessage) {
      let oldShareAppMessage = this.$scope.onShareAppMessage;
      this.$scope.onShareAppMessage = function (options) {
        stat.interceptShare(false);
        return oldShareAppMessage.call(this, options)
      };
    }
  },
  onShow() {
    isHide = false;
    stat.show(this);
  },
  onHide() {
    isHide = true;
    stat.hide(this);
  },
  onUnload() {
    if (isHide) {
      isHide = false;
      return
    }
    stat.hide(this);
  },
  onError(e) {
    stat.error(e);
  },
M
mehaotian 已提交
1435 1436
};

M
mehaotian 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
// 加载统计代码
function load_stat() {
  // #ifdef VUE3
  uni.onCreateVueApp((app) => {
    app.mixin(lifecycle);
    uni.report = function (type, options) {
      stat.sendEvent(type, options);
    };
  });

  if (get_platform_name() !== 'h5' && get_platform_name() !== 'n') {
    uni.onAppHide(() => {
      stat.appHide(get_page_vm());
    });
    uni.onAppShow(() => {
      stat.appShow(get_page_vm());
    });
  }
  // #endif

  // #ifndef VUE3
  // eslint-disable-next-line no-restricted-globals
  const Vue = require('vue')
  ;(Vue.default || Vue).mixin(lifecycle);
  uni.report = function (type, options) {
    stat.sendEvent(type, options);
  };
  // #endif
}
M
mehaotian 已提交
1466 1467

function main() {
M
mehaotian 已提交
1468 1469 1470
  if (is_debug) {
    {
      // #ifndef APP-NVUE
M
mehaotian 已提交
1471
      console.log('=== uni统计开启,version:1.0 ===');
M
mehaotian 已提交
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
      // #endif
    }
    load_stat();
  } else {
    if (process.env.NODE_ENV === 'development') {
      uni.report = function (type, options) {};
    } else {
      load_stat();
    }
  }
M
mehaotian 已提交
1482 1483 1484
}

main();