loading.js 2.63 KB
import {
  setRouteData,
  setLoginInfo,
  loginModal
} from '../lib/index'
import {
  getSessionId,
} from '~/utils/cache/storageApi'
import USERAPI from '~/api/usersApi/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  init() {
    const sessionId = getSessionId(),
      {
        url,
        targetPath = url ? decodeURIComponent(url) : ''
      } = this.options
    wx.nextTick(() => {
      let path = 'pages.index',
        obj = {}
      if (targetPath) obj.targetPath = targetPath
      if (sessionId) {
        USERAPI.checkSession().then(({
          code
        }) => {
          if (code == '0') {
            if (targetPath) {
              path = setRouteData(targetPath).url
              obj = setRouteData(targetPath).obj
            }
            wx.$router.reLaunch(path, obj)
          } else this.autoLogin(obj)
        })
      } else this.autoLogin(obj)
    })
  },
  autoLogin(obj) {
    const autoLoginObject = wx.$storage.get('auto_login_object')
    if (autoLoginObject) {
      const {
        failureTime,
        userName,
        password
      } = autoLoginObject
      if (Date.now() < failureTime) {
        USERAPI.accountLogin({
          userName,
          password
        }).then(async ({
          data,
          code,
          message
        }) => {
          if (code == '0' && data.loginUserInfoList.length) {
            const {
              sessionId,
              loginUserInfoList
            } = data
            setLoginInfo(loginUserInfoList[0], sessionId)
          } else {
            try {
              const reload = await loginModal({
                message: data.loginUserInfoList.length ? message : '登录失败请重试',
                cancelText: '返回'
              })
              if (reload) this.onShow()
            } catch (error) {
              wx.$storage.rm('auto_login_object')
              wx.$router.reLaunch('login.index', obj)
            }
          }
        })
      } else wx.$router.reLaunch('login.index', obj)
    } else wx.$router.reLaunch('login.index', obj)
  }
})