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

815 lines
18 KiB
JavaScript

const authApi = require('../../api/auth')
const userApi = require('../../api/user')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { DEFAULT_AVATAR } = require('../../utils/config')
const { getDraftValue, clearDraft, scheduleDraftSave, clearDraftTimer } = require('../../utils/form-draft')
const { runWithLoading } = require('../../utils/loading')
const phoneRegex = /^1[3-9]\d{9}$/
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/
const SETTINGS_DRAFT_KEY = 'user-settings'
const placeholderEntries = [
{
key: 'notifications',
title: '消息通知'
},
{
key: 'message-push',
title: '消息推送'
},
{
key: 'theme',
title: '主题设置'
},
{
key: 'privacy',
title: '隐私政策'
},
{
key: 'about',
title: '关于我们'
},
{
key: 'help',
title: '帮助中心'
},
{
key: 'clear-cache',
title: '缓存清理'
}
]
Page({
data: {
isLoggedIn: false,
loading: false,
savingProfile: false,
uploadingAvatar: false,
updatingPhone: false,
updatingPassword: false,
deactivating: false,
countdown: 0,
needSetPassword: false,
activeSecurityPanel: '',
userInfo: null,
defaultAvatar: DEFAULT_AVATAR,
placeholderEntries,
form: {
nickname: '',
signature: ''
},
bindPhoneForm: {
phone: '',
verificationCode: ''
},
changePhoneForm: {
newPhone: '',
verificationCode: ''
},
passwordForm: {
verificationCode: '',
password: '',
confirmPassword: ''
}
},
onShow() {
this.loadSettings()
},
onHide() {
this.clearCountdown()
clearDraftTimer(this)
},
onUnload() {
this.clearCountdown()
clearDraftTimer(this)
},
clearCountdown() {
if (this.countdownTimer) {
clearInterval(this.countdownTimer)
this.countdownTimer = null
}
},
resetSecurityForms() {
this.setData({
bindPhoneForm: {
phone: '',
verificationCode: ''
},
changePhoneForm: {
newPhone: '',
verificationCode: ''
},
passwordForm: {
verificationCode: '',
password: '',
confirmPassword: ''
}
})
},
restoreDraftValues() {
const draft = getDraftValue(SETTINGS_DRAFT_KEY, null)
if (!draft || typeof draft !== 'object') {
return
}
this.setData({
activeSecurityPanel: draft.activeSecurityPanel || '',
'form.nickname': draft.form && draft.form.nickname !== undefined ? draft.form.nickname : this.data.form.nickname,
'form.signature': draft.form && draft.form.signature !== undefined ? draft.form.signature : this.data.form.signature,
'bindPhoneForm.phone': draft.bindPhoneForm && draft.bindPhoneForm.phone ? draft.bindPhoneForm.phone : '',
'changePhoneForm.newPhone': draft.changePhoneForm && draft.changePhoneForm.newPhone ? draft.changePhoneForm.newPhone : ''
})
},
scheduleSettingsDraft() {
scheduleDraftSave(this, SETTINGS_DRAFT_KEY, () => ({
activeSecurityPanel: this.data.activeSecurityPanel,
form: {
nickname: this.data.form.nickname,
signature: this.data.form.signature
},
bindPhoneForm: {
phone: this.data.bindPhoneForm.phone
},
changePhoneForm: {
newPhone: this.data.changePhoneForm.newPhone
}
}))
},
startCountdown() {
this.clearCountdown()
this.setData({
countdown: 60
})
this.countdownTimer = setInterval(() => {
const next = this.data.countdown - 1
if (next <= 0) {
this.clearCountdown()
this.setData({
countdown: 0
})
return
}
this.setData({
countdown: next
})
}, 1000)
},
async loadSettings() {
this._avatarReloadSource = ''
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
needSetPassword: auth.getNeedSetPassword(),
loading: isLoggedIn
})
if (!isLoggedIn) {
this.clearCountdown()
this.setData({
userInfo: null,
activeSecurityPanel: '',
loading: false
})
return
}
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
this.setData({
userInfo,
'form.nickname': userInfo.nickname || '',
'form.signature': userInfo.signature || '',
needSetPassword: auth.getNeedSetPassword()
})
this.restoreDraftValues()
} catch (error) {
wx.showToast({
title: error.message || '设置页加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleBack() {
navigation.goBack('/pages/profile/index')
},
handleOpenAuth() {
navigation.openAuth('/pages/settings/index')
},
handleFormInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`form.${field}`]: event.detail.value
})
this.scheduleSettingsDraft()
},
handleBindPhoneInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`bindPhoneForm.${field}`]: event.detail.value
})
if (field === 'phone') {
this.scheduleSettingsDraft()
}
},
handleChangePhoneInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`changePhoneForm.${field}`]: event.detail.value
})
if (field === 'newPhone') {
this.scheduleSettingsDraft()
}
},
handlePasswordInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`passwordForm.${field}`]: event.detail.value
})
},
handleToggleSecurityPanel(event) {
const panel = event.currentTarget.dataset.panel
const nextPanel = this.data.activeSecurityPanel === panel ? '' : panel
this.clearCountdown()
this.resetSecurityForms()
this.setData({
activeSecurityPanel: nextPanel,
countdown: 0
})
this.scheduleSettingsDraft()
},
handleCloseSecurityPanel() {
this.resetSecurityForms()
this.clearCountdown()
this.setData({
activeSecurityPanel: '',
countdown: 0
})
this.scheduleSettingsDraft()
},
async handleSaveProfile() {
if (!this.data.form.nickname.trim()) {
wx.showToast({
title: '请输入昵称',
icon: 'none'
})
return
}
this.setData({
savingProfile: true
})
try {
await runWithLoading(() => userApi.updateUserInfo({
nickname: this.data.form.nickname.trim(),
signature: this.data.form.signature.trim()
}))
wx.showToast({
title: '资料已更新',
icon: 'none'
})
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '资料更新失败',
icon: 'none'
})
} finally {
this.setData({
savingProfile: false
})
}
},
handleChooseAvatar() {
if (this.data.uploadingAvatar) {
return
}
wx.chooseImage({
count: 1,
sizeType: ['compressed', 'original'],
sourceType: ['album', 'camera'],
success: async res => {
const filePath = Array.isArray(res.tempFilePaths) ? res.tempFilePaths[0] : ''
if (!filePath) {
return
}
this.setData({
uploadingAvatar: true
})
try {
await runWithLoading(() => userApi.uploadAvatar(filePath))
wx.showToast({
title: '头像已更新',
icon: 'none'
})
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '头像上传失败',
icon: 'none'
})
} finally {
this.setData({
uploadingAvatar: false
})
}
}
})
},
async handleDeleteAvatar() {
if (!this.data.userInfo || !this.data.userInfo.avatar) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '删除头像',
content: '删除后会恢复为默认头像。',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
try {
await runWithLoading(() => userApi.updateUserInfo({
avatar: ''
}))
wx.showToast({
title: '头像已删除',
icon: 'none'
})
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '头像删除失败',
icon: 'none'
})
}
},
async handleSwitchShop() {
if (!navigation.ensureLogin('查看门店')) {
return
}
const userInfo = this.data.userInfo
const shopIds = userInfo && Array.isArray(userInfo.shopIds) ? userInfo.shopIds : []
const shopNames = userInfo && Array.isArray(userInfo.shopNames) ? userInfo.shopNames : []
if (!shopIds.length) {
wx.showToast({
title: '当前账号还没有可用门店',
icon: 'none'
})
return
}
if (shopIds.length === 1) {
navigation.navigate('/pages/shop-detail/index', {
id: shopIds[0],
returnTo: navigation.getCurrentPageUrl()
})
return
}
const selection = await new Promise(resolve => {
wx.showActionSheet({
itemList: shopNames.map((name, index) => name || `门店 ${shopIds[index]}`),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
if (selection < 0 || selection >= shopIds.length) {
return
}
try {
const payload = await runWithLoading(() => authApi.switchShop({
shopId: shopIds[selection]
}))
getApp().setUserSession(payload)
wx.showToast({
title: '门店已切换',
icon: 'none'
})
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '门店切换失败',
icon: 'none'
})
}
},
async handleSendBindPhoneCode() {
if (this.data.countdown > 0) {
return
}
const phone = String(this.data.bindPhoneForm.phone || '').trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => userApi.sendVerificationCode({ phone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown()
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleBindPhoneSubmit() {
const phone = String(this.data.bindPhoneForm.phone || '').trim()
const verificationCode = String(this.data.bindPhoneForm.verificationCode || '').trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
if (!verificationCode) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
this.setData({
updatingPhone: true
})
try {
await runWithLoading(() => userApi.bindPhone({
phone,
verificationCode
}))
wx.showToast({
title: '手机号绑定成功',
icon: 'none'
})
this.handleCloseSecurityPanel()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '手机号绑定失败',
icon: 'none'
})
} finally {
this.setData({
updatingPhone: false
})
}
},
async handleSendChangePhoneCode() {
if (this.data.countdown > 0) {
return
}
const newPhone = String(this.data.changePhoneForm.newPhone || '').trim()
if (!phoneRegex.test(newPhone)) {
wx.showToast({
title: '请输入正确的新手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => userApi.sendVerificationCode({ phone: newPhone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown()
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleChangePhoneSubmit() {
const userInfo = this.data.userInfo || {}
const oldPhone = String(userInfo.phone || '').trim()
const newPhone = String(this.data.changePhoneForm.newPhone || '').trim()
const verificationCode = String(this.data.changePhoneForm.verificationCode || '').trim()
if (!oldPhone) {
wx.showToast({
title: '请先绑定手机号',
icon: 'none'
})
return
}
if (!phoneRegex.test(newPhone)) {
wx.showToast({
title: '请输入正确的新手机号',
icon: 'none'
})
return
}
if (!verificationCode) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
this.setData({
updatingPhone: true
})
try {
await runWithLoading(() => userApi.updatePhone({
oldPhone,
newPhone,
verificationCode
}))
wx.showToast({
title: '手机号修改成功',
icon: 'none'
})
this.handleCloseSecurityPanel()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '手机号修改失败',
icon: 'none'
})
} finally {
this.setData({
updatingPhone: false
})
}
},
async handleSendPasswordCode() {
if (this.data.countdown > 0) {
return
}
const userInfo = this.data.userInfo || {}
const phone = String(userInfo.phone || '').trim()
if (!phone) {
wx.showToast({
title: '请先绑定手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => authApi.sendVerificationCode({ phone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown()
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleUpdatePassword() {
const verificationCode = String(this.data.passwordForm.verificationCode || '').trim()
const password = String(this.data.passwordForm.password || '')
const confirmPassword = String(this.data.passwordForm.confirmPassword || '')
const userInfo = this.data.userInfo || {}
if (!userInfo.phone) {
wx.showToast({
title: '请先绑定手机号',
icon: 'none'
})
return
}
if (!verificationCode) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
if (!passwordRegex.test(password)) {
wx.showToast({
title: '密码需至少8位且包含字母和数字',
icon: 'none'
})
return
}
if (password !== confirmPassword) {
wx.showToast({
title: '两次输入的密码不一致',
icon: 'none'
})
return
}
this.setData({
updatingPassword: true
})
try {
await runWithLoading(() => userApi.updatePassword({
password,
verificationCode
}))
auth.setNeedSetPassword(false)
wx.showToast({
title: '密码已更新',
icon: 'none'
})
this.handleCloseSecurityPanel()
clearDraft(SETTINGS_DRAFT_KEY)
await this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '密码更新失败',
icon: 'none'
})
} finally {
this.setData({
updatingPassword: false
})
}
},
handleComingSoon() {
wx.showToast({
title: '该功能暂未开放',
icon: 'none'
})
},
async handleDeactivateAccount() {
if (this.data.deactivating) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '注销账号',
content: '注销后当前账号将不可继续登录,请确认是否继续。',
confirmColor: '#d5536f',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
this.setData({
deactivating: true
})
try {
await runWithLoading(() => userApi.deactivateAccount())
clearDraft(SETTINGS_DRAFT_KEY)
getApp().clearUserSession()
wx.showToast({
title: '账号已注销',
icon: 'none'
})
wx.switchTab({
url: '/pages/home/index'
})
} catch (error) {
wx.showToast({
title: error.message || '账号注销失败',
icon: 'none'
})
} finally {
this.setData({
deactivating: false
})
}
},
async handleLogout() {
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '退出登录',
content: '退出后需要重新登录才能查看订单和继续下单。',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
try {
await runWithLoading(() => authApi.logout())
} catch (error) {}
clearDraft(SETTINGS_DRAFT_KEY)
getApp().clearUserSession()
wx.showToast({
title: '已退出登录',
icon: 'none'
})
wx.switchTab({
url: '/pages/home/index'
})
},
async handleAvatarError() {
const currentAvatar = this.data.userInfo && this.data.userInfo.avatar
if (!currentAvatar) {
return
}
if (this._avatarReloadSource === currentAvatar) {
this.setData({
'userInfo.avatar': ''
})
return
}
this._avatarReloadSource = currentAvatar
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
if (!userInfo || !userInfo.avatar || userInfo.avatar === currentAvatar) {
this.setData({
'userInfo.avatar': ''
})
return
}
this.setData({
userInfo
})
} catch (error) {
this.setData({
'userInfo.avatar': ''
})
}
}
})