135 lines
2.9 KiB
JavaScript
135 lines
2.9 KiB
JavaScript
/**
|
|
* 用户数据管理器
|
|
*/
|
|
import { get, post } from '../utils/http';
|
|
|
|
export default class UserManager {
|
|
constructor() {
|
|
this.userId = null;
|
|
this.openid = null;
|
|
this.nickname = '';
|
|
this.avatarUrl = '';
|
|
this.isLoggedIn = false;
|
|
}
|
|
|
|
/**
|
|
* 初始化用户
|
|
*/
|
|
async init() {
|
|
try {
|
|
// 尝试从本地存储恢复用户信息
|
|
const cached = wx.getStorageSync('userInfo');
|
|
if (cached) {
|
|
this.userId = cached.userId;
|
|
this.openid = cached.openid;
|
|
this.nickname = cached.nickname;
|
|
this.avatarUrl = cached.avatarUrl;
|
|
this.isLoggedIn = true;
|
|
return;
|
|
}
|
|
|
|
// 获取登录code
|
|
const { code } = await this.wxLogin();
|
|
|
|
// 调用后端登录接口
|
|
const result = await post('/user/login', { code });
|
|
|
|
this.userId = result.userId;
|
|
this.openid = result.openid;
|
|
this.nickname = result.nickname || '游客';
|
|
this.avatarUrl = result.avatarUrl || '';
|
|
this.isLoggedIn = true;
|
|
|
|
// 缓存用户信息
|
|
wx.setStorageSync('userInfo', {
|
|
userId: this.userId,
|
|
openid: this.openid,
|
|
nickname: this.nickname,
|
|
avatarUrl: this.avatarUrl
|
|
});
|
|
} catch (error) {
|
|
console.error('用户初始化失败:', error);
|
|
// 使用临时身份
|
|
this.userId = 0;
|
|
this.nickname = '游客';
|
|
this.isLoggedIn = false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 微信登录(带超时)
|
|
*/
|
|
wxLogin() {
|
|
return new Promise((resolve, reject) => {
|
|
const timeout = setTimeout(() => {
|
|
reject(new Error('登录超时'));
|
|
}, 3000);
|
|
|
|
wx.login({
|
|
success: (res) => {
|
|
clearTimeout(timeout);
|
|
resolve(res);
|
|
},
|
|
fail: (err) => {
|
|
clearTimeout(timeout);
|
|
reject(err);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 获取用户游玩进度
|
|
*/
|
|
async getProgress(storyId = null) {
|
|
if (!this.isLoggedIn) return null;
|
|
return await get('/user/progress', { userId: this.userId, storyId });
|
|
}
|
|
|
|
/**
|
|
* 保存用户进度
|
|
*/
|
|
async saveProgress(storyId, currentNodeKey, isCompleted = false, endingReached = '') {
|
|
if (!this.isLoggedIn) return;
|
|
await post('/user/progress', {
|
|
userId: this.userId,
|
|
storyId,
|
|
currentNodeKey,
|
|
isCompleted,
|
|
endingReached
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 点赞故事
|
|
*/
|
|
async likeStory(storyId, isLiked) {
|
|
if (!this.isLoggedIn) return;
|
|
await post('/user/like', {
|
|
userId: this.userId,
|
|
storyId,
|
|
isLiked
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 收藏故事
|
|
*/
|
|
async collectStory(storyId, isCollected) {
|
|
if (!this.isLoggedIn) return;
|
|
await post('/user/collect', {
|
|
userId: this.userId,
|
|
storyId,
|
|
isCollected
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 获取收藏列表
|
|
*/
|
|
async getCollections() {
|
|
if (!this.isLoggedIn) return [];
|
|
return await get('/user/collections', { userId: this.userId });
|
|
}
|
|
}
|