SeasonPassView.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import { _decorator, instantiate, Label, Node, NodePool, Prefab, ProgressBar } from 'cc';
  2. import { UIView } from '@scripts/framework/ui/UIView';
  3. import { AppKernel } from '@scripts/app/AppKernel';
  4. import { UIViewID } from '@scripts/define/UIDefine';
  5. import { addBtnClick } from '@scripts/utils/UIHelper';
  6. import { RewardItem, RewardType } from './Tasks/RewardItem';
  7. import { NodeItem } from './Prize/NodeItem';
  8. import VirtualList from '@scripts/components/virtualList/VirtualList';
  9. const { ccclass, property } = _decorator;
  10. interface CDTask {
  11. targetTs: number;
  12. label: Label;
  13. format?: (timeStr: string) => string; // 改成接收已经格式化好的时间字符串,可选
  14. timerFunc: () => void;
  15. }
  16. @ccclass('SeasonPassView')
  17. export class SeasonPassView extends UIView {
  18. readonly viewId = UIViewID.SeasonPassView;
  19. @property(Node)
  20. private btn_close: Node = null;
  21. @property(Node)
  22. private btn_tasks: Node = null;
  23. @property(Node)
  24. private btn_prize: Node = null;
  25. @property(Node)
  26. private btn_buyPass: Node = null;
  27. @property(Node)
  28. private tasks: Node = null;
  29. @property(Node)
  30. private prize: Node = null;
  31. @property(Label)
  32. private season_end: Label = null;
  33. @property(Label)
  34. private tasks_daily_done: Label = null;
  35. @property(Label)
  36. private tasks_daily_reset: Label = null;
  37. @property(Node)
  38. private tasks_daily_content: Node = null;
  39. @property(Label)
  40. private tasks_seasonal_done: Label = null;
  41. @property(Label)
  42. private tasks_seasonal_reset: Label = null;
  43. @property(Node)
  44. private tasks_seasonal_content: Node = null;
  45. @property(Prefab)
  46. private tasks_reward_item: Prefab = null;
  47. @property(Node)
  48. private prize_fixed_dlx: Node = null;
  49. @property(Node)
  50. private redPoint_tasks: Node = null;
  51. @property(Node)
  52. private redPoint_prize: Node = null;
  53. @property(ProgressBar)
  54. private progressBar: ProgressBar = null;
  55. @property(Label)
  56. private progress_label: Label = null;
  57. @property(Label)
  58. private next_need_exp: Label = null;
  59. @property(VirtualList)
  60. private scrollView: VirtualList;
  61. private _store: any = {};
  62. private _dailyItemPool: NodePool = new NodePool();
  63. private _dailyUsedItems: Node[] = [];
  64. private _seasonalItemPool: NodePool = new NodePool();
  65. private _seasonalUsedItems: Node[] = [];
  66. protected async onBeforeOpen(_params: unknown): Promise<boolean> {
  67. const res = await this._store.reqSeasonPassInfo();
  68. return res;
  69. }
  70. protected onCreate(): void | Promise<void> {
  71. this._store = AppKernel.stores.seasonPassStore;
  72. AppKernel.events.on('seasonPass:update', this.updateSeasonPassView, this);
  73. AppKernel.events.on('checkIn:update', this.handleCheckInUpdate, this);
  74. addBtnClick(this.btn_close, this.onBtnCloseClick, this);
  75. addBtnClick(this.btn_tasks, this.onBtnTasksClick, this);
  76. addBtnClick(this.btn_prize, this.onBtnPrizeClick, this);
  77. addBtnClick(this.btn_buyPass, this.onBtnBuyPassClick, this);
  78. this.initView();
  79. }
  80. onRenderNodeItem(item: Node, index: number) {
  81. const { pass } = this._store.data ?? {};
  82. const { current_xp, is_deluxe } = pass ?? {};
  83. const list = pass?.nodes ?? [];
  84. const data = list[index];
  85. const nodeItem = item.getComponent(NodeItem);
  86. nodeItem.initItem({ node: data, current_xp, is_deluxe });
  87. item.active = true;
  88. }
  89. private handleCheckInUpdate() {
  90. this._store.reqSeasonPassInfo();
  91. }
  92. private updateSeasonPassView() {
  93. if (this.scrollView.checkInited(false)) this.scrollView.updateAll();
  94. this.updateTasks();
  95. this.updatePrize();
  96. this.updateRedPoint();
  97. this.updateProgress();
  98. }
  99. private updateTasks() {
  100. const { season_tasks } = this._store.data ?? {};
  101. this.updateDailyTasks();
  102. this.updateSeasonalTasks();
  103. const seasonal_targetTs = season_tasks?.end_at * 1000;
  104. this.startTimer(seasonal_targetTs, this.season_end);
  105. }
  106. private updateDailyTasks() {
  107. const { tasks, task_end_timestamp } = this._store.data ?? {};
  108. // 将当前正在使用的item全部回收进对象池
  109. for (const node of this._dailyUsedItems) {
  110. this._dailyItemPool.put(node);
  111. }
  112. this._dailyUsedItems.length = 0;
  113. for (const task of tasks ?? []) {
  114. let itemNode: Node;
  115. if (this._dailyItemPool.size() > 0) {
  116. itemNode = this._dailyItemPool.get();
  117. } else {
  118. itemNode = instantiate(this.tasks_reward_item);
  119. }
  120. itemNode.active = true;
  121. itemNode.parent = this.tasks_daily_content;
  122. const itemCmp = itemNode.getComponent(RewardItem);
  123. if (itemCmp) itemCmp.initItem(task, RewardType.Daily);
  124. this._dailyUsedItems.push(itemNode);
  125. }
  126. const daily_done = tasks?.filter(task => task.status > 0)?.length ?? 0;
  127. this.tasks_daily_done.string = `${daily_done}/${tasks?.length ?? 0} DONE`;
  128. const daily_targetTs = task_end_timestamp * 1000;
  129. this.startTimer(daily_targetTs, this.tasks_daily_reset, (cd) => "RESET IN " + cd);
  130. }
  131. private updateSeasonalTasks() {
  132. const { season_tasks } = this._store.data ?? {};
  133. for (const node of this._seasonalUsedItems) {
  134. this._seasonalItemPool.put(node);
  135. }
  136. this._seasonalUsedItems.length = 0;
  137. for (const task of season_tasks?.tasks ?? []) {
  138. let itemNode: Node;
  139. if (this._seasonalItemPool.size() > 0) {
  140. itemNode = this._seasonalItemPool.get();
  141. } else {
  142. itemNode = instantiate(this.tasks_reward_item);
  143. }
  144. itemNode.active = true;
  145. itemNode.parent = this.tasks_seasonal_content;
  146. const itemCmp = itemNode.getComponent(RewardItem);
  147. if (itemCmp) itemCmp.initItem(task, RewardType.Seasonal);
  148. this._seasonalUsedItems.push(itemNode);
  149. }
  150. const seasonal_done = season_tasks?.tasks.filter(task => task.status > 0)?.length ?? 0;
  151. this.tasks_seasonal_done.string = `${seasonal_done}/${season_tasks?.tasks.length ?? 0} DONE`;
  152. const seasonal_targetTs = season_tasks?.end_at * 1000;
  153. this.startTimer(seasonal_targetTs, this.tasks_seasonal_reset, (cd) => "RESET IN " + cd);
  154. }
  155. private updatePrize() {
  156. const { pass } = this._store.data ?? {};
  157. const { current_xp, is_deluxe } = pass ?? {};
  158. const activeLabel = this.prize_fixed_dlx.getChildByName('label');
  159. const btn_unlock = this.prize_fixed_dlx.getChildByName('btn_unlock');
  160. const lock = this.prize_fixed_dlx.getChildByName('lock');
  161. activeLabel.active = is_deluxe;
  162. btn_unlock.active = !is_deluxe;
  163. lock.active = !is_deluxe;
  164. }
  165. private updateRedPoint() {
  166. const { tasks, season_tasks, pass } = this._store.data ?? {};
  167. const hasTaskReward = tasks?.some(task => task.status === 1) ?? false;
  168. const hasSeasonalReward = season_tasks?.tasks.some(task => task.status === 1) ?? false;
  169. const { is_deluxe, nodes } = pass ?? {};
  170. const hasFreePrizeReward = nodes?.some(node => {
  171. const unlocked = node.unlocked === 1;
  172. const canClaim = node.free.claimed === 0;
  173. const hasReward = Object.values(node.free.reward)?.some(reward => reward != 0);
  174. return unlocked && canClaim && hasReward;
  175. });
  176. const hasDeluxePrizeReward = nodes?.some(node => {
  177. const unlocked = node.unlocked === 1;
  178. const canClaim = node.deluxe.claimed === 0;
  179. const hasReward = Object.values(node.deluxe.reward)?.some(reward => reward != 0);
  180. return unlocked && canClaim && hasReward && is_deluxe;
  181. })
  182. console.log("hasTaskReward", hasTaskReward, "hasSeasonalReward", hasSeasonalReward, "hasFreePrizeReward", hasFreePrizeReward, "hasDeluxePrizeReward", hasDeluxePrizeReward);
  183. this.redPoint_tasks.active = hasTaskReward || hasSeasonalReward;
  184. this.redPoint_prize.active = hasFreePrizeReward || hasDeluxePrizeReward;
  185. }
  186. private updateProgress() {
  187. const { pass } = this._store.data ?? {};
  188. const { current_xp, nodes } = pass ?? {};
  189. const next_need_exp = nodes?.find(node => node.required_xp > current_xp)?.required_xp;
  190. if (!next_need_exp) {
  191. this.progress_label.string = 'MAX';
  192. this.progressBar.progress = 1;
  193. this.next_need_exp.string = 'MAX LEVEL';
  194. } else {
  195. this.progress_label.string = `${current_xp}/${next_need_exp ?? 0} XP`;
  196. this.progressBar.progress = current_xp / next_need_exp;
  197. this.next_need_exp.string = `${next_need_exp - current_xp} XP TO\nNEXT PRIZE`;
  198. }
  199. }
  200. // 弹窗关闭,回收节点
  201. protected async onAfterClose() {
  202. for (const node of this._dailyUsedItems) {
  203. this._dailyItemPool.put(node);
  204. }
  205. this._dailyUsedItems.length = 0;
  206. for (const node of this._seasonalUsedItems) {
  207. this._seasonalItemPool.put(node);
  208. }
  209. this._seasonalUsedItems.length = 0;
  210. }
  211. // 弹窗销毁,清空池子释放资源
  212. protected onDestroy(): void {
  213. this._dailyItemPool.clear();
  214. this._seasonalItemPool.clear();
  215. this.stopAllTimer();
  216. AppKernel.events.off('seasonPass:update', this.updateSeasonPassView, this);
  217. AppKernel.events.off('checkIn:update', this.handleCheckInUpdate, this);
  218. super.onDestroy();
  219. }
  220. private initView() {
  221. this.onToggleSidebar("tasks");
  222. }
  223. private onBtnCloseClick() {
  224. AppKernel.ui.close(this.viewId);
  225. }
  226. private onToggleSidebar(type: string) {
  227. const selected_tasks = this.btn_tasks.getChildByName('selected');
  228. const unselected_tasks = this.btn_tasks.getChildByName('unselected');
  229. const selected_prize = this.btn_prize.getChildByName('selected');
  230. const unselected_prize = this.btn_prize.getChildByName('unselected');
  231. selected_tasks.active = type === "tasks";
  232. unselected_tasks.active = type !== "tasks";
  233. selected_prize.active = type === "prize";
  234. unselected_prize.active = type !== "prize";
  235. this.tasks.active = type === "tasks";
  236. this.prize.active = type === "prize";
  237. }
  238. private onBtnTasksClick() {
  239. this.onToggleSidebar("tasks");
  240. }
  241. private onBtnPrizeClick() {
  242. this.onToggleSidebar("prize");
  243. const data = this._store.data ?? {};
  244. this.scrollView.numItems = data?.pass?.nodes?.length ?? 0;
  245. }
  246. private onBtnBuyPassClick() {
  247. const { pass } = this._store.data ?? {};
  248. const gear = pass?.purchase_gear;
  249. if (!gear) return;
  250. AppKernel.ui.open(UIViewID.SeasonPassPurchase, gear);
  251. }
  252. private _cdTaskList: CDTask[] = [];
  253. /**
  254. * 开启倒计时
  255. * @param targetTs 结束时间戳(ms)
  256. * @param label 显示文字的Label
  257. * @param format 格式化回调,入参剩余秒数,返回要展示的字符串
  258. */
  259. private startTimer(targetTs: number, label: Label, format?: (timeStr: string) => string) {
  260. if (targetTs == null || isNaN(targetTs)) return;
  261. // 先查找这个label有没有正在跑的倒计时,存在就先停止旧的
  262. const existIdx = this._cdTaskList.findIndex(item => item.label === label);
  263. if (existIdx >= 0) {
  264. const oldTask = this._cdTaskList[existIdx];
  265. this.unschedule(oldTask.timerFunc);
  266. this._cdTaskList.splice(existIdx, 1);
  267. }
  268. // 计算当前剩余秒数
  269. const diff = targetTs - Date.now();
  270. const remainSec = Math.max(0, Math.ceil(diff / 1000));
  271. const timeStr = this.formatHMS(remainSec);
  272. // 有format就调用,没有直接用timeStr
  273. label.string = format ? format(timeStr) : timeStr;
  274. if (remainSec <= 0) {
  275. return;
  276. }
  277. // 新建任务
  278. const task: CDTask = {
  279. targetTs,
  280. label,
  281. format,
  282. timerFunc: () => this.onUpdateCDTask(task)
  283. };
  284. this._cdTaskList.push(task);
  285. this.onUpdateCDTask(task);
  286. this.schedule(task.timerFunc, 1);
  287. }
  288. private stopTimerByLabel(label: Label) {
  289. const idx = this._cdTaskList.findIndex(item => item.label === label);
  290. if (idx >= 0) {
  291. const task = this._cdTaskList[idx];
  292. this.unschedule(task.timerFunc);
  293. this._cdTaskList.splice(idx, 1);
  294. }
  295. }
  296. private stopAllTimer() {
  297. for (const task of this._cdTaskList) {
  298. this.unschedule(task.timerFunc);
  299. }
  300. this._cdTaskList.length = 0;
  301. }
  302. private onUpdateCDTask(task: CDTask) {
  303. const now = Date.now();
  304. const diff = task.targetTs - now;
  305. const remainSec = Math.max(0, Math.ceil(diff / 1000));
  306. const timeStr = this.formatHMS(remainSec);
  307. // 存在format回调就调用,没有直接使用时间字符串
  308. task.label.string = task.format ? task.format(timeStr) : timeStr;
  309. if (remainSec <= 0) {
  310. this.unschedule(task.timerFunc);
  311. const idx = this._cdTaskList.indexOf(task);
  312. if (idx > -1) {
  313. this._cdTaskList.splice(idx, 1);
  314. }
  315. }
  316. }
  317. private formatHMS(totalSec: number): string {
  318. const sec = Math.max(0, Math.floor(totalSec));
  319. const d = Math.floor(sec / (3600 * 24));
  320. const h = Math.floor((sec % (3600 * 24)) / 3600);
  321. const m = Math.floor((sec % 3600) / 60);
  322. const s = sec % 60;
  323. const pad = (n: number) => n.toString().padStart(2, '0');
  324. const hhmmss = `${pad(h)}:${pad(m)}:${pad(s)}`;
  325. if (d > 0) {
  326. return `${d}:${hhmmss}`;
  327. }
  328. return hhmmss;
  329. }
  330. }