app.js 10.3 KB
//app.js
import {WeToast} from './vendors/toast/wetoast';
import md5 from './vendors/md5';
var mta = require('./vendors/mta_analysis.js')
import { wechatLoginAction } from './utils/login';
import './router/index';
import event from './utils/event.js';

import {  logEvent, 
          YB_LAUNCH_APP,
          YB_EXIT_APP,
          YB_ENTER_FOREGROUND,
          YB_ENTER_BACKGROUND,
          YB_PAGE_OPEN_L,
          YB_AWAKE_MP,
          YB_SERVICE_PUSH,
          YB_WX_SCAN_CODE,
          YB_SHARE_UNION_TYPE
        } from './libs/analytics.js';

import { appReport } from './libs/appReport.js';

let plugin = requirePlugin("yoho-utils");
import config from './common/config.js'  
App({
  onLaunch: function (options) {
    let that = this;
    plugin.setApp(this);
    plugin.setConfig(config);
    plugin.setSystemInfo();
    plugin.setUdid();
    plugin.verify.getVerifyKey().then(res => {
      wechatLoginAction(function (response) {
        that.getShareInfo();
      });
    })
    this.checkNetworkType()

    if (options && options.scene){
      plugin.setGlobalData('ch', options.scene, false)
    }

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

    wx.checkSession({
      success: function () {
        //登录态未过期
        that.getWechatThirdSession();
        that.getUserInfo();
        that.getUnionID();
        that.getUser_union_type();
      },
      fail: function () {
        //登录态过期
        plugin.setGlobalData('WXThird_session','')
        plugin.setGlobalData('userInfo', {})
        plugin.setGlobalData('WXUnion_ID', '')
        plugin.setGlobalData('user_union_type', '', false)
      }
    })
    this.getSessionkey();
    let timestamp = new Date().getTime() + ''
    plugin.setGlobalData('sid', md5(timestamp), false)

    if (options){
      let channel = options.query.channel;
      let channelType = options.query.type;
      let params = { 'CHANNEL': channel, 'TYPE': channelType };
      logEvent(YB_LAUNCH_APP, params, this); 
    }

    this.mtainit(options);
    this.addListener();
  },
  addListener() {
    event.on('anchor-click', params => { // anchor组件中点击时上报楼层点击事件
      logEvent('YB_MAIN_EVENT', params);
    });
  },
 //当应用程序进入前台显示状态时触发
  onShow(options) {
    let that = this
    let params = {};
    let shareParams = {};
    let pathParam = ""
    if (options && options.query) {
      for (var Key in options.query) {
        console.log("key:" + Key + "==value:" + options.query[Key]);
        shareParams[Key] = options.query[Key];
        if (pathParam.length == 0) {
          pathParam = Key + '=' + options.query[Key] + '';
        } else {
          pathParam = pathParam + '&' + '' + Key + '=' + options.query[Key] + '';
        }
      }
    }
    logEvent(YB_SHARE_UNION_TYPE, shareParams, that)
    let path = '';
    if (options && options.path) {
      path = options.path
    }
    if (pathParam !== "") {
      path = path + "?" + pathParam
    }
    params = {
      PAGE_PATH: path
    };
    logEvent(YB_ENTER_FOREGROUND, params, that)
    // logEvent(YB_WX_SCAN_CODE, params, that);
    if (that.globalData.hasReportAwakeAction==='false'){
      logEvent(YB_AWAKE_MP, params, this);
      that.globalData.hasReportAwakeAction = 'true'
    }

    if (options && options.scene){
      appReport('start', "LIFECYCLE", "RESUME", {
        'activeWay': options.scene + ""
      }, this)

      if (+options.scene === 1014 && options.query.msg_id) {
        let param = {
          MSG_ID: options.query.msg_id
        }
        logEvent(YB_SERVICE_PUSH, param,that);
      }

    }else{
      appReport('start', "LIFECYCLE", "RESUME", {}, this)
    }

    let scene = options.scene || '';
    plugin.setGlobalData('currentScene', scene, false)
    this.showYOHOIconCount = 0;
  },

  //当应用程序进入后台状态时触发
  onHide () {
     let params = {};
     logEvent(YB_ENTER_BACKGROUND,params)
     appReport('start', "LIFECYCLE", "STOP", {},this)
  },
  onPageNotFound(res) {
    wx.redirectTo({
      url: `/pages/common/notfound?path=${encodeURIComponent(res.path)}`,
    })
  },

  getUserInfo: function () {
    return plugin.getGlobalDataByKey('userInfo');
  },

  getMobile: function() {
    return this.getUserInfo().mobile;
  },

  getUser_union_type: function () {
    this.getUnionTypeWithUid(this.getUid());
  },

  /*
  *union_type表示渠道号,在推广阶段通过商品详情页等传入。
  * 接收到该参数时,赋值给全局变量时,持久化到本地。
  * 在取值时,先从全局变量获取,若未获取到则从本地缓存中获取。
  * 时效7天
  */
  getUnion_type: function () {
    try {
      var value = this.checkUnion_type(this.globalData.union_type, this.globalData.union_type_time);
      if (!value) {
        let union_type = plugin.getGlobalDataByKey('union_type') || "";
        let union_type_time = plugin.getGlobalDataByKey('union_type_time') || "";
          value = this.checkUnion_type(union_type, union_type_time);
      }
      return value
    } catch (e) {
      // console.log(e)
    }
  },

  checkUnion_type: function (union_type, union_type_time) {
    if (!union_type)return '';
    let time_old = union_type_time;
    let time_new = new Date().getTime() + '';
    var dayDiff = parseInt ((parseInt(time_new) - parseInt(time_old)) / 1000 );
    if (dayDiff > 7 * 24 * 3600) {
      return '';
    }
    return union_type;
  },

  getUnionID: function () {
    return plugin.getGlobalDataByKey('WXUnion_ID')
  },

  getWechatThirdSession: function () {
    return plugin.getGlobalDataByKey('WXThird_session')
  },

  setUserInfo: function (cb) {
    plugin.setGlobalData('userInfo', cb)
    let uid = this.getUid()
    uid && this.getUnionTypeWithUid(uid)
  },

  setSessionkey: function (sessionkey) {
    plugin.setGlobalData('sessionkey', sessionkey)
  },

  setWechatThirdSession: function (session) {
    plugin.setGlobalData('WXThird_session', session)
  },

  setWXUnionID: function (unionID) {
    plugin.setGlobalData('WXUnion_ID', unionID)
  },

  setOpenID:function(openID){
    plugin.setGlobalData('openID', openID)
  },

  getOpenID: function () {
    return plugin.getGlobalDataByKey('openID')
  },

  updateUid: function (uid) {
    let userInfo = this.getUserInfo();
    userInfo.uid = uid
    plugin.setGlobalData('userInfo', userInfo)
    this.getUnionTypeWithUid(uid);
  },
  showYOHOIconCount: 0,
  globalData: {
    selectedChannel: 'boy',
    userInfo: {},
    systemInfo: null,
    WXThird_session: '',
    WXUnion_ID: '',
    openID:'',
    p2SecretKey: '', // verifyKey
    sessionkey: '',
    sid: '',
    udid:'',
    cid:'1',
    mobileRegisterState:'',
    hasReportAwakeAction: 'false',
    defraudurl:'https://activity.yoho.cn/feature/45.html?title=防诈骗提醒',
    union_type:'',//渠道号,大数据上传用
    union_type_time: '',
    ch:'',
    networkType:'0',
    deviceInfo:{},
    currentScene: 1001,
    user_union_type: '',//用户相关unionType 要与union_type区分开
    user_union_type_imageUrl: '',//联盟图片
    user_nounion_type_imageUrl:'',//非联盟用户分享banner图片
    shareId: '',
    shareInfo: {},
  },

  isLogin: function () {
    return plugin.isLogin()
  },

  getUid: function () {
    return plugin.getUid()
  },

  getMiniappType:function(){
    return plugin.getGlobalDataByKey('config').mini_app_type
  },

  /*
    获取用户相关union_type
  */
  getUnionTypeWithUid: function (uid) {
    let param = {
      method: 'app.union.shareOrder.queryUnionTypeByUid',
      uid,
    }
    let that = this;
    plugin.get({data: param})
      .then(data => {
        if (data.code == 200) {
          plugin.setGlobalData('user_union_type', data.data.unionType, false)
          plugin.setGlobalData('user_union_type_imageUrl', data.data.imageUrl, false)
          plugin.setGlobalData('shareId', data.data.shareId, false)
          plugin.setGlobalData('user_nounion_type_imageUrl', data.data.applyImageUrl, false)
          that.getShareInfo();
        }
      })
      .catch(error => {
        // console.log(error)
      });
  },

  /*
      获取分享信息
    */
  getShareInfo: function () {
    // console.log('getShareInfo');
    let param = {
      share_id: this.globalData.shareId,
    }
    let that = this;
    plugin.get({url:'/operations/api/v5/webshare/getShare', data:param})
      .then(data => {
        // console.log(data)
        if (data && data.code == 200) {
          plugin.setGlobalData('shareInfo', data.data, false)
        }
      })
      .catch(error => {
        // console.log(error)
      });
  },


  checkNetworkType:function(){
    let that = this;
    let net = '';

    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值:
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        var networkType = res.networkType
        if (networkType === 'wifi') {
          net = '1';
        } else if (networkType === '2g') {
          net = '2';
        } else if (networkType === '3g') {
          net = '3';
        } else if (networkType === '4g') {
          net = '4';
        } else {
          net = '0';
        }
        // console.log("network:",net)
      },
      complete:function(res){
        appReport('start', "LIFECYCLE", "START", {}, that)
      }
    })
    that.globalData.networkType = net;
  },

  showRelaunchModal: function () {
    wx.showModal({
      title: '提示',
      content: '使用微信小程序需要微信授权,您已经拒绝了该请求,请删除小程序重新进入。',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          wx.navigateBack({
            delta: 1
          })
        }
      }
    })
  },

  getSessionkey: function () {
    if (this.isLogin) {
      return plugin.getGlobalDataByKey('sessionkey')
    }
    return undefined;
  },

  //更新渠道号同时更新时间戳,48小时失效
  updateUnionType: function (union_type) {
    if (union_type){
      let timeS = new Date().getTime() + '';
      plugin.setGlobalData('union_type', union_type)
      plugin.setGlobalData('union_type_time', timeS)
    }
  },

  getAppId() {
    return plugin.getGlobalDataByKey('config').appid;
  },
  mtainit(e) {
    mta.App.init({
      "appID": "500570715",
      "eventID": "500570797",
    });
    // console.log("init mta");
  },
  WeToast
})