yingsa/miniprogram/pages/user/index.js

156 lines
3.6 KiB
JavaScript

const app = getApp()
const QRCode = require('../../utils/qrcode.js')
Page({
data: {
userInfo: null,
ladderUser: null,
currentStore: null,
showQrcode: false,
needProfile: false,
tempUserProfile: null
},
onLoad() {
this.initData()
},
onShow() {
this.refreshData()
},
async initData() {
// 先进行微信登录获取openid
if (!app.globalData.wxLoginInfo) {
try {
await app.wxLogin()
} catch (e) {
console.error('微信登录失败:', e)
}
}
if (app.globalData.token) {
await this.refreshData()
}
},
async refreshData() {
if (!app.globalData.token) return
try {
await app.getUserInfo()
this.setData({
userInfo: app.globalData.userInfo,
ladderUser: app.globalData.ladderUser,
currentStore: app.globalData.currentStore
})
} catch (e) {
console.error('获取用户信息失败:', e)
}
},
// 获取手机号授权
async onGetPhoneNumber(e) {
if (e.detail.errMsg !== 'getPhoneNumber:ok') {
wx.showToast({ title: '需要授权手机号才能登录', icon: 'none' })
return
}
wx.showLoading({ title: '登录中...' })
try {
// 如果没有微信登录信息,先登录
if (!app.globalData.wxLoginInfo) {
await app.wxLogin()
}
// 获取用户头像昵称
let userProfile = this.data.tempUserProfile
if (!userProfile) {
try {
const profileRes = await wx.getUserProfile({
desc: '用于完善会员资料'
})
userProfile = profileRes.userInfo
} catch (err) {
// 用户拒绝授权头像昵称,使用默认值
userProfile = { nickName: '新用户', avatarUrl: '' }
}
}
// 手机号登录
await app.phoneLogin(e.detail.encryptedData, e.detail.iv, userProfile)
// 获取门店信息
await app.getCurrentStore()
this.setData({
userInfo: app.globalData.userInfo,
ladderUser: app.globalData.ladderUser,
currentStore: app.globalData.currentStore,
needProfile: false,
tempUserProfile: null
})
wx.hideLoading()
wx.showToast({ title: '登录成功', icon: 'success' })
} catch (e) {
wx.hideLoading()
console.error('登录失败:', e)
wx.showToast({ title: e.message || '登录失败', icon: 'none' })
}
},
// 选择头像
async onChooseAvatar() {
try {
const res = await wx.getUserProfile({
desc: '用于完善会员资料'
})
this.setData({
tempUserProfile: res.userInfo,
needProfile: false
})
wx.showToast({ title: '已获取头像昵称', icon: 'success' })
} catch (e) {
wx.showToast({ title: '获取头像昵称失败', icon: 'none' })
}
},
// 旧的登录方法(兼容)
async handleLogin() {
// 触发手机号授权按钮
wx.showToast({ title: '请点击手机号登录按钮', icon: 'none' })
},
showMemberCode() {
if (!this.data.userInfo?.memberCode) return
this.setData({ showQrcode: true })
// 生成二维码
setTimeout(() => {
new QRCode('qrcode', {
text: this.data.userInfo.memberCode,
width: 200,
height: 200,
colorDark: '#000000',
colorLight: '#ffffff'
})
}, 100)
},
hideQrcode() {
this.setData({ showQrcode: false })
},
goTo(e) {
const url = e.currentTarget.dataset.url
if (!app.globalData.token) {
wx.showToast({ title: '请先登录', icon: 'none' })
return
}
wx.navigateTo({ url })
}
})