Login.js 6.68 KB
import commonApi from '~/api/module/common.js'
const phoneRex = /^[1]([3-9])[0-9]{9}$/
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loginType: 0,
    isAgree: false,
    mobile: '',
    captcha: '',
    count: 0,
    showChooseSource: false,
    showEnableWallet: false,
    showEnableSuccess: false,
    buttons: [{
      text: '取消'
    }, {
      text: '同意',
      extClass: 'btn_primary'
    }],
    pointsSource: [],
    walletObj: {},
    loginData: {}
  },
  changeLoginType() {
    const {
      loginType
    } = this.data
    this.setData({
      loginType: loginType == 0 ? 1 : 0
    })
  },
  // 同意隐私政策
  handleChangeAgree() {
    this.setData({
      isAgree: !this.data.isAgree
    })
  },

  // 跳转隐私政策页面
  handleAgree(e) {
    const {
      name
    } = e.currentTarget.dataset
    wx.p.router.jumpH5(`https://img01.glsx.com.cn/weapp/resource/miniprogram/points-mall/html/${name}.html`, true)
  },
  async onLoad() {
    wx.p.wxApi.showLoading()
    const {
      data,
      code
    } = await wx.p.api.userApi.login()
    // if (code == '0') this.customerLoginCallBack(data)
    if (data) this.sessionId = data.sessionId
    wx.hideLoading()
  },
  input(e) {
    const {
      value
    } = e.detail, {
      name
    } = e.target.dataset
    this.setData({
      [name]: value
    })
  },
  /**获取验证码 */
  async getSmsCode() {
    const {
      mobile,
      count
    } = this.data
    try {
      if (!phoneRex.test(mobile)) throw '请输入正确的手机号'
      if (count) throw '验证码发送过于频繁,请稍后在试'
    } catch (error) {
      return wx.p.wxApi.showToast(error)
    }
    wx.p.wxApi.showLoading()
    try {
      const {
        code,
        message
      } = await wx.p.api.userApi.getSmsCode(mobile)
      if (code == '0') {
        wx.p.wxApi.showToast('验证码已发送')
        this.countDown(60)
      } else wx.p.wxApi.showToast(message || '发送验证码失败')
    } catch (error) {
      wx.p.wxApi.showToast(error)
    }
  },
  /**验证码倒计时 */
  countDown(countDown) {
    if (countDown) this.setData({
      count: countDown
    })
    setTimeout(() => {
      let {
        count
      } = this.data
      this.setData({
        count: --count
      })
      if (count > 0) this.countDown()
      else this.setData({
        count: null
      })
    }, 1e3)
  },
  showTips(message) {
    wx.p.wxApi.showToast(typeof message == 'string' ? message : '请同意以下用户协议')
  },
  showModal() {
    this.setData({
      showAgreeModal: true
    })
  },
  dialogConfirm(e) {
    let { value } = e.detail
    this.setData({
      showAgreeModal: false
    })
    if (value == 1) {
      this.setData({
        isAgree: true
      })
    }
  },
  /**手机号短信登录 */
  async phoneLogin() {
    const {
      mobile,
      captcha,
      isAgree
    } = this.data
    if (!isAgree) {
      return this.showModal()
    }
    try {
      if (!mobile) throw '请输入手机号'
      if (!captcha) throw '请输入验证码'
      if (!phoneRex.test(mobile)) throw '请输入正确的手机号'
      wx.p.wxApi.showLoading()
      const {
        code,
        data,
        message
      } = await commonApi.phoneSmsLogin({
        mobile,
        captcha,
        sessionId: this.sessionId
      })
      if (code == '0') {
        data.headImgUrl = data?.logo
        this.customerLoginCallBack(data)
      } else {throw message}
      wx.hideLoading()
    } catch (error) {
      this.showTips(error || '服务不可用')
      setTimeout(() => {
        this.onLoad()
      }, 1500)
    }
  },
  /**微信登录 */
  async getPhoneNumber({
    detail
  }) {
    try {
      if (detail.errMsg && ['authorized', 'deny'].findIndex(e => detail.errMsg.toLowerCase().includes(e)) != -1) return
      if (!detail?.code) throw '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
      wx.p.wxApi.showLoading()
      let obj = {
        encryptedData: detail.encryptedData,
        iv: detail.iv,
        sessionId: this.sessionId
      }
      const {
        code,
        data,
        message
      } = await commonApi.authPhoneLogin(obj)
      wx.hideLoading()
      if (code == '0') this.customerLoginCallBack(data)
      else throw message
    } catch (error) {
      this.showTips(error || '服务不可用')
      setTimeout(() => {
        this.onLoad()
      }, 1500)
    }
  },
  /**登录回调 */
  customerLoginCallBack(data) {
    wx.p.storage.set('sessionId', data?.sessionId)
    this.setData({loginData: data})
    // 获取积分来源
    this.getSource()
  },

  getSource() {
    let { loginData } = this.data
    commonApi.getPointsSourceList({
      staffPhone: loginData?.phone
    }).then(res => {
      let { code, data, message } = res
      if (code == 0) {
        this.setData({pointsSource: data?.map(val => { return val.channelSource })})
        if (data?.length > 1) { // 积分渠道来源大于1 需要选择
          this.setData({
            showChooseSource: true
          })
        } else if (data?.length == 1) {
          this.setChannelSource(data[0]?.channelSource)
        }
      } else {
        wx.p.wxApi.showToast(message)
      }
    })
  },
  // 设置积分渠道
  setChannelSource(source) {
    let { loginData } = this.data
    // 查询门店数据
    this.getMerchantList(source, loginData)
  },
  getMerchantList(source, loginData) {
    commonApi.getMerchantData({staffPhone: loginData?.phone, channelSource: source}).then(res => {
      let { code, data, message } = res
      if (code == 0) {
        // 当没有门店数据返回时 默认赋值一个merchantId为 -1的门店作为游客使用
        if (!data?.length) {
          data = [{merchantId: -1}]
        }
        if (data?.length == 1) { // 仅有一个门店时跳过选择门店页面 直接登录成功
          const { merchantId, merchantName } = data[0] || {}
          wx.p.isLogin = true;
          wx.p.storage.set('userInfo', {
              ...loginData,
              channelSource: source,
              merchantId,
              merchantName
          })
          wx.p.router.reLaunch('/pages/tab/index/index', {loginPageFlag: true})
        } else { // 跳转到选择门店页面
          wx.p.router.go('/pages/chooseMerchant/index', {loginData: {channelSource: source, ...loginData}, merchantList: data, loginPageFlag: true})
        }
      } else {
        wx.p.wxApi.showToast(message)
      }
    })
  },

  // 选择积分来源确定
  pointSourceEvent(e) {
    this.setChannelSource(e.detail)
  },

  // 开通成功
  successConfirm() {
    let { walletObj } = this.data
    // 替换钱包昵称
    this.replaceNickName({...walletObj})
  },

  back() {
    wx.p.router.back()
  }
})