import { APP_FAVO_ADD, APP_FAVO_REMOVE, APP_GAME_LAUNCH, APP_GAME_LIST, success } from "@scripts/api"; import { Http } from "@scripts/request"; import { IGameInfo, IGameLaunch, IGameListParams } from "./data"; import { CURRENCY_TYPE, CurrencyType, GAME_TABS, GameTabType } from "@scripts/define/Define"; const UPDATE_LIST_CD = 10 * 60 * 1000; interface IGameCaches { list: IGameInfo[], update_at: number, } class GameStore { private _gameListMap: { [key: string]: IGameCaches } = {}; private _allGameList: IGameCaches; private _currencyNow: CurrencyType; private _favoriting: boolean = false; public get favoriting() { return this._favoriting; } public gameID = 0; public gameLink = ""; clearGame() { this.gameID = 0; this.gameLink = ""; } private getAllGames() { return this._allGameList?.list || []; } async reqAllGames() { const params: IGameListParams = { currency: "", favorite: 0 } const res = await Http.call(APP_GAME_LIST, params as any); if (success(res)) { this._allGameList = { list: res.data, update_at: Date.now(), }; return true; } return false; } async reqGameList(currency: CurrencyType, cache = true) { this._currencyNow = currency; const gameCache = this._gameListMap[currency]; if (gameCache && cache) { if (Date.now() - gameCache.update_at < UPDATE_LIST_CD) { return true; } } const params: IGameListParams = { currency: currency, favorite: 0 } const res = await Http.call(APP_GAME_LIST, params as any); if (success(res)) { this._gameListMap[currency] = { list: res.data, update_at: Date.now(), }; return true; } return false; } async reqFavoAdd(id: number) { if (this._favoriting) return; this._favoriting = true; const res = await Http.call(APP_FAVO_ADD, { id }); this._favoriting = false; if (success(res)) { const gameList = this.getAllGames(); const game = gameList.find(g => g.gameID === id); if (game) { game.isFavorite = 1; return game; } } } async reqFavoRemove(id: number) { if (this._favoriting) return; this._favoriting = true; const res = await Http.call(APP_FAVO_REMOVE, { id }); this._favoriting = false; if (success(res)) { const gameList = this.getAllGames(); const game = gameList.find(g => g.gameID === id); if (game) { game.isFavorite = 0; return game; } } } filterGames(tag: GameTabType, currency: CurrencyType) { const allGames = this._allGameList?.list || []; let gameList = allGames; switch (tag) { case GAME_TABS.Hot: case GAME_TABS.New: gameList = allGames.filter(v => v.tags.find(t => t.tagCode === tag)); break; case GAME_TABS.Favs: gameList = allGames.filter(v => v.isFavorite === 1); break; } return gameList.filter(v => v.currencies.includes(currency)); } async reqLaunchGame(gameCode: string, currency: string) { const res = await Http.call(APP_GAME_LAUNCH, { gameCode, currency }); if (res && res.data && res.data.launchUrl) { return res.data.launchUrl; } return null; } } export const gameStore = new GameStore();