import type { AuthToken } from '../../utils/api' import { sendSmsCode, wxBindMobile } from '../../utils/api' import { saveAuthToken, wxLoginCode } from '../../utils/auth' import { ApiError } from '../../utils/request' const MOBILE_PATTERN = /^1[3-9]\d{9}$/ let countdownTimer = 0 Page({ data: { mobile: '', code: '', countdown: 0, submitting: false }, onUnload() { if (countdownTimer) { clearInterval(countdownTimer) countdownTimer = 0 } }, onMobileInput(e: WechatMiniprogram.Input) { this.setData({ mobile: e.detail.value }) }, onCodeInput(e: WechatMiniprogram.Input) { this.setData({ code: e.detail.value }) }, async onSendCode() { const mobile = this.data.mobile.trim() if (!MOBILE_PATTERN.test(mobile)) { this.toast('请输入正确的手机号') return } if (this.data.countdown > 0) return try { await sendSmsCode(mobile) this.toast('验证码已发送') this.startCountdown() } catch (err) { this.toast((err as Error).message || '验证码发送失败') } }, startCountdown() { if (countdownTimer) clearInterval(countdownTimer) this.setData({ countdown: 60 }) countdownTimer = setInterval(() => { const next = this.data.countdown - 1 if (next <= 0) { clearInterval(countdownTimer) countdownTimer = 0 this.setData({ countdown: 0 }) return } this.setData({ countdown: next }) }, 1000) as unknown as number }, async onSubmit() { if (this.data.submitting) return const mobile = this.data.mobile.trim() const code = this.data.code.trim() if (!MOBILE_PATTERN.test(mobile)) { this.toast('请输入正确的手机号') return } if (code.length < 4) { this.toast('请输入短信验证码') return } this.setData({ submitting: true }) try { // 微信 code 一次性且短期有效,必须在提交时重新获取 const loginCode = await wxLoginCode() const token = await wxBindMobile(loginCode, mobile, code) const authToken: AuthToken = { tokenType: token.tokenType || 'Bearer', accessToken: token.accessToken, refreshToken: token.refreshToken || '', expiresIn: token.expiresIn || 0 } saveAuthToken(authToken) wx.reLaunch({ url: '/pages/home/index' }) } catch (err) { this.toast( err instanceof ApiError ? err.message : (err as Error).message || '绑定失败,请稍后重试' ) } finally { this.setData({ submitting: false }) } }, onOpenLegal(e: WechatMiniprogram.TouchEvent) { const { type } = e.currentTarget.dataset as { type: 'agreement' | 'privacy' } wx.navigateTo({ url: `/pages/legal/index?type=${type}` }) }, toast(title: string) { wx.showToast({ title, icon: 'none', duration: 1800 }) } })