findme-miniprogram-frontend/utils/simple-version-manager.js
2025-12-27 17:16:03 +08:00

147 lines
4 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.

// 简化版本管理器 - 检测版本更新并提醒用户清理缓存
const config = require('../config/config.js');
class VersionManager {
constructor() {
this.currentVersion = config.appVersion;
this.versionKey = 'app_version';
this.isShowingDialog = false; // 防止重复弹框
}
/**
* 检查版本更新
* @returns {boolean} 如果有版本更新或正在显示弹框,返回 true
*/
checkVersionUpdate() {
try {
// 🔥 如果正在显示弹框,直接返回 true阻塞所有逻辑
if (this.isShowingDialog) {
console.log('⚠️ 版本更新弹框正在显示中,阻塞后续逻辑');
return true;
}
const storedVersion = wx.getStorageSync(this.versionKey);
// 首次安装直接保存版本号
if (!storedVersion) {
wx.setStorageSync(this.versionKey, this.currentVersion);
return false;
}
// 版本不一致,提醒用户清理缓存
if (storedVersion !== this.currentVersion) {
console.log('⚠️ 检测到版本更新,旧版本:', storedVersion, '新版本:', this.currentVersion);
// 防止重复弹框
if (!this.isShowingDialog) {
// 🔥 立即设置标志,防止在弹框显示期间其他逻辑继续执行
this.isShowingDialog = true;
// 延迟一帧显示弹框,确保标志已设置
setTimeout(() => {
this.showClearCacheDialog(storedVersion, this.currentVersion);
}, 0);
}
return true;
}
return false;
} catch (error) {
console.error('版本检查失败:', error);
return false;
}
}
/**
* 显示版本更新提示框
*/
showClearCacheDialog(oldVersion, newVersion) {
// 设置标志防止重复弹框
this.isShowingDialog = true;
wx.showModal({
title: '版本更新',
content: `FindMe已更新版本需要重新登录以确保应用正常运行。`,
showCancel: false, // 不显示取消按钮
confirmText: '确定',
success: (res) => {
// 用户只能点确定,直接清理缓存并跳转
this.clearCacheAndRestart(newVersion);
},
complete: () => {
// 对话框关闭后重置标志
this.isShowingDialog = false;
}
});
}
/**
* 清理缓存并重启应用
*/
clearCacheAndRestart(newVersion) {
wx.showLoading({
title: '正在重启应用...',
mask: true
});
try {
// 🔥 清除全局登录状态(必须在清除存储之前)
try {
const app = getApp();
if (app) {
app.globalData.isLoggedIn = false;
app.globalData.userInfo = null;
app.globalData.nim = null; // 清除 NIM 实例
console.log('✅ 已清除全局登录状态');
}
} catch (globalError) {
console.error('清除全局状态失败:', globalError);
}
// 清理所有缓存数据
wx.clearStorageSync();
// 更新版本号
wx.setStorageSync(this.versionKey, newVersion);
setTimeout(() => {
wx.hideLoading();
// 直接跳转到登录页面
wx.reLaunch({
url: '/pages/login/login'
});
}, 1500); // 稍微延长一点时间确保清理完成
} catch (error) {
wx.hideLoading();
console.error('清理缓存失败:', error);
// 🔥 即使清理失败也清除全局状态
try {
const app = getApp();
if (app) {
app.globalData.isLoggedIn = false;
app.globalData.userInfo = null;
app.globalData.nim = null;
}
} catch (globalError) {
console.error('清除全局状态失败:', globalError);
}
wx.showToast({
title: '清理失败,请手动清理',
icon: 'error'
});
// 即使清理失败也跳转到登录页
setTimeout(() => {
wx.reLaunch({
url: '/pages/login/login'
});
}, 2000);
}
}
}
// 导出单例
module.exports = new VersionManager();