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

919 lines
24 KiB
JavaScript

const authApi = require('../../api/auth')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
const authStore = require('../../utils/auth')
const actionGuard = require('../../utils/action-guard')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
const phoneRegex = /^1[3-9]\d{9}$/
Page({
data: {
redirect: '',
activeTab: 'login',
loginType: 'password',
authHelperText: '',
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,
traditionalLoginExpanded: false,
wechatMiniSupported: false,
wechatMiniDisabledReason: '',
wechatMiniLoading: false,
showMiniShopSelector: false,
miniShopMessage: '',
miniShopTicket: '',
miniShops: [],
miniShopIndex: -1,
miniShopDisplayName: '',
miniShopNewUser: false,
miniShopSubmitting: 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 : '',
authHelperText: this.buildAuthHelperText('login', 'password')
})
this.detectWechatMiniCapability()
this.loadShopOptions()
this.consumePendingWechatMiniLogin()
this.waitForPendingWechatMiniAutoLogin()
},
onShow() {
this.consumePendingWechatMiniLogin()
},
noop() {},
detectWechatMiniCapability() {
let supported = false
let disabledReason = ''
try {
supported = wx.canIUse('button.open-type.getPhoneNumber')
const systemInfo = wx.getSystemInfoSync()
if (systemInfo && systemInfo.platform === 'devtools') {
supported = false
disabledReason = '开发者工具暂不支持一键登录,请用真机或其他方式登录'
}
} catch (error) {
supported = false
}
if (!supported && !disabledReason) {
disabledReason = '当前环境暂不支持一键登录,请使用其他方式登录'
}
this.setData({
wechatMiniSupported: supported,
wechatMiniDisabledReason: disabledReason
})
},
waitForPendingWechatMiniAutoLogin() {
const app = getApp()
if (
!app
|| typeof app.isWechatMiniAutoLoginPending !== 'function'
|| typeof app.waitForWechatMiniAutoLogin !== 'function'
|| !app.isWechatMiniAutoLoginPending()
) {
return
}
Promise.resolve(app.waitForWechatMiniAutoLogin())
.catch(() => false)
.then(async () => {
if (authStore.isLoggedIn()) {
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('自动登录后跳转失败,已回退到首页', redirectError)
await navigation.switchTab('/pages/home/index')
}
return
}
this.consumePendingWechatMiniLogin()
})
},
consumePendingWechatMiniLogin() {
const app = getApp()
if (!app || typeof app.consumePendingWechatMiniLogin !== 'function') {
return
}
const pending = app.consumePendingWechatMiniLogin()
if (pending && pending.status === 'SELECT_SHOP') {
this.openMiniShopSelector(pending)
}
},
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,
authHelperText: this.buildAuthHelperText(tab, this.data.loginType),
showResetPanel: false,
traditionalLoginExpanded: false,
loginAccountStatusText: '',
loginAccountStatusType: '',
registerAccountStatusText: '',
registerAccountStatusType: '',
registerPhoneStatusText: '',
registerPhoneStatusType: ''
})
},
handleLoginTypeChange(event) {
const type = event.currentTarget.dataset.type
this.setData({
loginType: type,
authHelperText: this.buildAuthHelperText(this.data.activeTab, type),
loginShops: [],
loginShopIndex: -1,
loginShopDisplayName: '',
allowLoginShopless: false,
loginShopMessage: '',
loginAccountStatusText: '',
loginAccountStatusType: '',
'form.shopId': ''
})
},
handleShowTraditionalLogin() {
this.setData({
traditionalLoginExpanded: true,
showResetPanel: false
})
},
handleToggleResetPanel() {
this.setData({
showResetPanel: !this.data.showResetPanel
})
},
handleInputChange(event) {
const field = event.currentTarget.dataset.field
const value = event.detail.value
const patch = {
[`form.${field}`]: value
}
if (field === 'account') {
if (this.data.activeTab === 'login') {
patch.loginAccountStatusText = ''
patch.loginAccountStatusType = ''
if (!String(value || '').trim()) {
patch.loginShops = []
patch.loginShopIndex = -1
patch.loginShopDisplayName = ''
patch.allowLoginShopless = false
patch.loginShopMessage = ''
patch['form.shopId'] = ''
}
} else {
patch.registerAccountStatusText = ''
patch.registerAccountStatusType = ''
}
}
if (field === 'phone') {
if (this.data.activeTab === 'register') {
patch.registerPhoneStatusText = ''
patch.registerPhoneStatusType = ''
} else if (this.data.loginType === 'phone' && !String(value || '').trim()) {
patch.loginShops = []
patch.loginShopIndex = -1
patch.loginShopDisplayName = ''
patch.allowLoginShopless = false
patch.loginShopMessage = ''
patch['form.shopId'] = ''
}
}
this.setData(patch)
},
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 : ''
})
},
handleMiniShopChange(event) {
const index = Number(event.detail.value)
const shop = this.data.miniShops[index]
this.setData({
miniShopIndex: index,
miniShopDisplayName: shop ? shop.shopName || '' : ''
})
},
handleCloseMiniShopSelector() {
if (this.data.miniShopSubmitting) {
return
}
this.setData({
showMiniShopSelector: false
})
},
handleResumeMiniShopSelector() {
if (!this.data.miniShopTicket || !this.data.miniShops.length) {
return
}
this.setData({
activeTab: 'login',
showMiniShopSelector: true
})
},
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
})
})
await this.finishLogin(payload, '登录成功')
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',
authHelperText: this.buildAuthHelperText('login', '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
})
}
},
handleWechatMiniUnavailableTap() {
wx.showToast({
title: this.data.wechatMiniDisabledReason || '当前环境暂不支持一键登录',
icon: 'none'
})
},
async handleWechatMiniPhoneLogin(event) {
if (!this.data.wechatMiniSupported || this.data.wechatMiniLoading) {
this.handleWechatMiniUnavailableTap()
return
}
const detail = event.detail || {}
if (!detail.code) {
wx.showToast({
title: this.resolveWechatAuthorizeError(detail),
icon: 'none'
})
return
}
this.setData({
wechatMiniLoading: true
})
try {
const wxCode = await this.requestWechatMiniCode()
const result = await runWithLoading(() => authApi.wechatMiniPhoneLogin({
wxCode,
phoneCode: detail.code,
preferredShopId: authStore.getPreferredMiniLoginShopId() || undefined
}))
await this.handleWechatMiniResult(result)
} catch (error) {
wx.showToast({
title: error.message || '微信手机号一键登录失败',
icon: 'none'
})
} finally {
this.setData({
wechatMiniLoading: false
})
}
},
async handleConfirmMiniShopLogin() {
const shop = this.data.miniShops[this.data.miniShopIndex]
if (!this.data.miniShopTicket) {
wx.showToast({
title: '登录票据已失效,请重新发起微信登录',
icon: 'none'
})
return
}
if (!shop || !shop.id) {
wx.showToast({
title: '请选择门店',
icon: 'none'
})
return
}
this.setData({
miniShopSubmitting: true
})
try {
const result = await runWithLoading(() => authApi.confirmWechatMiniLogin({
ticket: this.data.miniShopTicket,
shopId: shop.id
}))
if (!result || result.status !== 'SUCCESS') {
throw new Error((result && result.message) || '确认登录失败')
}
this.clearMiniShopSelector()
await this.finishLogin(result, result.newUser ? '注册并登录成功' : '登录成功')
} catch (error) {
wx.showToast({
title: error.message || '确认登录失败',
icon: 'none'
})
} finally {
this.setData({
miniShopSubmitting: false
})
}
},
resolveWechatAuthorizeError(detail) {
const errMsg = String((detail && detail.errMsg) || '')
if (errMsg.includes('user deny') || errMsg.includes('user cancel')) {
return '你已取消手机号授权,可继续使用账号密码或验证码登录。'
}
if (errMsg.includes('no permission')) {
return '当前小程序未开通手机号授权能力,请联系管理员检查微信配置。'
}
return '未获取到微信手机号授权,请稍后重试。'
},
requestWechatMiniCode() {
const app = getApp()
if (app && typeof app.requestWechatMiniCode === 'function') {
return app.requestWechatMiniCode()
}
return new Promise((resolve, reject) => {
wx.login({
success: res => {
if (res && res.code) {
resolve(res.code)
return
}
reject(new Error('获取微信登录凭证失败'))
},
fail: () => reject(new Error('获取微信登录凭证失败'))
})
})
},
async handleWechatMiniResult(result) {
if (!result) {
throw new Error('微信登录未返回结果')
}
if (result.status === 'SUCCESS') {
await this.finishLogin(result, result.newUser ? '注册并登录成功' : '登录成功')
return
}
if (result.status === 'SELECT_SHOP') {
this.openMiniShopSelector(result)
return
}
wx.showToast({
title: result.message || '请先使用传统方式登录',
icon: 'none'
})
},
openMiniShopSelector(result) {
const shops = Array.isArray(result && result.shops) ? result.shops : []
if (!shops.length) {
wx.showToast({
title: result && result.message ? result.message : '暂无可选门店,请稍后重试',
icon: 'none'
})
return
}
const defaultIndex = shops.length ? 0 : -1
const defaultShop = defaultIndex >= 0 ? shops[defaultIndex] : null
this.setData({
activeTab: 'login',
authHelperText: this.buildAuthHelperText('login', this.data.loginType),
showMiniShopSelector: true,
miniShopMessage: (result && result.message) || '',
miniShopTicket: (result && result.ticket) || '',
miniShops: shops,
miniShopIndex: defaultIndex,
miniShopDisplayName: defaultShop ? defaultShop.shopName || '' : '',
miniShopNewUser: Boolean(result && result.newUser)
})
},
clearMiniShopSelector() {
this.setData({
showMiniShopSelector: false,
miniShopMessage: '',
miniShopTicket: '',
miniShops: [],
miniShopIndex: -1,
miniShopDisplayName: '',
miniShopNewUser: false,
miniShopSubmitting: false
})
},
async finishLogin(payload, successMessage) {
getApp().setUserSession(payload)
this.clearMiniShopSelector()
this.setData({
loading: false,
wechatMiniLoading: false
})
wx.showToast({
title: successMessage || '登录成功',
icon: 'none'
})
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('登录后跳转失败,已回退到首页', redirectError)
await navigation.switchTab('/pages/home/index')
}
},
buildAuthHelperText(activeTab, loginType) {
if (activeTab === 'register') {
return '注册前请先选门店'
}
if (loginType === 'phone') {
return '未注册手机号会先选门店'
}
return '多门店账号需先选门店'
}
})