app.js 9.95 KB
import wx from './utils/wx';
import udid from './common/udid';
import event from './common/event';
import {
  verify
} from './common/api';
import Promise from './vendors/es6-promise';
import {
  wechatAuthLogin,
  verifySessionKey
} from './common/login';
import {
  MD5
} from './vendors/crypto';
import config from './common/config';
import Yas from './common/yas';
import './router/index'; // 新增的router
import {
  stringify
} from './vendors/query-stringify';

import commonModel from './models/common';

let yas;

// app.js
App({
  globalData: {
    userInfo: {},
    unionID: '',
    sessionKey: '',
    thirdSession: '',
    udid: '',
    unionType: '',
    systemInfo: {}
  },
  reportData: {
    awakeReported: false
  },
  onLaunch: function(options) {
    this.globalData.udid = udid.get(); // 生成 UDID

    verify.gen(); // 此处返回是是 Promise,需要调用接口的业务,最好在 then 里边执行

    let sysInfo = wx.getSystemInfoSync();

    if (!sysInfo.screenHeight) {
      sysInfo.screenHeight = sysInfo.windowHeight;
    }
    if (!sysInfo.screenWidth) {
      sysInfo.screenWidth = sysInfo.windowWidth;
    }
    this.globalData.systemInfo = sysInfo;

    if (options && options.query && options.query.union_type) {
      this.updateUnionType(options.query.union_type);
    }

    let timestamp = new Date().getTime() + '';

    this.globalData.sid = MD5(timestamp);
    yas = new Yas(this);
    yas.report('YB_LAUNCH_APP');
  },
  onShow: function(options) {
    udid.get(); // 生成 UDID
    verify.gen(); // 此处返回是是 Promise,需要调用接口的业务,最好在 then 里边执行

    // wx.getLocation({}); // 获取位置信息
    wx.checkSession().then(() => { // 微信登录未过期
      this.getWechatThirdSession();
      this.getUserInfo();
      this.getUnionID();
      this.doLogin();
      this.setUserUnionType(this.getUid());
    }).catch(() => { // 微信登录过期
      wx.setStorage({
        key: 'thirdSession',
        data: ''
      });
      wx.setStorage({
        key: 'userInfo',
        data: {}
      });

      wx.setStorage({
        key: 'unionID',
        data: ''
      });

      wx.setStorage({
        key: 'unionTypeTime',
        data: '',
      });

      wx.setStorage({
        key: 'unionType',
        data: ''
      });

      this.setSessionKey('');
      this.setUserInfo({});

      this.doLogin();
    });

    // yas 登录成功回调上报
    event.on('yas-login-type-report', params => {
      yas.report('YB_MY_LOGIN', params);
    });

    // yas  注册成功后上报
    event.on('yas-user-register-success', params => {
      yas.report('YB_REGISTER_SUCCESS', params);
    });

    let shareParams = {};
    if (options && options.query) {
      for (var Key in options.query) {
        shareParams[Key] = options.query[Key];
      }
    }
    yas.report('YB_SHARE_UNION_TYPE', shareParams)

    yas.report('YB_ENTER_FOREGROUND'); // 系统-程序切换置前台上报
    if (this.reportData.awakeReported === false) {
      let path = options.path || ' ';

      if (Object.keys(options.query).length) {
        path = `${path}?${stringify(options.query)}`;
      }

      yas.report('YB_AWAKE_MP', {
        PAGE_PATH: path
      }); // 唤起事件,即每次启动后获取到原始的推广路径时上报该事件,以对推广渠道数据进行监测;

      this.reportData.awakeReported = true;
    }
  },
  onHide: function() {
    yas.report('YB_ENTER_BACKGROUND'); // 系统 - 程序切换置后台上报
  },
  doLogin: function() {
    // 默认自动登录,退出不走自动登录
    if (!this._getSync('disableAutoLogin')) {
      this.getSessionKey();
      return Promise.resolve(this.wechatAuthLogin());
    }
  },
  _getSync: function(key) {
    try {
      return wx.getStorageSync(key);
    } catch (e) {
      console.log(`wx.getStorageSync get ${key} failed.`);
      return {};
    }
  },
  _setSync: function(key, value) {
    try {
      wx.setStorageSync(key, value);
    } catch (e) {
      console.log(`wx.setStorageSync set ${key} failed.`);
    }
  },
  _removeSync: function(key) {
    try {
      wx.removeStorageSync(key);
    } catch (e) {
      console.log(`wx.removeStorageSync del ${key} failed.`);
    }
  },
  getWechatThirdSession: function() {
    this.globalData.thirdSession = this._getSync('thirdSession');
    return this.globalData.thirdSession;
  },
  setWechatThirdSession: function(session) {
    this.globalData.thirdSession = session;
    wx.setStorage({
      key: 'thirdSession',
      data: this.globalData.thirdSession
    });
  },
  getUid: function() {
    return this.globalData.userInfo.uid || 0;
  },
  getUserInfo: function() {
    this.globalData.userInfo = this._getSync('userInfo');
    return this.globalData.userInfo;
  },
  getUnionID: function() {
    this.globalData.unionID = this._getSync('unionID');
    return this.globalData.unionID;
  },
  getSessionKey: function() {
    this.globalData.sessionKey = this._getSync('sessionKey');
    return this.globalData.sessionKey;
  },
  getOpenID: function() {
    let openid;

    if (this.globalData.openID) {
      return this.globalData.openID;
    }

    openid = wx.getStorageSync('openID');
    this.globalData.openID = openid;
    return openid;
  },
  setOpenID: function(openID) {
    if (openID) {
      this.globalData.openID = openID;
      wx.setStorage({
        key: 'openID',
        data: openID
      });
    }
  },
  setUnionID: function(unionID) {
    this.globalData.unionID = unionID;
    wx.setStorage({
      key: 'unionID',
      data: unionID
    });
    event.emit('wx-union-id-update');
  },
  setUserInfo: function(user) {
    this.globalData.userInfo = user;
    wx.setStorage({
      key: 'userInfo',
      data: this.globalData.userInfo
    });
    setTimeout(() => {
      let uid = user.uid;
      this.setUserUnionType(uid);
    }, 1000);

    
  },
  getUserUnionType() {
    return this.globalData.userUnionType;
  },
  setUserUnionType(uid) {
    if (!uid) {
      return;
    }

    if (this.globalData.userUnionType) {
      return;
    }

    commonModel.getUnionTypeWithUid(uid).then(result => {
      console.log('uniontype=>', result);

      if (!result) {
        return;
      }

      this.globalData.userUnionType = result.unionType || '';
      this.globalData.userUnionTypeImageUrl = result.imageUrl || '';
      this.globalData.shareId = result.shareId || 0;
      this.globalData.userNounionTypeImageUrl = result.applyImageUrl || '';
    }).catch((err) => {
      console.error('userTypeErr=>', err);
    });
  },
  updateUnionType(unionType) {
    if (!unionType) {
      return;
    }

    let timeS = new Date().getTime() + '';

    this.globalData.union_type = unionType;
    this.globalData.unionTypeTime = timeS;
    wx.setStorage({
      key: 'unionTypeTime',
      data: timeS,
    });
    wx.setStorage({
      key: 'unionType',
      data: unionType
    });
  },
  getUnionType() {
    /*
     *unionType表示渠道号,在推广阶段通过商品详情页等传入。
     * 接收到该参数时,赋值给全局变量时,持久化到本地。
     * 在取值时,先从全局变量获取,若未获取到则从本地缓存中获取。
     * 时效7天
     */
    try {
      let value = this.checkUnionType(this.globalData.union_type, this.globalData.unionTypeTime);

      if (!value) {
        let unionType = wx.getStorageSync('unionType');
        let unionTypeTime = wx.getStorageSync('unionTypeTime');

        value = this.checkUnionType(unionType, unionTypeTime);
      }
      return value;
    } catch (e) {
      // console.log(e)
    }
  },

  checkUnionType(unionType, unionTypeTime) {
    if (!unionType) {
      return '';
    }

    let time_old = unionTypeTime;
    let time_new = new Date().getTime() + '';
    let dayDiff = parseInt((parseInt(time_new) - parseInt(time_old)) / 1000);

    if (dayDiff > 7 * 24 * 3600) {
      return '';
    }
    return unionType;
  },
  setSessionKey: function(sessionKey) {
    this.globalData.sessionKey = sessionKey;
    this._setSync('sessionKey', sessionKey);
  },
  resumeUserInfo: function() {
    this.globalData.userInfo = this._getSync('userInfo');
  },
  resumeSessionKey: function() {
    this.globalData.sessionKey = this._getSync('sessionKey');
  },
  wechatAuthLogin: function() {
    if (!this.globalData.userInfo.uid || !this.globalData.sessionKey) {
      return wechatAuthLogin().then(res => {
        if (res.code === 10003) { // 微信号已绑定手机号
          this.setSessionKey(res.data.sessionKey);
          this.setUserInfo(res.data);
          event.emit('user-login-success');
        }

        if (res.code === 10004) { // 微信号未绑定手机号
          // 自动登录未绑定静默处理、不强制绑定
        }
      }).catch(() => {});
    }

    return verifySessionKey().then(ves => {
      if (ves.code !== 200) { // sessionKey已过期

        // 清理原存储的用户信息
        this.clearUserSession();
        return wechatAuthLogin();
      } else {
        this.resumeUserInfo();
        this.resumeSessionKey();
        event.emit('user-login-success');
        return Promise.resolve({});
      }
    }).then(res => {
      if (res.code === 10003) { // 微信号已绑定手机号
        this.setSessionKey(res.data.sessionKey);
        this.setUserInfo(res.data);
        event.emit('user-login-success');
      }

      if (res.code === 10004) { // 微信号未绑定手机号
        // 自动登录未绑定静默处理、不强制绑定
      }
      event.emit('enable-tap-login');
    }).catch(() => {
      event.emit('enable-tap-login');
    });
  },
  clearUserSession: function() {
    this.setSessionKey('');
    this.setUserInfo({});
    this.setUnionID('');
  },
  getReportUid() {
    return this.globalData.userInfo.uid || this._getSync('userInfo').uid || '';
  },
  getAppId() {
    return config.appid;
  },
  getPvid() {
    return MD5(`${new Date().getTime()}${udid.get()}`).toString();
  },
  getSystemInfo() {
    return this.globalData.systemInfo;
  },
  getMiniappType() {
    return config.mini_app_type;
  }
});