index.js 28.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import pagesTitle from 'uni-pages?{"type":"style"}';
import Vue from 'vue';

/**
 * 获取系统信息
 */
const sys = uni.getSystemInfoSync();

// 访问开始即启动小程序,访问结束结分为:进入后台超过5min、在前台无任何操作超过30min、在新的来源打开小程序;
const STAT_VERSION = '0.0.1';
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;

let pagesData = pagesTitle.pages;
let titleJsons = {};
for (let i in pagesData) {
  titleJsons[i] = pagesData[i].navigationBarTitleText || '';
}
石小磊 已提交
23

fxy060608's avatar
fxy060608 已提交
24 25 26 27 28
const UUID_KEY = '__DC_STAT_UUID';
const UUID_VALUE = '__DC_UUID_VALUE';

function getUuid() {
  let uuid = '';
29
  if (get_platform_name() === 'n') {
fxy060608's avatar
fxy060608 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    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);
    }
  }
52
  return uuid
fxy060608's avatar
fxy060608 已提交
53 54
}

55 56 57 58 59 60
const get_uuid = (statData) => {
  // 有可能不存在 deviceId(一般不存在就是出bug了),就自己生成一个
  return sys.deviceId || getUuid()
};

const get_sgin = (statData) => {
fxy060608's avatar
fxy060608 已提交
61 62 63 64 65 66 67 68
  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]] + '&';
  }
69

fxy060608's avatar
fxy060608 已提交
70 71
  return {
    sign: '',
72
    options: sginStr.substr(0, sginStr.length - 1),
fxy060608's avatar
fxy060608 已提交
73 74 75
  }
};

76 77 78 79 80 81
const get_encodeURIComponent_options = (statData) => {
  let data = {};
  for (let prop in statData) {
    data[prop] = encodeURIComponent(statData[prop]);
  }
  return data
fxy060608's avatar
fxy060608 已提交
82 83
};

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
/**
 * 获取当前平台
 * 移动端  : 'n',
 * h5	  : 'h5',
 * 微信	  : 'wx',
 * 阿里	  : 'ali',
 * 百度	  : 'bd',
 * 头条	  : 'tt',
 * qq	  : 'qq',
 * 快应用  : 'qn',
 * 快手	  : 'ks',
 * 飞书	  : 'lark',
 * 快应用  : 'qw',
 * 钉钉	  : 'dt'
 */
const get_platform_name = () => {
  // 苹果审核代码中禁止出现 alipay 字样 ,需要特殊处理一下
Q
qiang 已提交
101
  const aliArr = ['y', 'a', 'p', 'mp-ali'];
fxy060608's avatar
fxy060608 已提交
102
  const platformList = {
103
    'app': 'n',
fxy060608's avatar
fxy060608 已提交
104
    'app-plus': 'n',
105
    h5: 'h5',
fxy060608's avatar
fxy060608 已提交
106
    'mp-weixin': 'wx',
Q
qiang 已提交
107
    [aliArr.reverse().join('')]: 'ali',
fxy060608's avatar
fxy060608 已提交
108 109
    'mp-baidu': 'bd',
    'mp-toutiao': 'tt',
Q
qiang 已提交
110
    'mp-qq': 'qq',
Q
qiang 已提交
111
    'quickapp-native': 'qn',
112 113 114
    'mp-kuaishou': 'ks',
    'mp-lark': 'lark',
    'quickapp-webview': 'qw'
fxy060608's avatar
fxy060608 已提交
115
  };
116 117 118 119 120 121 122 123 124
  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]
fxy060608's avatar
fxy060608 已提交
125 126
};

127 128 129 130
/**
 * 获取小程序 appid
 */
const get_pack_name = () => {
131
  let packName = '';
132
  if (get_platform_name() === 'wx' || get_platform_name() === 'qq') {
133 134 135 136
    // 兼容微信小程序低版本基础库
    if (uni.canIUse('getAccountInfoSync')) {
      packName = uni.getAccountInfoSync().miniProgram.appId || '';
    }
fxy060608's avatar
fxy060608 已提交
137
  }
138
  if (get_platform_name() === 'n') ;
fxy060608's avatar
fxy060608 已提交
139 140 141
  return packName
};

142 143 144 145 146
/**
 * 应用版本
 */
const get_version = () => {
  return get_platform_name() === 'n' ? plus.runtime.version : ''
fxy060608's avatar
fxy060608 已提交
147 148
};

149 150 151 152 153
/**
 * 获取渠道
 */
const get_channel = () => {
  const platformName = get_platform_name();
fxy060608's avatar
fxy060608 已提交
154 155 156 157
  let channel = '';
  if (platformName === 'n') {
    channel = plus.runtime.channel;
  }
158
  return channel
fxy060608's avatar
fxy060608 已提交
159 160
};

161 162 163 164 165 166
/**
 * 获取小程序场景值
 * @param {Object} options 页面信息
 */
const get_scene = (options) => {
  const platformName = get_platform_name();
fxy060608's avatar
fxy060608 已提交
167 168
  let scene = '';
  if (options) {
169
    return options
fxy060608's avatar
fxy060608 已提交
170 171 172 173
  }
  if (platformName === 'wx') {
    scene = uni.getLaunchOptionsSync().scene;
  }
174
  return scene
fxy060608's avatar
fxy060608 已提交
175
};
176 177 178 179 180 181 182 183

/**
 * 获取拼接参数
 */
const get_splicing = (data) => {
  let str = '';
  for (var i in data) {
    str += i + '=' + data[i] + '&';
fxy060608's avatar
fxy060608 已提交
184
  }
185
  return str.substr(0, str.length - 1)
fxy060608's avatar
fxy060608 已提交
186 187
};

188 189 190 191 192 193 194 195 196
/**
 * 获取页面url,不包含参数
 */
const get_route = (pageVm) => {
  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 || ''
fxy060608's avatar
fxy060608 已提交
197
  } else {
198
    return _self.route || (_self.$scope && _self.$scope.route) || (_self.$mp && _self.$mp.page.route)
fxy060608's avatar
fxy060608 已提交
199 200 201
  }
};

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

  let page = pageVm.$page || (pageVm.$scope && pageVm.$scope.$page);
  let lastPageRoute = uni.getStorageSync('_STAT_LAST_PAGE_ROUTE');
  if (!page) return lastPageRoute || ''
  return page.fullPath === '/' ? page.route : page.fullPath
fxy060608's avatar
fxy060608 已提交
213 214
};

215 216 217 218 219 220 221 222
/**
 * 获取页面实例
 */
const get_page_vm = () => {
  let pages = getCurrentPages();
  let $page = pages[pages.length - 1];
  if (!$page) return null
  return $page.$vm
fxy060608's avatar
fxy060608 已提交
223 224
};

225 226 227 228 229 230 231 232
/**
 * 获取页面类型
 */
const get_page_types = (self) => {
  // XXX 百度有问题 ,获取的都是 componet ,等待修复
  if (self.mpType === 'page' || self.$mpType === 'page' || (self.$mp && self.$mp.mpType === 'page') || self
    .$options.mpType === 'page') {
    return 'page';
fxy060608's avatar
fxy060608 已提交
233
  }
234 235 236
  if (self.mpType === 'app' || self.$mpType === 'app' || (self.$mp && self.$mp.mpType === 'app') || self.$options
    .mpType === 'app') {
    return 'app'
fxy060608's avatar
fxy060608 已提交
237
  }
238
  return null;
fxy060608's avatar
fxy060608 已提交
239 240
};

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
/**
 * 处理上报参数
 * @param {Object}  需要处理的数据
 */
const handle_data = (statData) => {
  let firstArr = [];
  let contentArr = [];
  let lastArr = [];
  for (let i in statData) {
    const rd = statData[i];
    rd.forEach((elm) => {
      const newData = get_splicing(elm);
      if (i === 0) {
        firstArr.push(newData);
      } else if (i === 3) {
        lastArr.push(newData);
      } else {
        contentArr.push(newData);
      }
    });
fxy060608's avatar
fxy060608 已提交
261 262
  }

263 264 265
  firstArr.push(...contentArr, ...lastArr);
  // 参数需要处理成字符串,方便上传
  return JSON.stringify(firstArr)
fxy060608's avatar
fxy060608 已提交
266 267 268
};


269 270 271
/**
 * 自定义事件参数校验
 */
fxy060608's avatar
fxy060608 已提交
272
const calibration = (eventName, options) => {
273 274
  //  login 、 share 、pay_success 、pay_fail 、register 、title
  if (!eventName) {
275
    console.error(`uni.report Missing [eventName] parameter`);
276
    return true
fxy060608's avatar
fxy060608 已提交
277 278
  }
  if (typeof eventName !== 'string') {
279
    console.error(`uni.report [eventName] Parameter type error, it can only be of type String`);
fxy060608's avatar
fxy060608 已提交
280 281 282
    return true
  }
  if (eventName.length > 255) {
283
    console.error(`uni.report [eventName] Parameter length cannot be greater than 255`);
fxy060608's avatar
fxy060608 已提交
284 285 286 287
    return true
  }

  if (typeof options !== 'string' && typeof options !== 'object') {
288
    console.error('uni.report [options] Parameter type error, Only supports String or Object type');
fxy060608's avatar
fxy060608 已提交
289 290 291 292
    return true
  }

  if (typeof options === 'string' && options.length > 255) {
293
    console.error(`uni.report [options] Parameter length cannot be greater than 255`);
fxy060608's avatar
fxy060608 已提交
294 295 296 297
    return true
  }

  if (eventName === 'title' && typeof options !== 'string') {
298 299 300
    console.error(
      `uni.report [eventName] When the parameter is title, the [options] parameter can only be of type String`
    );
fxy060608's avatar
fxy060608 已提交
301
    return true
302 303 304
  }
};

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 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
const get_page_name = (routepath) => {
  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,
        });
    },
  });
};

const dbSet = (name, value) => {
  let data = uni.getStorageSync('$$STAT__DBDATA') || {};
	if (!data) {
		data = {};
	}
	data[name] = value;
	uni.setStorageSync('$$STAT__DBDATA', data);
};
402

403 404 405 406 407 408 409 410 411 412
const dbGet = (name) => {
  let data = uni.getStorageSync('$$STAT__DBDATA') || {};
  if (!data) {
  	data = {};
  }
	if (!data[name]) {
		return undefined
	}
	return data[name]
};
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
const dbRemove = (name) => {
  let data = uni.getStorageSync('$$STAT__DBDATA') || {};
	if (data[name]) {
		delete data[name];
		uni.setStorageSync('$$STAT__DBDATA', data);
	} else {
		data = uni.getStorageSync('$$STAT__DBDATA');
		if (data[name]) {
			delete data[name];
			uni.setStorageSync('$$STAT__DBDATA', data);
		}
	}
};

// 首次访问时间
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)
};
438

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
/**
 * 获取首次访问时间
 */
const get_first_visit_time = () => {
	const timeStorge = dbGet(FIRST_VISIT_TIME_KEY);
	let time = 0;
	if (timeStorge) {
		time = timeStorge;
	} else {
		time = get_time();
		dbSet(FIRST_VISIT_TIME_KEY, time);
		// 首次访问需要 将最后访问时间置 0
		dbRemove(LAST_VISIT_TIME_KEY);
	}
	return time
};

/**
 * 最后访问时间
 */
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
};
468

469 470
// 页面停留时间记录key
const PAGE_RESIDENCE_TIME = '__page__residence__time';
471

472 473 474 475 476 477 478
/**
 * 设置页面停留时间
 */
const set_page_residence_time = () => {
	let First_Page_Residence_Time = get_time();
	dbSet(PAGE_RESIDENCE_TIME, First_Page_Residence_Time);
	return First_Page_Residence_Time
479 480
};

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
/**
 * 获取页面停留时间
 */
const get_page_residence_time = () => {
	let Last_Page_Residence_Time = get_time();
	let First_Page_Residence_Time = dbGet(PAGE_RESIDENCE_TIME);
	return Last_Page_Residence_Time - First_Page_Residence_Time
};

/**
 * 获取总访问次数
 */
const TOTAL_VISIT_COUNT = '__total__visit__count';
const get_total_visit_count = () => {
	const timeStorge = dbGet(TOTAL_VISIT_COUNT);
	let count = 1;
	if (timeStorge) {
		count = timeStorge;
		count++;
	}
	dbSet(TOTAL_VISIT_COUNT, count);
	return count
石小磊 已提交
503 504
};

505 506 507 508 509 510 511 512 513 514 515 516
let Set__First__Time = 0;
let Set__Last__Time = 0;

/**
 * 获取第一次时间
 */
const get_first_time = () => {
	let time = new Date().getTime();
	Set__First__Time = time;
	Set__Last__Time = 0;
	return time
};
fxy060608's avatar
fxy060608 已提交
517

518 519 520 521 522 523 524 525
/**
 * 获取最后一次时间
 */
const get_last_time = () => {
	let time = new Date().getTime();
	Set__Last__Time = time;
	return time
};
fxy060608's avatar
fxy060608 已提交
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
/**
 * 获取页面 \ 应用停留时间
 */
const get_residence_time = (type) => {
	let residenceTime = 0;
	if (Set__First__Time !== 0) {
		residenceTime = Set__Last__Time - Set__First__Time;
	}

	residenceTime = parseInt(residenceTime / 1000);
	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,
	}
};

let statConfig = require('uni-stat-config').default || require('uni-stat-config');

// 统计数据默认值
let statData = {
  uuid: get_uuid(), // 设备标识
  ut: get_platform_name(), // 平台类型
  mpn: get_pack_name(), // 原生平台包名、小程序 appid
  ak: statConfig.appid, // uni-app 应用 Appid
  usv: STAT_VERSION, // 统计 sdk 版本
  v: get_version(), // 应用版本,仅app
  ch: get_channel(), // 渠道信息
  cn: '', // 国家
  pn: '', // 省份
  ct: '', // 城市
  t: get_time(), // 上报数据时的时间戳
  tt: '',
  p: sys.platform === 'android' ? 'a' : 'i', // 手机系统
  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 屏幕高度
};
class Report {
fxy060608's avatar
fxy060608 已提交
587
  constructor() {
588
    // 页面实例
fxy060608's avatar
fxy060608 已提交
589
    this.self = '';
590 591 592 593 594 595 596
    // 进入应用标识
    this.__licationShow = false;
    // 离开应用标识
    this.__licationHide = false;
    // 统计默认值
    this.statData = statData;
    // 标题默认值
fxy060608's avatar
fxy060608 已提交
597 598 599 600
    this._navigationBarTitle = {
      config: '',
      page: '',
      report: '',
601
      lt: '',
fxy060608's avatar
fxy060608 已提交
602 603
    };

604 605 606 607
    // 页面参数
    this._query = {};
    // 页面最后停留页面的 url
    // this._lastPageRoute = ''
fxy060608's avatar
fxy060608 已提交
608

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    // 注册拦截器
    let registerInterceptor = typeof uni.addInterceptor === 'function';
    if (registerInterceptor) {
      this.addInterceptorInit();
      this.interceptLogin();
      this.interceptShare(true);
      this.interceptRequestPayment();
    }
  }

  addInterceptorInit() {
    let self = this;
    uni.addInterceptor('setNavigationBarTitle', {
      invoke(args) {
        self._navigationBarTitle.page = args.title;
      },
    });
fxy060608's avatar
fxy060608 已提交
626
  }
627

628 629 630 631 632 633 634
  interceptLogin() {
    let self = this;
    uni.addInterceptor('login', {
      complete() {
        self._login();
      },
    });
635 636
  }

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
  interceptShare(type) {
    let self = this;
    if (!type) {
      self._share();
      return
    }
    uni.addInterceptor('share', {
      success() {
        self._share();
      },
      fail() {
        self._share();
      },
    });
  }

  interceptRequestPayment() {
    let self = this;
    uni.addInterceptor('requestPayment', {
      success() {
        self._payment('pay_success');
      },
      fail() {
        self._payment('pay_fail');
      },
    });
  }

  _login() {
    this.sendEventRequest({
        key: 'login',
      },
      0
    );
  }

  _share() {
    this.sendEventRequest({
      key: 'share',
    }, 0);
  }
  _payment(key) {
    this.sendEventRequest({
      key,
    }, 0);
  }

  /**
   * 进入应用触发
   */
  applicationShow() {
    // 通过 __licationHide 判断保证是进入后台后在次进入应用,避免重复上报数据
fxy060608's avatar
fxy060608 已提交
689
    if (this.__licationHide) {
690 691 692
      get_last_time();
      const time = get_residence_time('app');
      // 需要判断进入后台是否超过时限 ,默认是 30min ,是的话需要执行进入应用的上报
fxy060608's avatar
fxy060608 已提交
693
      if (time.overtime) {
694
        let lastPageRoute = uni.getStorageSync('_STAT_LAST_PAGE_ROUTE');
fxy060608's avatar
fxy060608 已提交
695
        let options = {
696 697
          path: lastPageRoute,
          scene: this.statData.sc,
fxy060608's avatar
fxy060608 已提交
698
        };
699
        this.sendReportRequest(options);
fxy060608's avatar
fxy060608 已提交
700
      }
701
      // 状态重置
fxy060608's avatar
fxy060608 已提交
702 703 704 705
      this.__licationHide = false;
    }
  }

706 707 708 709 710 711 712
  /**
   * 离开应用触发
   * @param {Object} self
   * @param {Object} type
   */
  applicationHide(self, type) {
    // 进入应用后台保存状态,方便进入前台后判断是否上报应用数据
fxy060608's avatar
fxy060608 已提交
713
    this.__licationHide = true;
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
    get_last_time();
    const time = get_residence_time();
    const route = get_page_route(self);
    // this._lastPageRoute = route
    uni.setStorageSync('_STAT_LAST_PAGE_ROUTE', route);
    this.sendHideRequest({
        urlref: route,
        urlref_ts: time.residenceTime,
      },
      type
    );
    // 重置时间
    get_first_time();
  }

  /**
   * 进入页面触发
   */
  pageShow(self) {
    // 清空值 ,初始化 ,避免污染后面的上报数据
    this._navigationBarTitle = {
      config: '',
      page: '',
      report: '',
      lt: '',
    };
fxy060608's avatar
fxy060608 已提交
740

741 742 743 744 745
    const route = get_page_route(self);
    const routepath = get_route(self);

    this._navigationBarTitle.config = get_page_name(routepath);
    // 表示应用触发 ,页面切换不触发之后的逻辑
fxy060608's avatar
fxy060608 已提交
746
    if (this.__licationShow) {
747 748 749
      get_first_time();
      // this._lastPageRoute = route
      uni.setStorageSync('_STAT_LAST_PAGE_ROUTE', route);
fxy060608's avatar
fxy060608 已提交
750
      this.__licationShow = false;
751
      return
fxy060608's avatar
fxy060608 已提交
752 753
    }

754 755 756 757
    get_last_time();

    const time = get_residence_time('page');
    // 停留时间
fxy060608's avatar
fxy060608 已提交
758 759
    if (time.overtime) {
      let options = {
760 761
        path: route,
        scene: this.statData.sc,
fxy060608's avatar
fxy060608 已提交
762
      };
763
      this.sendReportRequest(options);
fxy060608's avatar
fxy060608 已提交
764
    }
765 766
    // 重置时间
    get_first_time();
fxy060608's avatar
fxy060608 已提交
767 768
  }

769 770 771 772
  /**
   * 离开页面触发
   */
  pageHide(self) {
fxy060608's avatar
fxy060608 已提交
773
    if (!this.__licationHide) {
774 775 776 777 778 779 780 781 782 783 784 785
      get_last_time();
      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,
fxy060608's avatar
fxy060608 已提交
786
      });
787 788
      // this._lastPageRoute = route
      return
fxy060608's avatar
fxy060608 已提交
789 790 791
    }
  }

792

793 794 795 796 797
  /**
   * 发送请求,应用维度上报
   * @param {Object} options 页面信息
   */
  sendReportRequest(options) {
fxy060608's avatar
fxy060608 已提交
798
    this._navigationBarTitle.lt = '1';
799 800 801 802 803 804 805 806 807 808 809 810 811
    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()
    });
    if (get_platform_name() === 'n') {
812 813 814 815
      this.getProperty();
    } else {
      this.getNetworkInfo();
    }
fxy060608's avatar
fxy060608 已提交
816 817
  }

818 819 820 821 822
  /**
   * 发送请求,页面维度上报
   * @param {Object} opt
   */
  sendPageRequest(opt) {
fxy060608's avatar
fxy060608 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    let {
      url,
      urlref,
      urlref_ts
    } = opt;
    this._navigationBarTitle.lt = '11';
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '11',
      ut: this.statData.ut,
      url,
      tt: this.statData.tt,
      urlref,
      urlref_ts,
      ch: this.statData.ch,
      usv: this.statData.usv,
840 841
      t: get_time(),
      p: this.statData.p,
fxy060608's avatar
fxy060608 已提交
842 843 844 845
    };
    this.request(options);
  }

846 847 848 849 850 851
  /**
   * 进入后台上报数据
   * @param {Object} opt
   * @param {Object} type
   */
  sendHideRequest(opt, type) {
fxy060608's avatar
fxy060608 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864
    let {
      urlref,
      urlref_ts
    } = opt;
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '3',
      ut: this.statData.ut,
      urlref,
      urlref_ts,
      ch: this.statData.ch,
      usv: this.statData.usv,
865 866
      t: get_time(),
      p: this.statData.p,
fxy060608's avatar
fxy060608 已提交
867 868 869
    };
    this.request(options, type);
  }
870 871 872 873 874

  /**
   * 自定义事件上报
   */
  sendEventRequest({
fxy060608's avatar
fxy060608 已提交
875
    key = '',
876
    value = ''
fxy060608's avatar
fxy060608 已提交
877
  } = {}) {
878 879 880 881
    // const route = this._lastPageRoute
    const routepath = get_route();
    this._navigationBarTitle.config = get_page_name(routepath);
    this._navigationBarTitle.lt = '21';
fxy060608's avatar
fxy060608 已提交
882 883 884 885 886
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '21',
      ut: this.statData.ut,
887
      url: routepath,
fxy060608's avatar
fxy060608 已提交
888 889
      ch: this.statData.ch,
      e_n: key,
890
      e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(),
fxy060608's avatar
fxy060608 已提交
891
      usv: this.statData.usv,
892 893
      t: get_time(),
      p: this.statData.p,
fxy060608's avatar
fxy060608 已提交
894 895 896 897
    };
    this.request(options);
  }

898 899 900 901 902 903 904 905 906 907 908 909 910
  /**
   * 获取wgt资源版本
   */
  getProperty() {
    plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
      this.statData.v = wgtinfo.version || '';
      this.getNetworkInfo();
    });
  }

  /**
   * 获取网络信息
   */
fxy060608's avatar
fxy060608 已提交
911 912 913 914 915
  getNetworkInfo() {
    uni.getNetworkType({
      success: (result) => {
        this.statData.net = result.networkType;
        this.getLocation();
916
      },
917 918 919
    });
  }

920 921 922
  /**
   * 获取位置信息
   */
fxy060608's avatar
fxy060608 已提交
923
  getLocation() {
924
    if (statConfig.getLocation) {
fxy060608's avatar
fxy060608 已提交
925 926 927 928 929 930 931 932 933 934 935 936 937
      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;
          this.request(this.statData);
938
        },
fxy060608's avatar
fxy060608 已提交
939 940 941 942 943 944 945 946
      });
    } else {
      this.statData.lat = 0;
      this.statData.lng = 0;
      this.request(this.statData);
    }
  }

947 948 949 950 951
  /**
   * 发送请求
   * @param {Object} data 上报数据
   * @param {Object} type 类型
   */
fxy060608's avatar
fxy060608 已提交
952
  request(data, type) {
953
    let time = get_time();
fxy060608's avatar
fxy060608 已提交
954
    const title = this._navigationBarTitle;
955 956 957 958 959
    Object.assign(data, {
      ttn: title.page,
      ttpj: title.config,
      ttc: title.report
    });
fxy060608's avatar
fxy060608 已提交
960

961 962 963
    let uniStatData = dbGet('__UNI__STAT__DATA') || {};
    if (!uniStatData[data.lt]) {
      uniStatData[data.lt] = [];
964
    }
965 966 967
    // 加入队列
    uniStatData[data.lt].push(data);
    dbSet('__UNI__STAT__DATA', uniStatData);
968

969 970 971
    let page_residence_time = get_page_residence_time();
    // 判断时候到达上报时间 ,默认 10 秒上报
    if (page_residence_time < OPERATING_TIME && !type) return
fxy060608's avatar
fxy060608 已提交
972

973 974 975
    // 时间超过,重新获取时间戳
    set_page_residence_time();
    const stat_data = handle_data(uniStatData);
fxy060608's avatar
fxy060608 已提交
976 977 978
    let optionsData = {
      usv: STAT_VERSION, //统计 SDK 版本号
      t: time, //发送请求时的时间戮
979
      requests: stat_data,
fxy060608's avatar
fxy060608 已提交
980
    };
981

982 983 984 985 986 987
    // 重置队列
    dbRemove('__UNI__STAT__DATA');

    if (data.ut === 'h5') {
      this.imageRequest(optionsData);
      return
988
    }
fxy060608's avatar
fxy060608 已提交
989

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

    this.sendRequest(optionsData);
fxy060608's avatar
fxy060608 已提交
999
  }
1000 1001 1002 1003
  getIsReportData(){
  	return is_report_data()
  }

fxy060608's avatar
fxy060608 已提交
1004
  /**
1005 1006
   * 数据上报
   * @param {Object} optionsData 需要上报的数据
fxy060608's avatar
fxy060608 已提交
1007
   */
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  sendRequest(optionsData) {
    this.getIsReportData().then(() => {
    	uni.request({
    		url: STAT_URL,
    		method: 'POST',
    		// header: {
    		//   'content-type': 'application/json' // 默认值
    		// },
    		data: optionsData,
    		success: () => {},
    		fail: (e) => {
    			if (++this._retry < 3) {
    				setTimeout(() => {
    					this.sendRequest(optionsData);
    				}, 1000);
    			}
    		},
    	});
1026
    });
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
  }

  /**
   * 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;
    });
fxy060608's avatar
fxy060608 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  }

  sendEvent(key, value) {
    // 校验 type 参数
    if (calibration(key, value)) return

    if (key === 'title') {
      this._navigationBarTitle.report = value;
      return
    }
1048 1049 1050
    this.sendEventRequest({
        key,
        value: typeof value === 'object' ? JSON.stringify(value) : value,
fxy060608's avatar
fxy060608 已提交
1051
      },
1052 1053
      1
    );
fxy060608's avatar
fxy060608 已提交
1054
  }
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
}

let vue =  (Vue.default || Vue);

class Stat extends Report {
	static getInstance() {
		if (!vue.instance) {
			vue.instance = new Stat();
		}
		return vue.instance
	}
	constructor() {
		super();
		this.instance = null;
	}

	/**
	 * 进入应用
	 * @param {Object} options 页面参数
	 * @param {Object} self	当前页面实例
	 */
	launch(options, self) {
		// 初始化页面停留时间  start
		let residence_time =  set_page_residence_time();
		this.__licationShow = true;
		this.sendReportRequest(options, true);
	}
	load(options, self) {
		this.self = self;
		this._query = options;
	}

	appHide(self){
		this.applicationHide(self, true);
	}

	appShow(self){
		this.applicationShow(self);
	}

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

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

	error(em) {
		// 开发工具内不上报错误
		if (this._platform === 'devtools') {
			if (process.env.NODE_ENV === 'development') {
				console.info('当前运行环境为开发者工具,不上报数据。');
				return;
			}
		}
		let emVal = '';
		if (!em.message) {
			emVal = JSON.stringify(em);
		} else {
			emVal = em.stack;
		}
		let options = {
			ak: this.statData.ak,
			uuid: this.statData.uuid,
			lt: '31',
			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),
			p: this.statData.p,
		};
		this.request(options);
	}
}

fxy060608's avatar
fxy060608 已提交
1147
const stat = Stat.getInstance();
1148 1149

// 用于判断是隐藏页面还是卸载页面
fxy060608's avatar
fxy060608 已提交
1150
let isHide = false;
1151

fxy060608's avatar
fxy060608 已提交
1152
const lifecycle = {
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 1183 1184 1185
	onLaunch(options) {
		// 进入应用上报数据
		stat.launch(options, this);
	},
	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);
	}
fxy060608's avatar
fxy060608 已提交
1186 1187
};

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

function main() {
	if (process.env.NODE_ENV === 'development') {
	  uni.report = function(type, options) {};
	} else {
    console.log('统计已开启');
	  const Vue = require('vue'); 
	  (Vue.default || Vue).mixin(lifecycle);
	  uni.report = function(type, options) {
	    stat.sendEvent(type, options);
	  };
	}
fxy060608's avatar
fxy060608 已提交
1200 1201
}

1202
main();