import { defineStore } from "pinia"; const defaultUser = { id: "", nickName: "游客", avatar: "../static/avatar.png", trio: 0, // 大于1表示完成了新手引导 lvlName: "砖石1级", }; const getLvlName = (score, rankList = []) => { let lvlName = ""; rankList.some((r, index) => { lvlName = rankList[index].name; if (r.upgrade_scores > score) { if (rankList[index - 1]) { lvlName = rankList[index - 1].name; } return true; } return false; }); return lvlName; }; const getLvlImage = (score, rankList = []) => { // 先保存到本地,分享只能用本地图片 let lvlImage = ""; rankList.some((r, index) => { lvlImage = rankList[index].icoin; if (r.upgrade_scores > score) { if (rankList[index - 1]) { lvlImage = rankList[index - 1].icoin; } return true; } return false; }); return lvlImage; }; // 定义游戏相关的 store export default defineStore("store", { // 状态 state: () => ({ user: defaultUser, device: { deviceId: "", deviceName: "", }, config: {}, rankData: { rank: [], ringRank: [], }, }), // 计算属性 getters: { getUsername: (state) => { return state.user.username; }, }, // 方法 actions: { getLvlName(score) { return getLvlName(score, this.config.randInfos); }, getLvlImage(score) { return getLvlImage(score, this.config.randInfos); }, updateRank(data = {}) { this.rankData = { rank: data.rank || [], ringRank: data.ringRank || [] }; }, async updateUser(user = {}) { this.user = { ...defaultUser, ...user }; if (user.avatar) { // 先保存到本地,分享只能用本地图片 const imageInfo = await uni.getImageInfo({ src: user.avatar }); this.user.avatar = imageInfo.path; } if (this.user.scores) { this.user.lvlName = getLvlName(this.user.scores, this.config.randInfos); const lvlImage = getLvlImage(this.user.scores, this.config.randInfos); if (lvlImage) { const imageInfo = await uni.getImageInfo({ src: lvlImage }); this.user.lvlImage = imageInfo.path; } } }, updateDevice(deviceId, deviceName) { this.device.deviceId = deviceId; this.device.deviceName = deviceName; }, async updateConfig(config) { this.config = config; if (this.user.scores) { this.user.lvlName = getLvlName(this.user.scores, this.config.randInfos); const lvlImage = getLvlImage(this.user.scores, this.config.randInfos); if (lvlImage) { const imageInfo = await uni.getImageInfo({ src: lvlImage }); this.user.lvlImage = imageInfo.path; } } }, }, // 开启数据持久化 persist: { enabled: true, strategies: [ { storage: uni.getStorageSync, paths: ["user", "device", "config"], // 只持久化用户信息 }, ], }, });