feat: 首页更新

This commit is contained in:
2025-11-11 18:48:54 +08:00
parent 230191f181
commit b48cce06f4
43 changed files with 3186 additions and 1029 deletions

258
stores/gameStore.ts Normal file
View File

@@ -0,0 +1,258 @@
/**
* 游戏状态管理
* 使用 Zustand + AsyncStorage 持久化
*/
import { create } from 'zustand';
// import { useShallow } from 'zustand/react/shallow';
import storageManager, { STORAGE_KEYS } from '@/utils/storageManager';
import gameService from '@/services/gameService';
import appConfig from '@/utils/config';
import useTenantStore from '@/stores/tenantStore';
import useMsgStore from '@/stores/msgStore';
import { filter, map, concat, cloneDeep, groupBy } from 'lodash-es';
import { GameMainKeysEnum, defaultHomeGameTabMenus } from '@/constants/game';
// 状态
interface State {
appLoginPopType: number;
receiveAwardPopType: number;
appLoginPop: boolean;
menuSort: Record<string, any>[];
rebateGameSort: Record<string, any>[];
originalGames: Record<string, any>[];
blockchainGames: Record<string, any>[];
homeHotGames: Record<string, any>[];
gamesTry: Record<string, any>[];
gamesTryPlayIds: number[];
smallClassGames: Record<string, any>;
gameBigClass: Record<string, any>;
}
// 操作
interface Actions {
setHomePageData: (data: Record<string, any>) => void;
setOriginalGames: (data: Record<string, any>[]) => void;
setBlockchainGames: (data: Record<string, any>[]) => void;
setGamesTry: (data: Record<string, any>[]) => void;
setHomeHotGames: (data: Record<string, any>[]) => void;
setSmallClassGame: (data: Record<string, any>) => void;
setGameBigClass: (data: Record<string, any>) => void;
// requestHomePageData: (data?: Record<string, any>) => Promise<any>;
}
/**
* 租户状态 Store
*/
const useGameStore = create<State & Actions>()((set, get) => ({
// 初始状态
appLoginPopType: 0,
receiveAwardPopType: 0,
appLoginPop: false,
menuSort: [], // 游戏主菜单
rebateGameSort: [],
originalGames: [], // 原创游戏
blockchainGames: [], // 区块链游戏
homeHotGames: [], // 热门游戏
gamesTry: [], // 试玩游戏
gamesTryPlayIds: [], // 试玩游戏id列表
smallClassGames: {},
gameBigClass: {},
// 保存首页数据
setHomePageData: (data: any) => {
if (data) {
const { setNotices, setBanners } = useMsgStore.getState();
// 设置注册弹窗
const appLoginPopType = data.appLoginPopType || 0;
const receiveAwardPopType = data.receiveAwardPopType || 0;
const appLoginPop = data.appLoginPop || false;
// 菜单排序
const menuSort = filter(data.version_type, item => item.sort_v !== 0 && item.state == 1).sort((a, b) => {
return b.sort_v - a.sort_v;
});
console.log(menuSort, 'menuSort 1');
// version_shuffle
const rebateGameSort = data.version_shuffle || [];
// 所有游戏销售状态
// gameStore.setGameAllStates(res.data.gameState);
// 公告
setNotices(data.news?.data || []);
// 轮播图
setBanners(data.banners?.data || []);
set({ appLoginPopType, receiveAwardPopType, appLoginPop, menuSort, rebateGameSort });
// 原创游戏
get().setOriginalGames(data.originalGames);
// 区块链游戏
get().setBlockchainGames(data.hsGames);
// 试玩游戏
get().setGamesTry(data.gamesTry);
// 首页热门游戏
get().setHomeHotGames(data.homeHotGames?.[1] || []);
get().setSmallClassGame(data.homeHotGames);
// 三方游戏
get().setGameBigClass(data.thirdGames);
// 手动持久化
// storageManager.setItem(STORAGE_KEYS.TENANT_STORE, JSON.stringify({ tenantInfo: data }));
}
if (__DEV__) {
console.log('💾 Tenant info saved:', data);
}
},
setOriginalGames: (list: Record<string, any>[]) => {
const originalGames = map(list, (item: any) => ({
...item,
isOriginal: true,
})).sort((a: any, b: any) => a.hotVal - b.hotVal);
set({ originalGames });
},
setBlockchainGames: (list: Record<string, any>[]) => {
set({ blockchainGames: list || [] });
},
setGamesTry: (list: Record<string, any>[]) => {
set({ gamesTry: list || [] });
storageManager.session.setItem(STORAGE_KEYS.GAME_TRY, list);
const gamesTryPlayIds = concat(...map(list, item => map(item.subList, subItem => Number(subItem.play_id))));
set({ gamesTryPlayIds });
},
setHomeHotGames: (list: Record<string, any>[]) => {
set({ homeHotGames: list || [] });
},
setSmallClassGame: (data: Record<string, any>) => {
set({ smallClassGames: {
[GameMainKeysEnum.HOT_ELECTRONIC]: data?.[2] || [],
[GameMainKeysEnum.HOT_FISHING]: data?.[3] || [],
[GameMainKeysEnum.HOT_CHESS]: data?.[5] || [],
[GameMainKeysEnum.HOT_BLOCK_THIRD]: data?.[8] || [],
} });
},
setGameBigClass: (data: Record<string, any>) => {
const groupByType = cloneDeep(groupBy(data, item => item.big_type));
set({ gameBigClass: {
[GameMainKeysEnum.CHESS]: groupByType?.[1] || [],
[GameMainKeysEnum.ELECTRONIC]: groupByType?.[2] || [],
[GameMainKeysEnum.FISHING]: groupByType?.[3] || [],
[GameMainKeysEnum.LIVE]: groupByType?.[4] || [],
[GameMainKeysEnum.SPORTS]: groupByType?.[5] || [],
[GameMainKeysEnum.LOTTERY]: groupByType?.[7] || [],
[GameMainKeysEnum.BLOCK_THIRD]: groupByType?.[10] || [],
} });
},
}));
// 从 AsyncStorage 恢复状态的函数
export const restoreGameState = async () => {
try {
const stored = await storageManager.session.getItem(STORAGE_KEYS.TENANT_STORE);
if (stored) {
const state = JSON.parse(stored);
useGameStore.setState(state);
if (__DEV__) {
console.log('✅ Tenant state restored from storage');
}
}
} catch (error) {
console.error('Failed to restore tenant state:', error);
}
};
// 获取首页数据
export const requestHomePageData = async () => {
try {
const { tenantInfo } = useTenantStore.getState();
const params = {
tid: tenantInfo?.tid,
aseq: {
aseq: appConfig.app.aseqId,
},
version_type: {
version_type: 3, // 1 是棋牌, 2 是网赚 3, 是综合彩票
},
news: {
page_start: 1,
num_per_page: 999,
chan_con: 8,
state: 1,
message_id: '10,13', //10公告 13 跑马灯
sort_flag: 1,
vip_level: 0, //userInfo.value.cust_level || 0,
proxy: tenantInfo?.proxy,
apply: 8, // 1 棋牌2 网赚3 综合彩票3 老版彩票; (apply后端设置默认为1为可选参数)
language: 0, //Number(window.localStorage.getItem('languageNum') || '0'),
},
game_news: {
page_start: 1,
num_per_page: 9999,
state: 1,
message_id: 17,
sort_flag: 1,
tid: tenantInfo?.tid,
proxy: tenantInfo?.proxy,
chan_con: 0,
apply: 8,
ma_id: 10,
// vip_level: userInfo.value.cust_level || 0,
vip_level: 0,
type: 'MWEB',
language: 0,
},
banners: {
page_start: 1,
num_per_page: 999,
chan_con: 8,
state: 1,
message_id: 12,
sort_flag: 1,
tid: tenantInfo?.tid,
proxy: tenantInfo?.proxy,
apply: 8,
location: '1',
type: 'MWEB',
language: Number(window.localStorage.getItem('languageNum') || '0'),
},
homeHotGames: {
// cust_id: userInfo.value.cust_id || '0',
cust_id: '0',
},
proxyConfig: {
proxy: tenantInfo?.proxy,
},
hotGames: {
size: 12,
},
};
const { data } = await gameService.getHomePageData(params);
// ✅ 直接调用 setHomePageData action
useGameStore.getState().setHomePageData(data);
if (__DEV__) {
console.log('✅ Home-data info loaded:', data);
}
return Promise.resolve(data);
} catch (error) {
console.error('Failed to request home-data info:', error);
return Promise.reject(error);
}
};
export default useGameStore;

View File

@@ -29,8 +29,12 @@ export type { Theme, Language } from './settingsStore';
// Tenant Store
export {
default as useTenantStore,
useTenantInfo,
useTenantStates,
useTenantActions,
restoreTenantState,
} from './tenantStore';
// Game Store
export {
default as useGameStore,
restoreGameState,
} from './gameStore';

72
stores/msgStore.ts Normal file
View File

@@ -0,0 +1,72 @@
/**
* 消息状态管理
* 使用 Zustand + AsyncStorage 持久化
*/
import { create } from 'zustand';
import storageManager, { STORAGE_KEYS } from '@/utils/storageManager';
import { filter } from 'lodash-es';
// import { useShallow } from 'zustand/react/shallow';
// import { tenantService } from '@/services';
/**
* 状态
*/
interface State {
notices: Record<string, any>[];
homeBanner: Record<string, any>[];
mineBanner: Record<string, any>[];
}
/**
* 操作
*/
interface Actions {
setNotices: (list: Record<string, any>[]) => void;
setBanners: (list: Record<string, any>[]) => void;
}
/**
* 租户状态 Store
*/
const useMsgStore = create<State & Actions>()((set, get) => ({
// state
notices: [],
homeBanner: [],
mineBanner: [],
// actions
setNotices: (list: Record<string, any>[]) => {
set({ notices: list });
if (__DEV__) {
console.log('💾 notices saved:', list);
}
},
setBanners: (list: Record<string, any>[]) => {
const homeBanner = filter(list, (item) => item.content1 && item.content1.includes('1'));
const mineBanner = filter(list, (item) => item.content1 && item.content1.includes('2'));
set({ homeBanner, mineBanner });
if (__DEV__) {
console.log('💾 banners saved:', list);
}
},
}));
// 从 AsyncStorage 恢复状态的函数
export const restoreMsgState = async () => {
try {
const stored = storageManager.session.getItem(STORAGE_KEYS.MSG_STORE);
if (stored) {
useMsgStore.setState(stored);
if (__DEV__) {
console.log('✅ Msg state restored from storage');
}
}
} catch (error) {
console.error('Failed to restore msg state:', error);
}
};
export default useMsgStore;

View File

@@ -5,7 +5,7 @@
import { create } from 'zustand';
import { useShallow } from 'zustand/react/shallow';
import AsyncStorage from '@react-native-async-storage/async-storage';
import storageManager, { STORAGE_KEYS } from '@/utils/storageManager';
/**
* 主题类型
@@ -59,7 +59,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setTheme: (theme) => {
set({ theme });
// 手动持久化
AsyncStorage.setItem('settings-storage', JSON.stringify(get()));
storageManager.local.setItem(STORAGE_KEYS.SETTINGS_STORE, get());
if (__DEV__) {
console.log('🎨 Theme changed:', theme);
}
@@ -69,7 +69,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setLanguage: (language) => {
set({ language });
// 手动持久化
AsyncStorage.setItem('settings-storage', JSON.stringify(get()));
storageManager.local.setItem(STORAGE_KEYS.SETTINGS_STORE, get());
if (__DEV__) {
console.log('🌐 Language changed:', language);
}
@@ -79,7 +79,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setNotificationsEnabled: (enabled) => {
set({ notificationsEnabled: enabled });
// 手动持久化
AsyncStorage.setItem('settings-storage', JSON.stringify(get()));
storageManager.local.setItem(STORAGE_KEYS.SETTINGS_STORE, get());
if (__DEV__) {
console.log('🔔 Notifications:', enabled ? 'enabled' : 'disabled');
}
@@ -89,7 +89,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setSoundEnabled: (enabled) => {
set({ soundEnabled: enabled });
// 手动持久化
AsyncStorage.setItem('settings-storage', JSON.stringify(get()));
storageManager.local.setItem(STORAGE_KEYS.SETTINGS_STORE, get());
if (__DEV__) {
console.log('🔊 Sound:', enabled ? 'enabled' : 'disabled');
}
@@ -99,7 +99,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setHapticsEnabled: (enabled) => {
set({ hapticsEnabled: enabled });
// 手动持久化
AsyncStorage.setItem('settings-storage', JSON.stringify(get()));
storageManager.local.setItem(STORAGE_KEYS.SETTINGS_STORE, get());
if (__DEV__) {
console.log('📳 Haptics:', enabled ? 'enabled' : 'disabled');
}
@@ -109,7 +109,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
resetSettings: () => {
set(DEFAULT_SETTINGS);
// 手动持久化
AsyncStorage.setItem('settings-storage', JSON.stringify(DEFAULT_SETTINGS));
storageManager.local.setItem(STORAGE_KEYS.SETTINGS_STORE, get());
if (__DEV__) {
console.log('🔄 Settings reset to default');
}
@@ -119,7 +119,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
// 从 AsyncStorage 恢复状态的函数
export const restoreSettingsState = async () => {
try {
const stored = await AsyncStorage.getItem('settings-storage');
const stored = await storageManager.local.getItem(STORAGE_KEYS.SETTINGS_STORE);
if (stored) {
const state = JSON.parse(stored);
useSettingsStore.setState(state);

View File

@@ -4,41 +4,36 @@
*/
import { create } from 'zustand';
import { useShallow } from 'zustand/react/shallow';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { STORAGE_KEYS } from '@/utils/storage';
import { tenantService } from '@/services/tenantService';
import { useEffect } from 'react';
// import { useShallow } from 'zustand/react/shallow';
import storageManager, { STORAGE_KEYS } from '@/utils/storageManager';
import { tenantService } from '@/services';
/**
* 租户信息接口
*/
// export interface Tenant {
// id: string;
// username: string;
// email: string;
// avatar?: string;
// nickname?: string;
// phone?: string;
// createdAt?: string;
// }
/**
* 租户状态接口
*/
interface TenantState {
// 状态
tenantInfo: Record<string, any> | null;
// 操作
setTenantInfo: (data: Record<string, any>) => void;
requestTenantInfo: (data?: Record<string, any>) => Promise<any>;
export interface Tenant {
tid: number;
proxy: number;
create_time: string;
domain_addr: string
}
// 状态
interface State {
tenantInfo: Tenant | null;
}
// 操作
interface Actions {
setTenantInfo: (data: Record<string, any>) => void;
}
/**
* 租户状态 Store
*/
const useTenantStore = create<TenantState>()((set, get) => ({
const useTenantStore = create<State & Actions>()((set, get) => ({
// 初始状态
tenantInfo: null,
@@ -47,39 +42,19 @@ const useTenantStore = create<TenantState>()((set, get) => ({
setTenantInfo: (data: any) => {
set({ tenantInfo: data });
// 手动持久化
// AsyncStorage.setItem(STORAGE_KEYS.TENANT_STORE, JSON.stringify({ tenantInfo: data }));
storageManager.session.setItem(STORAGE_KEYS.TENANT_STORE, get());
storageManager.session.setItem(STORAGE_KEYS.TENANT_TID, data?.tid ?? '');
if (__DEV__) {
console.log('💾 Tenant info saved:', data);
}
},
// 获取租户信息(调用 API 并使用 setTenantInfo 保存)
requestTenantInfo: async () => {
try {
const params = {
domain_addr: 'https://51zhh5.notbug.org',
};
const { data } = await tenantService.getPlatformData(params);
// 调用 setTenantInfo 来保存数据,避免重复代码
get().setTenantInfo(data);
if (__DEV__) {
console.log('✅ Tenant info loaded:', data);
}
return Promise.resolve(data);
} catch (error) {
console.error('Failed to request tenant info:', error);
return Promise.reject(error);
}
},
}));
// 从 AsyncStorage 恢复状态的函数
export const restoreTenantState = async () => {
try {
const stored = await AsyncStorage.getItem(STORAGE_KEYS.TENANT_STORE);
const stored = storageManager.session.getItem(STORAGE_KEYS.TENANT_STORE);
if (stored) {
const state = JSON.parse(stored);
useTenantStore.setState(state);
@@ -99,24 +74,29 @@ export const restoreTenantState = async () => {
// 获取用户信息
export const useTenantInfo = () => useTenantStore((state) => state.tenantInfo);
// 租户数据是否加载完成
export const useTenantLoad = () => useTenantStore((state) => !!state.tenantInfo?.tid || !!state.tenantInfo?.create_time);
// 获取租户状态
export const useTenantStates = () =>
useTenantStore(
useShallow((state) => ({
tenantInfo: state.tenantInfo,
tenantLoad: !!state.tenantInfo?.tid || !!state.tenantInfo?.create_time,
}))
);
// 获取租户信息
export const requestTenantInfo = async (): Promise<Tenant> => {
try {
// 使用 getState() 而不是 hook
const { setTenantInfo } = useTenantStore.getState();
const params = {
domain_addr: 'https://51zhh5.notbug.org',
};
const { data } = await tenantService.getPlatformData(params);
// 获取租户操作方法
// 使用 useShallow 避免每次渲染都返回新对象
export const useTenantActions = () =>
useTenantStore(
useShallow((state) => ({
setTenantInfo: state.setTenantInfo,
requestTenantInfo: state.requestTenantInfo,
}))
);
setTenantInfo(data);
if (__DEV__) {
console.log('✅ Tenant info loaded:', data);
}
return Promise.resolve(data);
} catch (error) {
console.error('Failed to request tenant info:', error);
return Promise.reject(error);
}
};
export default useTenantStore;

View File

@@ -5,7 +5,7 @@
import { create } from 'zustand';
import { useShallow } from 'zustand/react/shallow';
import AsyncStorage from '@react-native-async-storage/async-storage';
import storageManager, { STORAGE_KEYS } from '@/utils/storageManager';
/**
* 用户信息接口
@@ -20,16 +20,15 @@ export interface User {
createdAt?: string;
}
/**
* 用户状态接口
*/
interface UserState {
// 状态
// 状态
interface State {
user: User | null;
isLoggedIn: boolean;
token: string | null;
}
// 操作
// 操作
interface Actions {
setUser: (user: User) => void;
setToken: (token: string) => void;
login: (user: User, token: string) => void;
@@ -40,7 +39,7 @@ interface UserState {
/**
* 用户状态 Store
*/
export const useUserStore = create<UserState>()((set, get) => ({
export const useUserStore = create<State & Actions>()((set, get) => ({
// 初始状态
user: null,
isLoggedIn: false,
@@ -51,7 +50,7 @@ export const useUserStore = create<UserState>()((set, get) => ({
const newState = { user, isLoggedIn: true };
set(newState);
// 手动持久化
AsyncStorage.setItem('user-storage', JSON.stringify(newState));
storageManager.session.setItem(STORAGE_KEYS.USER_STORE, newState);
},
// 设置 token
@@ -59,8 +58,7 @@ export const useUserStore = create<UserState>()((set, get) => ({
set({ token });
// 手动持久化 - 延迟执行以确保状态已更新
setTimeout(() => {
const state = get();
AsyncStorage.setItem('user-storage', JSON.stringify(state));
storageManager.session.setItem(STORAGE_KEYS.USER_STORE, get());
}, 0);
},
@@ -74,9 +72,9 @@ export const useUserStore = create<UserState>()((set, get) => ({
set(newState);
// 同时保存 token 到 AsyncStorage用于 API 请求)
AsyncStorage.setItem('auth_token', token);
storageManager.session.setItem('auth_token', token);
// 手动持久化整个状态
AsyncStorage.setItem('user-storage', JSON.stringify(newState));
storageManager.session.setItem(STORAGE_KEYS.USER_STORE, newState);
if (__DEV__) {
console.log('✅ User logged in:', user.username);
@@ -93,9 +91,9 @@ export const useUserStore = create<UserState>()((set, get) => ({
set(newState);
// 清除 AsyncStorage 中的 token
AsyncStorage.removeItem('auth_token');
storageManager.session.removeItem('auth_token');
// 清除持久化状态
AsyncStorage.removeItem('user-storage');
storageManager.session.removeItem('user-storage');
if (__DEV__) {
console.log('👋 User logged out');
@@ -109,7 +107,7 @@ export const useUserStore = create<UserState>()((set, get) => ({
const newUser = { ...currentUser, ...updates };
set({ user: newUser });
// 手动持久化
AsyncStorage.setItem('user-storage', JSON.stringify({ ...get(), user: newUser }));
storageManager.session.setItem(STORAGE_KEYS.USER_STORE, { ...get(), user: newUser });
if (__DEV__) {
console.log('📝 User updated:', updates);
@@ -121,7 +119,7 @@ export const useUserStore = create<UserState>()((set, get) => ({
// 从 AsyncStorage 恢复状态的函数
export const restoreUserState = async () => {
try {
const stored = await AsyncStorage.getItem('user-storage');
const stored = await storageManager.session.getItem(STORAGE_KEYS.USER_STORE);
if (stored) {
const state = JSON.parse(stored);
useUserStore.setState(state);