otp/pages/mine/mine.js
2025-06-17 14:44:48 +08:00

369 lines
No EOL
8.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// pages/mine/mine.js
const {
syncTokens,
getCloudTokens,
showToast,
showLoading,
hideLoading
} = require('../../utils/util');
const config = require('../../utils/config');
const { hasValidTokens, clearAllTokens } = require('../../utils/cloud');
Page({
/**
* 页面的初始数据
*/
data: {
loading: false,
uploading: false,
clearing: false,
isLoggedIn: false,
userInfo: null,
currentYear: new Date().getFullYear()
},
onShow: function() {
// 每次显示页面时检查登录状态
const app = getApp();
const isLoggedIn = hasValidTokens();
// 如果未登录,强制重置用户信息
if (!isLoggedIn) {
this.setData({
isLoggedIn: false,
userInfo: {
avatarUrl: '/images/default-avatar.png',
nickName: '微信用户'
}
});
return;
}
// 如果已登录优先使用globalData中的用户信息
this.setData({
isLoggedIn: true,
userInfo: app.globalData.userInfo || {
avatarUrl: '/images/default-avatar.png',
nickName: '微信用户'
}
});
},
/**
* 数据备份
*/
uploadData: async function() {
// 检查登录状态
if (!this.data.isLoggedIn) {
showToast('请先登录');
return;
}
try {
const tokens = wx.getStorageSync('tokens') || [];
if (!tokens.length) {
showToast('未发现本地数据');
return;
}
// 显示确认对话框
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '数据备份',
content: '确定备份本地数据到云端?',
confirmText: '确定',
confirmColor: '#ff9c10',
success: res => resolve(res.confirm)
});
});
if (!confirmed) return;
this.setData({ uploading: true });
showLoading('正在备份...');
// 同步到云端
await syncTokens(tokens);
showToast('数据备份成功', 'success');
} catch (error) {
console.error('数据备份失败:', error);
showToast('数据备份失败,请重试');
} finally {
this.setData({ uploading: false });
hideLoading();
}
},
/**
* 数据恢复
*/
restoreData: async function() {
// 检查登录状态
if (!this.data.isLoggedIn) {
showToast('请先登录');
return;
}
try {
this.setData({ loading: true });
showLoading('正在获取云端数据...');
// 获取云端数据
const cloudTokens = await getCloudTokens();
if (!cloudTokens || !cloudTokens.length) {
showToast('未发现备份数据');
return;
}
// 显示确认对话框
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '云端数据恢复',
content: `发现${cloudTokens.length}条数据,确定使用云端数据覆盖本地记录?`,
confirmColor: '#ff9c10',
success: res => resolve(res.confirm)
});
});
if (!confirmed) return;
// 保存到本地
await wx.setStorageSync('tokens', cloudTokens);
showToast('数据恢复成功', 'success');
} catch (error) {
// 如果是404错误云端无数据不打印错误日志
if (error.statusCode !== 404) {
console.error('数据恢复失败:', error);
}
showToast('数据恢复失败,请重试');
} finally {
this.setData({ loading: false });
hideLoading();
}
},
/**
* 用户授权登录
*/
goAuth: async function() {
if (this.data.isLoggedIn) return;
try {
showLoading('登录中...');
const app = getApp();
const userInfo = await app.userLogin();
// 使用hasValidTokens检查完整的登录状态
const isLoggedIn = hasValidTokens();
if (!isLoggedIn) {
throw new Error('登录失败:未能获取有效的访问令牌');
}
// 检查是否有自定义设置
const customAvatar = wx.getStorageSync('customAvatar');
const customNickName = wx.getStorageSync('customNickName');
// 更新登录状态,优先使用自定义设置
this.setData({
isLoggedIn: true,
userInfo: {
...(userInfo || {}),
avatarUrl: customAvatar || wx.getStorageSync('userAvatar') || '/images/default-avatar.png',
nickName: customNickName || wx.getStorageSync('userNickName') || '微信用户'
}
});
showToast('登录成功', 'success');
} catch (error) {
console.error('登录失败:', error);
showToast(error.message || '登录失败,请重试');
} finally {
hideLoading();
}
},
/**
* 处理头像选择
*/
onChooseAvatar: async function(e) {
const { avatarUrl } = e.detail;
try {
showLoading('更新头像中...');
// 更新头像
this.setData({
'userInfo.avatarUrl': avatarUrl
});
// 使用异步存储操作
await Promise.all([
wx.setStorage({
key: 'userAvatar',
data: avatarUrl
}),
wx.setStorage({
key: 'customAvatar',
data: avatarUrl
})
]);
showToast('头像更新成功', 'success');
} catch (error) {
console.error('头像更新失败:', error);
// 恢复默认头像
this.setData({
'userInfo.avatarUrl': '/images/default-avatar.png'
});
showToast('头像更新失败,请重试');
} finally {
hideLoading();
}
},
/**
* 处理昵称修改
*/
onNicknameChange: function(e) {
const nickName = e.detail.value;
if (!nickName) return;
try {
// 更新昵称
this.setData({
'userInfo.nickName': nickName
});
// 保存到本地存储
wx.setStorageSync('userNickName', nickName);
// 额外保存为自定义昵称
wx.setStorageSync('customNickName', nickName);
} catch (error) {
console.error('昵称更新失败:', error);
showToast('昵称更新失败,请重试');
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
wx.stopPullDownRefresh();
},
/**
* 退出登录
*/
onLoad: function() {
const app = getApp();
// 监听全局logout事件
app.globalData.eventEmitter.on('logout', this.handleLogout.bind(this));
},
onUnload: function() {
const app = getApp();
// 移除事件监听
if (app.globalData.eventEmitter && this.handleLogout) {
app.globalData.eventEmitter.off('logout', this.handleLogout);
}
},
handleLogout: function() {
// 重置页面数据
this.setData({
isLoggedIn: false,
userInfo: {
avatarUrl: '/images/default-avatar.png',
nickName: '微信用户'
}
});
},
/**
* 清空云端数据
*/
clearCloudData: async function() {
// 检查登录状态
if (!this.data.isLoggedIn) {
showToast('请先登录');
return;
}
try {
// 显示确认对话框
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '清空云端数据',
content: '确定清空云端所有备份数据?此操作不可恢复!',
confirmText: '确定',
confirmColor: '#ff9c10',
success: res => resolve(res.confirm)
});
});
if (!confirmed) return;
this.setData({ clearing: true });
showLoading('正在清空...');
// 调用清空接口
await clearAllTokens();
showToast('云端数据已清空', 'success');
} catch (error) {
console.error('清空云端数据失败:', error);
showToast(error.message || '清空失败,请重试');
} finally {
this.setData({ clearing: false });
hideLoading();
}
},
logout: async function() {
try {
// 显示确认对话框
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
confirmText: '确定',
confirmColor: '#ff9c10',
success: res => resolve(res.confirm)
});
});
if (!confirmed) return;
showLoading('正在退出...');
// 调用全局logout方法
const app = getApp();
app.logout();
// 本地UI更新
this.handleLogout();
showToast('已退出登录', 'success');
} catch (error) {
console.error('退出登录失败:', error);
showToast('退出登录失败,请重试');
} finally {
hideLoading();
}
},
/**
* 转发
*/
onShareAppMessage: function() {
return {
title: '支持云端备份的动态验证码',
path: '/pages/index/index',
imageUrl: '/images/share.png'
};
}
});