Files
JayuCloud/WeChatProgram/pages/auth/index.js
T

563 lines
14 KiB
JavaScript
Raw Normal View History

2026-04-01 15:18:35 +08:00
const authApi = require('../../api/auth')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
const phoneRegex = /^1[3-9]\d{9}$/
Page({
data: {
redirect: '',
activeTab: 'login',
loginType: 'password',
loading: false,
shops: [],
registerShopIndex: -1,
registerShopDisplayName: '',
loginShops: [],
loginShopIndex: -1,
loginShopDisplayName: '',
allowLoginShopless: false,
loginShopMessage: '',
loginAccountStatusText: '',
loginAccountStatusType: '',
registerAccountStatusText: '',
registerAccountStatusType: '',
registerPhoneStatusText: '',
registerPhoneStatusType: '',
countdown: 0,
forgotCountdown: 0,
showResetPanel: false,
form: {
account: '',
password: '',
confirmPassword: '',
nickname: '',
phone: '',
verificationCode: '',
shopId: '',
rememberMe: true
},
resetForm: {
phone: '',
verificationCode: '',
newPassword: ''
}
},
onLoad(options) {
this.setData({
redirect: options && options.redirect ? options.redirect : ''
})
this.loadShopOptions()
},
async loadShopOptions() {
try {
const shops = await shopApi.getShopsSimple()
this.setData({
shops: Array.isArray(shops) ? shops : []
})
} catch (error) {
wx.showToast({
title: '门店列表加载失败',
icon: 'none'
})
}
},
handleTabChange(event) {
const tab = event.currentTarget.dataset.tab
this.setData({
activeTab: tab,
showResetPanel: false,
loginAccountStatusText: '',
loginAccountStatusType: '',
registerAccountStatusText: '',
registerAccountStatusType: '',
registerPhoneStatusText: '',
registerPhoneStatusType: ''
})
},
handleLoginTypeChange(event) {
const type = event.currentTarget.dataset.type
this.setData({
loginType: type,
loginShops: [],
loginShopIndex: -1,
loginShopDisplayName: '',
allowLoginShopless: false,
loginShopMessage: '',
loginAccountStatusText: '',
loginAccountStatusType: '',
'form.shopId': ''
})
},
handleToggleResetPanel() {
this.setData({
showResetPanel: !this.data.showResetPanel
})
},
handleInputChange(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`form.${field}`]: event.detail.value
})
},
handleResetInputChange(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`resetForm.${field}`]: event.detail.value
})
},
handleRegisterShopChange(event) {
const index = Number(event.detail.value)
const shop = this.data.shops[index]
this.setData({
registerShopIndex: index,
registerShopDisplayName: shop ? shop.shopName || shop.name || '' : '',
'form.shopId': shop ? shop.id : ''
})
},
handleLoginShopChange(event) {
const index = Number(event.detail.value)
const shop = this.data.loginShops[index]
this.setData({
loginShopIndex: index,
loginShopDisplayName: shop ? shop.shopName || '' : '',
'form.shopId': shop ? shop.id : ''
})
},
async handleAccountBlur() {
const account = this.data.form.account.trim()
if (!account) {
return
}
if (this.data.activeTab === 'register') {
await this.checkRegisterAccountAvailability()
return
}
if (this.data.loginType !== 'password') {
return
}
await Promise.all([
this.checkLoginAccountAvailability(),
this.loadLoginShopsByAccount()
])
},
async handlePhoneBlur() {
const phone = this.data.form.phone.trim()
if (!phone) {
return
}
if (this.data.activeTab === 'register') {
if (phoneRegex.test(phone)) {
await this.checkRegisterPhoneAvailability()
}
return
}
if (this.data.loginType !== 'phone' || !phoneRegex.test(phone)) {
return
}
await this.loadLoginShopsByPhone()
},
applyLoginShopSelection(selection) {
const shops = Array.isArray(selection && selection.shops) ? selection.shops : []
const allowLoginShopless = Boolean(selection && selection.allowShoplessLogin)
let loginShopIndex = -1
let loginShopDisplayName = ''
let shopId = ''
if (!allowLoginShopless && shops.length === 1) {
loginShopIndex = 0
loginShopDisplayName = shops[0].shopName || ''
shopId = shops[0].id
}
this.setData({
loginShops: shops,
allowLoginShopless,
loginShopMessage: (selection && selection.message) || '',
loginShopIndex,
loginShopDisplayName,
'form.shopId': shopId
})
},
async checkLoginAccountAvailability() {
try {
const result = await userApi.checkLoginAccountAvailability(this.data.form.account.trim())
this.setData({
loginAccountStatusText: result && result.message ? result.message : '',
loginAccountStatusType: result && result.exists ? 'success' : 'error'
})
return Boolean(result && result.exists)
} catch (error) {
this.setData({
loginAccountStatusText: '',
loginAccountStatusType: ''
})
return false
}
},
async loadLoginShopsByAccount() {
try {
const result = await userApi.getLoginShopsByAccount(this.data.form.account.trim())
this.applyLoginShopSelection(result)
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开启门店预选,可直接登录',
shops: []
})
}
},
async loadLoginShopsByPhone() {
try {
const result = await userApi.getLoginShopsByPhone(this.data.form.phone.trim())
this.applyLoginShopSelection(result)
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开启门店预选,可直接登录',
shops: []
})
}
},
async checkRegisterAccountAvailability() {
try {
const result = await userApi.checkAccountAvailability(this.data.form.account.trim())
this.setData({
registerAccountStatusText: result && result.message ? result.message : '',
registerAccountStatusType: result && result.available ? 'success' : 'error'
})
return Boolean(result && result.available)
} catch (error) {
this.setData({
registerAccountStatusText: '',
registerAccountStatusType: ''
})
return false
}
},
async checkRegisterPhoneAvailability() {
try {
const result = await userApi.checkPhoneAvailability(this.data.form.phone.trim())
this.setData({
registerPhoneStatusText: result && result.message ? result.message : '',
registerPhoneStatusType: result && result.available ? 'success' : 'error'
})
return Boolean(result && result.available)
} catch (error) {
this.setData({
registerPhoneStatusText: '',
registerPhoneStatusType: ''
})
return false
}
},
startCountdown(fieldName) {
this.setData({
[fieldName]: 60
})
const timer = setInterval(() => {
const nextValue = this.data[fieldName] - 1
this.setData({
[fieldName]: nextValue
})
if (nextValue <= 0) {
clearInterval(timer)
}
}, 1000)
},
async handleSendCode() {
if (this.data.countdown > 0) {
return
}
const phone = this.data.form.phone.trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
if (this.data.activeTab === 'register') {
const phoneAvailable = await this.checkRegisterPhoneAvailability()
if (!phoneAvailable) {
wx.showToast({
title: this.data.registerPhoneStatusText || '该手机号已被注册',
icon: 'none'
})
return
}
}
try {
await runWithLoading(() => userApi.sendVerificationCode({
phone
}))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown('countdown')
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleSendForgotCode() {
if (this.data.forgotCountdown > 0) {
return
}
const phone = this.data.resetForm.phone.trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => authApi.sendVerificationCode({
phone
}))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown('forgotCountdown')
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
validateLoginForm() {
const form = this.data.form
if (this.data.loginType === 'password') {
if (!form.account.trim() || !form.password) {
return '请输入账号和密码'
}
} else if (!phoneRegex.test(form.phone.trim()) || !form.verificationCode.trim()) {
return '请输入正确的手机号和验证码'
}
if (!this.data.allowLoginShopless && this.data.loginShops.length && !form.shopId) {
return '请选择登录门店'
}
return ''
},
async validateRegisterForm() {
const form = this.data.form
if (!form.nickname.trim()) {
return '请输入昵称'
}
if (!form.account.trim()) {
return '请输入账号'
}
if (!phoneRegex.test(form.phone.trim())) {
return '请输入正确的手机号'
}
if (!form.verificationCode.trim()) {
return '请输入验证码'
}
if (!form.password || form.password.length < 6) {
return '密码至少 6 位'
}
if (form.password !== form.confirmPassword) {
return '两次输入的密码不一致'
}
if (!form.shopId) {
return '请选择门店'
}
const [accountAvailable, phoneAvailable] = await Promise.all([
this.checkRegisterAccountAvailability(),
this.checkRegisterPhoneAvailability()
])
if (!accountAvailable || !phoneAvailable) {
return '请先处理注册信息中的占用问题'
}
return ''
},
async handleSubmit() {
this.setData({
loading: true
})
try {
if (this.data.activeTab === 'login') {
const loginError = this.validateLoginForm()
if (loginError) {
throw new Error(loginError)
}
let payload
await runWithLoading(async () => {
payload = this.data.loginType === 'phone'
? await authApi.phoneLogin({
phone: this.data.form.phone.trim(),
verificationCode: this.data.form.verificationCode.trim(),
shopId: this.data.form.shopId || undefined
})
: await authApi.login({
account: this.data.form.account.trim(),
password: this.data.form.password,
rememberMe: true,
shopId: this.data.form.shopId || undefined
})
})
getApp().setUserSession(payload)
wx.showToast({
title: '登录成功',
icon: 'none'
})
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('登录后跳转失败,已回退到首页:', redirectError)
await navigation.switchTab('/pages/home/index')
}
return
}
const registerError = await this.validateRegisterForm()
if (registerError) {
throw new Error(registerError)
}
await runWithLoading(() => authApi.register({
account: this.data.form.account.trim(),
password: this.data.form.password,
nickname: this.data.form.nickname.trim(),
phone: this.data.form.phone.trim(),
verificationCode: this.data.form.verificationCode.trim(),
shopId: this.data.form.shopId
}))
wx.showToast({
title: '注册成功,请登录',
icon: 'none'
})
this.setData({
activeTab: 'login',
loginType: 'password',
'form.password': '',
'form.confirmPassword': '',
'form.verificationCode': ''
})
} catch (error) {
wx.showToast({
title: error.message || (this.data.activeTab === 'login' ? '登录失败' : '注册失败'),
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
async handleResetPassword() {
const form = this.data.resetForm
if (!phoneRegex.test(form.phone.trim())) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
if (!form.verificationCode.trim()) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
if (!form.newPassword || form.newPassword.length < 6) {
wx.showToast({
title: '新密码至少 6 位',
icon: 'none'
})
return
}
this.setData({
loading: true
})
try {
await runWithLoading(() => authApi.resetPasswordByPhone({
phone: form.phone.trim(),
verificationCode: form.verificationCode.trim(),
newPassword: form.newPassword
}))
wx.showToast({
title: '密码已重置,请重新登录',
icon: 'none'
})
this.setData({
showResetPanel: false,
resetForm: {
phone: '',
verificationCode: '',
newPassword: ''
}
})
} catch (error) {
wx.showToast({
title: error.message || '密码重置失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
}
})