index.js 21.2 KB
Newer Older
1
import { version } from '../package.json';
fxy060608's avatar
fxy060608 已提交
2

M
mehaotian 已提交
3 4 5 6 7
const STAT_VERSION = version;
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;
const APP_PVER_TIME = 300;
fxy060608's avatar
fxy060608 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
const OPERATING_TIME = 10;

const UUID_KEY = '__DC_STAT_UUID';
const UUID_VALUE = '__DC_UUID_VALUE';

function getUuid() {
  let uuid = '';
  if (getPlatformName() === '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 getSgin = (statData) => {
  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]] + '&';
  }
  // const options = sginStr.substr(0, sginStr.length - 1)
  // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY;
  // const si = crypto.createHash('md5').update(sginStr).digest('hex');
  return {
    sign: '',
    options: sginStr.substr(0, sginStr.length - 1)
  };
};

const getSplicing = (data) => {
  let str = '';
  for (var i in data) {
    str += i + '=' + data[i] + '&';
  }
  return str.substr(0, str.length - 1)
};

const getTime = () => {
  return parseInt(new Date().getTime() / 1000);
};

const getPlatformName = () => {
  const platformList = {
    'app-plus': 'n',
    'h5': 'h5',
    'mp-weixin': 'wx',
    'mp-alipay': 'ali',
    'mp-baidu': 'bd',
    'mp-toutiao': 'tt',
    'mp-qq': 'qq'
  };
  return platformList[process.env.VUE_APP_PLATFORM];
};

const getPackName = () => {
  let packName = '';
  if (getPlatformName() === 'wx' || getPlatformName() === 'qq') {
    packName = uni.getAccountInfoSync().miniProgram.appId || '';
  }
  return packName
};

const getVersion = () => {
  return getPlatformName() === 'n' ? plus.runtime.version : '';
};

const getChannel = () => {
  const platformName = getPlatformName();
  let channel = '';
  if (platformName === 'n') {
    channel = plus.runtime.channel;
  }
  return channel;
};

const getScene = (options) => {
  const platformName = getPlatformName();
  let scene = '';
  if (options) {
    return options;
  }
  if (platformName === 'wx') {
    scene = uni.getLaunchOptionsSync().scene;
  }
  return scene;
};
const First__Visit__Time__KEY = 'First__Visit__Time';
const Last__Visit__Time__KEY = 'Last__Visit__Time';

const getFirstVisitTime = () => {
  const timeStorge = uni.getStorageSync(First__Visit__Time__KEY);
  let time = 0;
  if (timeStorge) {
    time = timeStorge;
  } else {
    time = getTime();
    uni.setStorageSync(First__Visit__Time__KEY, time);
    uni.removeStorageSync(Last__Visit__Time__KEY);
  }
  return time;
};

const getLastVisitTime = () => {
  const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY);
  let time = 0;
  if (timeStorge) {
    time = timeStorge;
  } else {
    time = '';
  }
  uni.setStorageSync(Last__Visit__Time__KEY, getTime());
  return time;
};


const PAGE_RESIDENCE_TIME = '__page__residence__time';
let First_Page_residence_time = 0;
let Last_Page_residence_time = 0;


const setPageResidenceTime = () => {
  First_Page_residence_time = getTime();
  if (getPlatformName() === 'n') {
    uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime());
  }
  return First_Page_residence_time
};

const getPageResidenceTime = () => {
  Last_Page_residence_time = getTime();
  if (getPlatformName() === 'n') {
    First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME);
  }
  return Last_Page_residence_time - First_Page_residence_time
};
const TOTAL__VISIT__COUNT = 'Total__Visit__Count';
const getTotalVisitCount = () => {
  const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT);
  let count = 1;
  if (timeStorge) {
    count = timeStorge;
    count++;
  }
  uni.setStorageSync(TOTAL__VISIT__COUNT, count);
  return count;
};

const GetEncodeURIComponentOptions = (statData) => {
  let data = {};
  for (let prop in statData) {
    data[prop] = encodeURIComponent(statData[prop]);
  }
  return data;
};

let Set__First__Time = 0;
let Set__Last__Time = 0;

const getFirstTime = () => {
  let time = new Date().getTime();
  Set__First__Time = time;
  Set__Last__Time = 0;
  return time;
};


const getLastTime = () => {
  let time = new Date().getTime();
  Set__Last__Time = time;
  return time;
};


const getResidenceTime = (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
  };

};

const getRoute = () => {
  var pages = getCurrentPages();
  var page = pages[pages.length - 1];
  let _self = page.$vm;

  if (getPlatformName() === 'bd') {
    return _self.$mp && _self.$mp.page.is;
  } else {
240
    return (_self.$scope && _self.$scope.route) || (_self.$mp && _self.$mp.page.route);
fxy060608's avatar
fxy060608 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254
  }
};

const getPageRoute = (self) => {
  var pages = getCurrentPages();
  var page = pages[pages.length - 1];
  let _self = page.$vm;
  let query = self._query;
  let str = query && JSON.stringify(query) !== '{}' ? '?' + JSON.stringify(query) : '';
  // clear
  self._query = '';
  if (getPlatformName() === 'bd') {
    return _self.$mp && _self.$mp.page.is + str;
  } else {
255
    return (_self.$scope && _self.$scope.route + str )|| (_self.$mp && _self.$mp.page.route + str);
fxy060608's avatar
fxy060608 已提交
256 257 258 259
  }
};

const getPageTypes = (self) => {
260 261 262
  if (self.mpType === 'page' || (self.$mp && self.$mp.mpType === 'page') || self.$options.mpType === 'page') {
    return true;
  }
fxy060608's avatar
fxy060608 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 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
  return false;
};

const calibration = (eventName, options) => {
  //  login 、 share 、pay_success 、pay_fail 、register 、title
  if(!eventName){
    console.error(`uni.report 缺少 [eventName] 参数`);
    return true
  }
  if (typeof eventName !== 'string') {
    console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`);
    return true
  }
  if (eventName.length > 255) {
    console.error(`uni.report [eventName] 参数长度不能大于 255`);
    return true
  }

  if (typeof options !== 'string' && typeof options !== 'object') {
    console.error(`uni.report [options] 参数类型错误,只能为 String 或 Object 类型`);
    return true
  }

  if (typeof options === 'string' && options.length > 255) {
    console.error(`uni.report [options] 参数长度不能大于 255`);
    return true
  }

  if (eventName === 'title' && typeof options !== 'string') {
    console.error('uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型');
    return true
  }
};

const PagesJson = require('uni-pages?{"type":"style"}').default;
const statConfig = require('uni-stat-config').default || require('uni-stat-config');

const resultOptions = uni.getSystemInfoSync();

class Util {
  constructor() {
    this.self = '';
    this._retry = 0;
    this._platform = '';
    this._query = {};
    this._navigationBarTitle = {
      config: '',
      page: '',
      report: '',
      lt: ''
    };
    this._operatingTime = 0;
    this._reportingRequestData = {
      '1': [],
      '11': []
    };
    this.__prevent_triggering = false;

    this.__licationHide = false;
    this.__licationShow = false;
    this._lastPageRoute = '';
    this.statData = {
      uuid: getUuid(),
      ut: getPlatformName(),
      mpn: getPackName(),
      ak: statConfig.appid,
      usv: STAT_VERSION,
      v: getVersion(),
      ch: getChannel(),
      cn: '',
      pn: '',
      ct: '',
      t: getTime(),
      tt: '',
      p: resultOptions.platform === 'android' ? 'a' : 'i',
      brand: resultOptions.brand || '',
      md: resultOptions.model,
      sv: resultOptions.system.replace(/(Android|iOS)\s/, ''),
      mpsdk: resultOptions.SDKVersion || '',
      mpv: resultOptions.version || '',
      lang: resultOptions.language,
      pr: resultOptions.pixelRatio,
      ww: resultOptions.windowWidth,
      wh: resultOptions.windowHeight,
      sw: resultOptions.screenWidth,
      sh: resultOptions.screenHeight
    };

  }

  _applicationShow() {
    if (this.__licationHide) {
      getLastTime();
      const time = getResidenceTime('app');
      if (time.overtime) {
        let options = {
          path: this._lastPageRoute,
          scene: this.statData.sc
        };
        this._sendReportRequest(options);
      }
      this.__licationHide = false;
    }
  }

  _applicationHide(self, type) {

    this.__licationHide = true;
    getLastTime();
    const time = getResidenceTime();
    getFirstTime();
374
    const route = getPageRoute(this);
fxy060608's avatar
fxy060608 已提交
375
    this._sendHideRequest({
376
      urlref: route,
fxy060608's avatar
fxy060608 已提交
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
      urlref_ts: time.residenceTime
    }, type);
  }

  _pageShow() {
    const route = getPageRoute(this);
    const routepath = getRoute();
    this._navigationBarTitle.config = PagesJson &&
      PagesJson.pages[routepath] &&
      PagesJson.pages[routepath].titleNView &&
      PagesJson.pages[routepath].titleNView.titleText ||
      PagesJson &&
      PagesJson.pages[routepath] &&
      PagesJson.pages[routepath].navigationBarTitleText || '';

    if (this.__licationShow) {
      getFirstTime();
      this.__licationShow = false;
      // console.log('这是 onLauch 之后执行的第一次 pageShow ,为下次记录时间做准备');
      this._lastPageRoute = route;
      return;
    }

    getLastTime();
    this._lastPageRoute = route;
    const time = getResidenceTime('page');
    if (time.overtime) {
      let options = {
        path: this._lastPageRoute,
        scene: this.statData.sc
      };
      this._sendReportRequest(options);
    }
    getFirstTime();
  }

  _pageHide() {
    if (!this.__licationHide) {
      getLastTime();
      const time = getResidenceTime('page');
      this._sendPageRequest({
        url: this._lastPageRoute,
        urlref: this._lastPageRoute,
        urlref_ts: time.residenceTime
      });
      this._navigationBarTitle = {
        config: '',
        page: '',
        report: '',
        lt: ''
      };
      return;
    }
  }

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

  _share() {
    this._sendEventRequest({
      key: 'share'
    }, 0);
  }
  _payment(key) {
    this._sendEventRequest({
      key
    }, 0);
  }
  _sendReportRequest(options) {
449

fxy060608's avatar
fxy060608 已提交
450 451 452
    this._navigationBarTitle.lt = '1';
    let query = options.query && JSON.stringify(options.query) !== '{}' ? '?' + JSON.stringify(options.query) : '';
    this.statData.lt = '1';
453
    this.statData.url = (options.path + query) || '';
fxy060608's avatar
fxy060608 已提交
454 455 456 457 458
    this.statData.t = getTime();
    this.statData.sc = getScene(options.scene);
    this.statData.fvts = getFirstVisitTime();
    this.statData.lvts = getLastVisitTime();
    this.statData.tvc = getTotalVisitCount();
459 460 461 462 463
    if (getPlatformName() === 'n') {
      this.getProperty();
    } else {
      this.getNetworkInfo();
    }
fxy060608's avatar
fxy060608 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
  }

  _sendPageRequest(opt) {
    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,
      t: getTime(),
      p: this.statData.p
    };
    this.request(options);
  }

  _sendHideRequest(opt, type) {
    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,
      t: getTime(),
      p: this.statData.p
    };
    this.request(options, type);
  }
  _sendEventRequest({
    key = '',
    value = ""
  } = {}) {
513
    const route = this._lastPageRoute;
fxy060608's avatar
fxy060608 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    let options = {
      ak: this.statData.ak,
      uuid: this.statData.uuid,
      lt: '21',
      ut: this.statData.ut,
      url: route,
      ch: this.statData.ch,
      e_n: key,
      e_v: typeof(value) === 'object' ? JSON.stringify(value) : value.toString(),
      usv: this.statData.usv,
      t: getTime(),
      p: this.statData.p
    };
    this.request(options);
  }

  getNetworkInfo() {
    uni.getNetworkType({
      success: (result) => {
        this.statData.net = result.networkType;
        this.getLocation();
      }
    });
  }

539 540 541 542 543 544 545
  getProperty() {
    plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
      this.statData.v = wgtinfo.version || '';
      this.getNetworkInfo();
    });
  }

fxy060608's avatar
fxy060608 已提交
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
  getLocation() {
    if (statConfig.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;
          this.request(this.statData);
        }
      });
    } else {
      this.statData.lat = 0;
      this.statData.lng = 0;
      this.request(this.statData);
    }
  }

  request(data, type) {
    let time = getTime();
    const title = this._navigationBarTitle;
    data.ttn = title.page;
    data.ttpj = title.config;
    data.ttc = title.report;

    let requestData = this._reportingRequestData;
578 579 580
    if (getPlatformName() === 'n') {
      requestData = uni.getStorageSync('__UNI__STAT__DATA') || {};
    }
fxy060608's avatar
fxy060608 已提交
581
    if (!requestData[data.lt]) {
582 583 584 585 586 587
      requestData[data.lt] = [];
    }
    requestData[data.lt].push(data);

    if (getPlatformName() === 'n') {
      uni.setStorageSync('__UNI__STAT__DATA', requestData);
fxy060608's avatar
fxy060608 已提交
588 589 590 591
    }
    if (getPageResidenceTime() < OPERATING_TIME && !type) {
      return
    }
592 593 594 595
    let uniStatData = this._reportingRequestData;
    if (getPlatformName() === 'n') {
      uniStatData = uni.getStorageSync('__UNI__STAT__DATA');
    }
fxy060608's avatar
fxy060608 已提交
596 597 598 599 600
    // 时间超过,重新获取时间戳
    setPageResidenceTime();
    let firstArr = [];
    let contentArr = [];
    let lastArr = [];
601 602 603

    for (let i in uniStatData) {
      const rd = uniStatData[i];
fxy060608's avatar
fxy060608 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
      rd.forEach((elm) => {
        const newData = getSplicing(elm);
        if (i === 0) {
          firstArr.push(newData);
        } else if (i === 3) {
          lastArr.push(newData);
        } else {
          contentArr.push(newData);
        }
      });
    }

    firstArr.push(...contentArr, ...lastArr);
    let optionsData = {
      usv: STAT_VERSION, //统计 SDK 版本号
      t: time, //发送请求时的时间戮
      requests: JSON.stringify(firstArr),
    };
622

fxy060608's avatar
fxy060608 已提交
623
    this._reportingRequestData = {};
624 625 626
    if (getPlatformName() === 'n') {
      uni.removeStorageSync('__UNI__STAT__DATA');
    }
fxy060608's avatar
fxy060608 已提交
627 628 629 630 631

    if (data.ut === 'h5') {
      this.imageRequest(optionsData);
      return
    }
632 633 634 635 636 637 638

    if (getPlatformName() === 'n' && this.statData.p === 'a') {
      setTimeout(() => {
        this._sendRequest(optionsData);
      }, 200);
      return
    }
639
    this._sendRequest(optionsData);
640 641 642 643 644 645 646 647 648 649
  }
  _sendRequest(optionsData) {
    uni.request({
      url: STAT_URL,
      method: 'POST',
      // header: {
      //   'content-type': 'application/json' // 默认值
      // },
      data: optionsData,
      success: () => {
650 651
        // if (process.env.NODE_ENV === 'development') {
        //   console.log('stat request success');
652 653 654 655 656 657 658 659 660 661 662 663 664
        // }
      },
      fail: (e) => {
        // if (process.env.NODE_ENV === 'development') {
        //   console.log('stat request fail', e);
        // }
        if (++this._retry < 3) {
          setTimeout(() => {
            this.request(data);
          }, 1000);
        }
      }
    });
fxy060608's avatar
fxy060608 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 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 745 746 747 748 749 750 751 752 753 754 755 756 757
  }
  /**
   * h5 请求
   */
  imageRequest(data) {
    let image = new Image();
    let options = getSgin(GetEncodeURIComponentOptions(data)).options;
    image.src = STAT_H5_URL + '?' + options;
  }

  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);
  }
}


class Stat extends Util {
  static getInstance() {
    if (!this.instance) {
      this.instance = new Stat();
    }
    return this.instance;
  }
  constructor() {
    super();
    this.instance = null;
    // 注册拦截器
    if (typeof uni.addInterceptor === 'function') {
      this.addInterceptorInit();
      this.interceptLogin();
      this.interceptShare(true);
      this.interceptRequestPayment();
    }
  }

  addInterceptorInit() {
    let self = this;
    uni.addInterceptor('setNavigationBarTitle', {
      invoke(args) {
        self._navigationBarTitle.page = args.title;
      }
    });
  }

  interceptLogin() {
    let self = this;
    uni.addInterceptor('login', {
      complete() {
        self._login();
      }
    });
  }

  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');
      }
    });
  }

  report(options, self) {
    this.self = self;
M
mehaotian 已提交
758 759 760
    // if (process.env.NODE_ENV === 'development') {
    //   console.log('report init');
    // }
fxy060608's avatar
fxy060608 已提交
761 762 763 764 765 766
    setPageResidenceTime();
    this.__licationShow = true;
    this._sendReportRequest(options, true);
  }

  load(options, self) {
767 768 769 770
    if (!self.$scope && !self.$mp) {
      const page = getCurrentPages();
      self.$scope = page[page.length - 1];
    }
fxy060608's avatar
fxy060608 已提交
771 772 773 774 775 776
    this.self = self;
    this._query = options;
  }

  show(self) {
    this.self = self;
777
    if (getPageTypes(self)) {
778 779
      this._pageShow(self);
    } else {
fxy060608's avatar
fxy060608 已提交
780 781 782 783 784
      this._applicationShow(self);
    }
  }

  ready(self) {
785 786 787 788
    // this.self = self;
    // if (getPageTypes(self)) {
    //   this._pageShow(self);
    // }
fxy060608's avatar
fxy060608 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
  }
  hide(self) {
    this.self = self;
    if (getPageTypes(self)) {
      this._pageHide(self);
    } else {
      this._applicationHide(self, true);
    }
  }
  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: getTime(),
      p: this.statData.p
    };
    this.request(options);
  }
}

const stat = Stat.getInstance();
let isHide = false;
const lifecycle = {
  onLaunch(options) {
    stat.report(options, this);
  },
  onReady() {
    stat.ready(this);
  },
  onLoad(options) {
839 840 841 842 843 844 845 846 847
    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)
      };
    }
fxy060608's avatar
fxy060608 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
  },
  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);
  }
};

function main() {
  const Vue = require('vue');
871 872 873 874 875 876 877 878
  if (process.env.NODE_ENV === 'development') {
    uni.report = function(type, options) {};
  }else{
    (Vue.default || Vue).mixin(lifecycle);
    uni.report = function(type, options) {
      stat.sendEvent(type, options);
    };
  }
fxy060608's avatar
fxy060608 已提交
879 880 881
}

main();