99 lines
2.5 KiB
JavaScript
99 lines
2.5 KiB
JavaScript
const { request } = require('../../utils/request')
|
|
|
|
const app = getApp()
|
|
|
|
Page({
|
|
data: {
|
|
phone: '13800000000',
|
|
code: '',
|
|
sending: false,
|
|
submitting: false,
|
|
countdown: 0
|
|
},
|
|
|
|
timer: null,
|
|
|
|
onUnload() {
|
|
if (this.timer) {
|
|
clearInterval(this.timer)
|
|
this.timer = null
|
|
}
|
|
},
|
|
|
|
onPhoneInput(e) {
|
|
this.setData({ phone: e.detail.value })
|
|
},
|
|
onCodeInput(e) {
|
|
this.setData({ code: e.detail.value })
|
|
},
|
|
|
|
startCountdown() {
|
|
this.setData({ countdown: 60 })
|
|
if (this.timer) clearInterval(this.timer)
|
|
this.timer = setInterval(() => {
|
|
const next = this.data.countdown - 1
|
|
if (next <= 0) {
|
|
clearInterval(this.timer)
|
|
this.timer = null
|
|
this.setData({ countdown: 0 })
|
|
} else {
|
|
this.setData({ countdown: next })
|
|
}
|
|
}, 1000)
|
|
},
|
|
|
|
async sendCode() {
|
|
if (this.data.countdown > 0 || this.data.sending) return
|
|
const phone = (this.data.phone || '').trim()
|
|
if (!phone) {
|
|
wx.showToast({ title: '请输入手机号', icon: 'none' })
|
|
return
|
|
}
|
|
this.setData({ sending: true })
|
|
try {
|
|
const result = await request('/api/auth/sms-code', {
|
|
method: 'POST',
|
|
data: { phone }
|
|
})
|
|
if (result && result.mock_code) {
|
|
this.setData({ code: String(result.mock_code) })
|
|
wx.showToast({ title: '验证码:' + result.mock_code, icon: 'none' })
|
|
} else {
|
|
wx.showToast({ title: '验证码已发送', icon: 'none' })
|
|
}
|
|
this.startCountdown()
|
|
} catch (e) {
|
|
wx.showToast({ title: '发送失败:' + e.message, icon: 'none' })
|
|
} finally {
|
|
this.setData({ sending: false })
|
|
}
|
|
},
|
|
|
|
async login() {
|
|
if (this.data.submitting) return
|
|
const phone = (this.data.phone || '').trim()
|
|
const code = (this.data.code || '').trim()
|
|
if (!phone || !code) {
|
|
wx.showToast({ title: '请填写手机号和验证码', icon: 'none' })
|
|
return
|
|
}
|
|
this.setData({ submitting: true })
|
|
try {
|
|
const result = await request('/api/auth/login', {
|
|
method: 'POST',
|
|
data: { phone, code }
|
|
})
|
|
app.globalData.token = result.access_token
|
|
app.globalData.user = result.user
|
|
wx.setStorageSync('token', result.access_token)
|
|
wx.setStorageSync('user', result.user)
|
|
wx.showToast({ title: '登录成功', icon: 'success' })
|
|
wx.redirectTo({ url: '/pages/home/home' })
|
|
} catch (e) {
|
|
wx.showToast({ title: '登录失败:' + e.message, icon: 'none' })
|
|
} finally {
|
|
this.setData({ submitting: false })
|
|
}
|
|
}
|
|
})
|