Files
toutoukan_front/miniprogram/app.ts
2025-09-26 01:02:43 +08:00

114 lines
3.2 KiB
TypeScript

// app.ts
import { CardData, Comment, IAppOption } from "../typings";
import envConfig from "./env";
App<IAppOption>({
globalData: {
token: "",
userInfo: null,
rawCardData: [
] ,
processedCardsData: []
},
onLaunch() {
const token = wx.getStorageSync("token");
if (token) {
this.globalData.token = token;
}
},
fetchRawCardData(): Promise<CardData[]> {
return new Promise((resolve, reject) => {
wx.request({
url: `${envConfig.apiBaseUrl}/article/get`,
method: "POST",
data: {
uid: "1c3e5a7d-9b1f-4c3a-8e5f-7d9b1c3e5a7d"
},
success: (res) => {
if (res.data && res.data.success && Array.isArray(res.data.data)) {
const rawData = res.data.data as CardData[];
this.globalData.rawCardData = rawData;
const processedData = this.processVoteData(rawData);
this.globalData.processedCardsData = processedData;
console.log("成功获取文评列表:", processedData);
resolve(processedData);
} else {
const error = new Error("接口返回格式不正确");
console.error(error, res);
reject(error);
}
},
fail: (err) => {
console.error("拉取投票数据失败", err);
reject(err);
}
});
});
},
getComments(articleId: number): Promise<Comment[]> {
return new Promise((resolve, reject) => {
wx.request({
url: `${envConfig.apiBaseUrl}/comment/get`,
method: "POST",
data: {
articleId: articleId // int 类型
},
success: (res) => {
const response = res.data as CommentResponse;
if (response.success && Array.isArray(response.data)) {
resolve(response.data);
} else {
reject(new Error(response.message || "获取评论失败"));
}
},
fail: (err) => {
reject(new Error("网络请求失败"));
}
});
});
},
// 处理投票数据的方法
processVoteData(rawData: CardData[]): CardData[] {
return rawData.map(card => {
// 计算每个选项的百分比
const optionsWithPercentage = card.options.map(option => {
const percentage = card.total_voters > 0
? Math.round((option.votes / card.total_voters) * 100)
: 0;
return {
...option,
percentage,
isSelected: false // 初始化选中状态
};
});
return {
...card,
options: optionsWithPercentage
};
});
},
setToken(token: string) {
this.globalData.token = token;
wx.setStorageSync("token", token); // 同步到缓存,持久化存储
},
// 提供清除 token 的方法(退出登录时使用)
clearToken() {
this.globalData.token = "";
wx.removeStorageSync("token");
},
setUserInfo(userInfo: WechatMiniprogram.CustomUserInfo){
this.globalData.userInfo = userInfo;
// 可选:持久化存储到缓存(根据需求决定是否需要)
wx.setStorageSync("userInfo", userInfo);
},
clearUserInfo(){
this.globalData.userInfo = null;
wx.removeStorageSync("userInfo")
}
})