loading.js 5.81 KB
import { checkLoginUserInfo, setRouteData, setLoginInfo, loginModal } from '../lib/index'
import { getSessionId } from '~/utils/cache/storageApi'
import USERAPI from '~/api/usersApi/index'
import { IMG_URL } from '~/utils/constantData'
import md5 from '~/utils/lib/md5'
import { sceneByIdApi } from '~/api/checkProduct.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_URL
  },

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

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const appEnter = wx.getEnterOptionsSync()
    if (appEnter.scene == 1037) {
      if (Object.keys(appEnter.referrerInfo).length) {
        const { extraData } = appEnter.referrerInfo
        if (extraData && Object.keys(extraData).length) this.phoneSmsLogin(extraData)
        else this.init()
      } else this.init()
    } else if ([1047, 1048, 1049].includes(appEnter.scene)) {
      if (!this.options.scene) {
        this.init()
        return
      }
      sceneByIdApi({
        id: decodeURIComponent(appEnter.query.scene).split('=')[1]
      }).then(res => {
        const url = res.scene
        const obj = this.arrToObj(url.split('&'))
        if (obj.hasOwnProperty('userName') && obj.hasOwnProperty('password')) {
          wx.$storage.rm("sessionId")
          wx.$storage.rm("userInfo")
          wx.$storage.rm("auto_login_object")
          wx.$storage.rm("posterId")
          wx.$storage.rm("mock_data")
          wx.$storage.set("firstLogin", "firstLogin")
          wx.$storage.set("disLikeRecordFlag", true)
          this.accountLogin(obj)
        } else this.init()
      }).catch(() => {
        this.init()
      })
    } else this.init()
  },

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },
  arrToObj(list) {
    if (!Array.isArray(list)) {
      return {}
    }
    var obj = {}
    list.forEach(item => {
      let temp = item.split('=')
      obj[temp[0]] = temp[1]
    })
    return obj
  },

  init() {
    wx.nextTick(() => {
      const sessionId = getSessionId(),
        { url, targetPath = url ? decodeURIComponent(url) : '' } = this.options
      let path = 'pages.output',
        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)
  },
  phoneSmsLogin(extraData) {
    USERAPI.phoneSmsLogin({
      mobile: extraData.phone,
      code: extraData.smscode
    })
      .then(({ code, data, message }) => {
        if (code == '0') checkLoginUserInfo(data)
        else {
          wx.$api.showToast(message || '系统异常')
          setTimeout(() => {
            wx.$router.reLaunch('login.index')
          }, 1e3)
        }
      })
      .catch(err => {
        wx.$api.showToast('系统异常')
        setTimeout(() => {
          wx.$router.reLaunch('login.index')
        }, 1e3)
      })
  },
  accountLogin(obj) {
    const params = {
      userName: obj.userName,
      password: md5(obj.password)
    }
    USERAPI.accountLogin(params).then(({ code, data, message }) => {
      if (code == '0') {
        const { sessionId, loginUserInfoList } = data
        var routeParams = {}
        var list = []
        if (obj.url == '/packagesList/packageOutput/pages/summary') {
          routeParams = {
            merchantId: obj.merchantId,
            merchantName: obj.merchantName,
            pMerchantId: loginUserInfoList[0].subLoginUser.merchantId,
            pMerchantName: loginUserInfoList[0].subLoginUser.merchantName,
            isSuper: loginUserInfoList[0].isSuper,
            fixScenceCode: obj.sceneCode
          }
          Object.keys(routeParams).forEach((item) => {
            list.push(item + "=" + routeParams[item])
          })
          this.options.targetPath = obj.url + "?" + list.join("&")
        }
        setLoginInfo(loginUserInfoList[0], sessionId)
      } else {
        wx.$api.showToast(message || '系统异常')
        setTimeout(() => {
          wx.$router.reLaunch('login.index')
        }, 1e3)
      }
    })
      .catch(err => {
        wx.$api.showToast('系统异常')
        setTimeout(() => {
          wx.$router.reLaunch('login.index')
        }, 1e3)
      })
  }
})