app.js 9.19 KB
const restapi = require('/utils/restapi.js')
const utilapi = require('/utils/util.js')
let app_timer = null
import router from './router/index.js'
import * as Sentry from './utils/sentry-miniapp.wx.min'
// 先屏蔽不上sentry功能
// import * as Sentry from 'sentry-miniapp'
const accountInfo = wx.getAccountInfoSync()
// console.log(Sentry)
// 初始化 Sentry 生产环境再开启
// accountInfo.miniProgram.envVersion == 'release' &&
Sentry.init({
  dsn: 'https://bcc13d39aab94cba95ce03b65035b5a5@sentry.glsx.com.cn/25'
})
//app.js
App({
  // 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
  onLaunch: function (option) {
    wx.$router = router
    var self = this
    // 获取用户登录场景值
    // console.log('onLaunch.option', option)

    // 初始化本地会话信息
    self.initSession()

    self.globalData.app = this
    self.globalData.scene = option.scene
    self.globalData.appId = wx.getAccountInfoSync().miniProgram.appId

    self.globalData.initAppInfo(option.query.merchantId | option.query.m, function (res) {
      // console.log('App onLaunch', res)
    })

    /**
     * 获取自定义导航栏信息
     */
    let padding = 6
    let ios = true
    wx.getSystemInfo({
      success(res) {
        // console.log(res)
        if (res.platform == 'android') {
          padding = 8
          ios = false
        }
        self.globalData.systemInfo = {
          statusBarPadding: padding,
          ios: ios,
          statusBarHeight: res.statusBarHeight,
          phoneHeight: res.screenHeight - res.statusBarHeight
        }
      }
    })

    // 打开调试
    // wx.setEnableDebug({
    //   enableDebug: true
    // })
  },

  /**
   * 初始化本地会话
   */
  initSession: function () {
    var sessionId = wx.getStorageSync(this.globalData.sessionKey)
    if (!sessionId) {
      sessionId = utilapi.sessionId()
      // 从cookie中获取sessionId存储到本地
      // console.log('sessionId:', sessionId)
      wx.setStorageSync(this.globalData.sessionKey, sessionId)
    }
  },

  initAppInfo: function (merchantId, callback) {
    let self = this
    if (merchantId == 0) {
      merchantId = ''
    }
    // console.log('initAppInfo merchantId:', merchantId)
    restapi.getAppInfo(merchantId, function (res) {
      console.log('getAppInfo', res)
      if (res.returnCode == 0) {
        self.globalData.extConfig = res.data
        wx.setStorageSync('EXT_CONFIG', res.data)
        if (callback) {
          callback(res.data)
        }
      }
    })
  },

  // 当小程序启动,或从后台进入前台显示,会触发
  onShow: function (option) {
    let self = this
    // console.log('onShow.option ', option)
    self.globalData.sceneData = option
    self.globalData.scene = option.scene
    self.globalData.initAppInfo(option.query.merchantId | option.query.m, function (res) {
      // console.log('App onShow', res)
    })

    //获取转发场景下携带的参数
    if (option.shareTicket) {
      let shareInfo = wx.getShareInfo(option.shareTicket)
      console.log('shareInfo', shareInfo)
    }
    //我的活动栏,首次进入小程序点击“我的活动”(小程序删除后再使用也算首次),显示使用提示“如何使用做活动”,yes:显示,no:不显示
    let showDoActivity = wx.getStorageSync('showDoActivity')
    if (!showDoActivity) {
      wx.setStorageSync('showDoActivity', 'yes')
    }
  },

  onHide: function () {
    let that = this
    that.globalData.clearMarqueeTime = true
    if (app_timer) clearInterval(app_timer)
  },

  login: function () {
    // debugger
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var self = this
        self.globalData.code = res.code
        console.log('login', res)
        // restapi.jsTestLogin(res.code, self.globalData.appId, function (response) {
        restapi.jscodeLogin(res.code, self.globalData.appId, function (response) {
          console.log('response', response)
          switch (response.returnCode) {
            case '0': // 获取微信用户信息成功
              self.globalData.userInfo = response.data
              if (response.data.accountId) {
                // 已获取手机号
                // 登录成功回调
                self.loginSuccessCallback(response.data)
              } else {
                // 未获取手机号,授权获取
                wx.navigateTo({
                  url: '/pages/auth/phone/phone'
                })
              }
              break
            case '-1':
              // 获取微信用户信息为空,授权获取
              if (response.errId == '200205') {
                self.userAuth()
              }
              break
            default:
              wx.showToast({
                title: response.message
              })
          }
        })
      }
    })
  },

  userAuth: function () {
    var self = this
    // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
    wx.getUserProfile({
      desc: '用于完善会员资料',
      lang: 'zh_CN',
      success: res => {
        wx.checkSession({
          success() {
            //session_key 未过期,并且在本生命周期一直有效
            self.authLogin(res)
          },
          fail() {
            // session_key 已经失效,需要重新执行登录流程
            wx.login({
              success: response => {
                appInstance.globalData.code = response['code']
                self.authLogin(res)
              }
            })
          }
        })
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  authLogin: function (wechatAuthSetting) {
    var self = this
    wechatAuthSetting['code'] = self.globalData.code
    wechatAuthSetting['appId'] = self.globalData.appId
    wechatAuthSetting['merchantId'] = self.globalData.extConfig.merchantId
    console.log('wechatAuthSetting', wechatAuthSetting)
    restapi.authLogin(
      wechatAuthSetting,
      function (response) {
        console.log('authLogin', response)
        switch (response.returnCode) {
          case '0':
            self.globalData.userInfo = response.data
            if (response.data.accountId) {
              // 已获取手机号
              // 登录成功回调
              self.loginSuccessCallback(response.data)
            } else {
              // 未获取手机号,授权获取
              wx.navigateTo({
                url: '/pages/auth/phone/phone'
              })
            }
            break
          default:
            wx.showToast({
              title: response.message
            })
        }
      },
      function () {
        console.log('authLogin request fail!')
      }
    )
  },

  /**
   * 提示框
   */
  showMessage: function (title) {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 2000
    })
  },
  getCustomerMessageNew(accountId) {
    if (!accountId) {
      return
    }
    restapi.getCustomerMessageNew(
      {
        accountId: accountId,
        sendType: 'B'
      },
      res => {
        console.log(res)
        if (res.returnCode == 0) {
          if (res.data.length > 0) {
            wx.showTabBarRedDot({
              index: 1
            })
          }
        }
      }
    )
  },
  /**
   * 登录成功回调
   */
  loginSuccessCallback: function (userInfo) {
    console.log(userInfo)
    this.globalData.userInfo = userInfo
    this.globalData.accountId = userInfo.accountId
    // this.getCustomerMessageNew(userInfo.accountId)
    // if (!app_timer) {
    //   app_timer = setInterval(() => {
    //     this.getCustomerMessageNew(userInfo.accountId)
    //   }, 1000 * 600)
    // }
    if (this.userInfoReadyCallback) {
      this.userInfoReadyCallback(userInfo)
    }
  },

  globalData: {
    sessionKey: 'DJ_S_',
    clearMarqueeTime: false,
    extConfig: {
      appId: null,
      appName: '我的智慧门店',
      merchantId: null,
      merchantName: ''
    },
    scene: null,
    app: null,
    userInfo: null,
    code: null,
    accountId: null,
    unionId: '',
    authUserInfo: false,
    authPhone: false,
    curUserId: '',
    nobindAppear: false,
    deviceName: '',
    smartCarAppList: [],
    deviceStatusVO: {},
    myMileageVO: {},
    // 精品交付单需要的用户手机号
    phoneNumber: '',
    loginSuccessCallback: function (userInfo) {
      this.app.loginSuccessCallback(userInfo)
    },
    login: function () {
      this.app.login()
    },
    selectedDevice: {
      userId: '',
      typeNmae: '',
      typeId: ''
    },
    systemInfo: null,
    //我的活动栏需要的用户id
    systemUserId: null,
    employeeId: null,
    smartCarMapKey: 'ZEJBZ-LVNRG-EXMQH-I74N6-EHNIS-WHF6E',
    sceneData: null,
    appId: null,
    // 初始化应用信息
    initAppInfo: function (merchantId, callback) {
      var extConfig = wx.getStorageSync('EXT_CONFIG')
      if (extConfig) {
        this.extConfig = extConfig
        if (merchantId && extConfig.merchantId != merchantId) {
          this.app.initAppInfo(merchantId, callback)
        } else if (extConfig.merchantId) {
          callback(extConfig)
        }
      } else {
        this.app.initAppInfo(merchantId | null, callback)
      }
    }
  }
})