WeeklyPassView.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. import { _decorator, find, 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 VirtualList from '@scripts/components/virtualList/VirtualList';
  7. import { RewardItem } from './RewardItem';
  8. import { REWARD_OPEN_TYPE } from '../RewardView/RewardView';
  9. import { formatNumShort } from '@scripts/utils/Helper';
  10. const { ccclass, property } = _decorator;
  11. interface CDTask {
  12. targetTs: number;
  13. label: Label;
  14. format?: (timeStr: string) => string; // 改成接收已经格式化好的时间字符串,可选
  15. timerFunc: () => void;
  16. }
  17. @ccclass('WeeklyPassView')
  18. export class WeeklyPassView extends UIView {
  19. readonly viewId = UIViewID.WeeklyPassView;
  20. @property(Node)
  21. private btn_close: Node = null;
  22. @property(Node)
  23. private btn_claim_all: Node = null;
  24. @property(Node)
  25. private btn_grey: Node = null;
  26. @property(Node)
  27. private gifts: Node = null;
  28. @property(Node)
  29. private instant_rewards: Node = null;
  30. @property(Node)
  31. private total_rewards: Node = null;
  32. @property(Label)
  33. private countdown: Label = null;
  34. @property(Label)
  35. private valid: Label = null;
  36. @property(Label)
  37. private available: Label = null;
  38. @property(VirtualList)
  39. private scrollView: VirtualList;
  40. private _store: any = {};
  41. private _default_gift: number = -1;
  42. private _claiming: boolean = false;
  43. protected async onBeforeOpen(_params: unknown): Promise<boolean> {
  44. const res = await this._store.reqWeeklyPassInfo();
  45. return res;
  46. }
  47. protected onCreate(): void | Promise<void> {
  48. this._store = AppKernel.stores.weeklyPassStore;
  49. AppKernel.events.on('weeklyPass:update', this.updateView, this);
  50. addBtnClick(this.btn_close, this.onBtnCloseClick, this);
  51. addBtnClick(this.btn_claim_all, this.onBtnClaimAllClick, this);
  52. this.bindGiftsBtns();
  53. this.initView();
  54. }
  55. protected onOpen(_params: unknown): void | Promise<void> {
  56. const tiers = this._store.data?.tiers ?? [];
  57. const tier = tiers[this._default_gift] ?? {};
  58. const days = tier?.days ?? [];
  59. this.scrollView.numItems = days?.length ?? 0;
  60. }
  61. onRenderRewardItem(item: Node, index: number) {
  62. const tiers = this._store.data?.tiers ?? [];
  63. const tier = tiers[this._default_gift] ?? {};
  64. const days = tier?.days ?? [];
  65. const data = days[index];
  66. const rewardItem = item.getComponent(RewardItem);
  67. rewardItem.initItem(data);
  68. item.active = true;
  69. }
  70. // 弹窗销毁,清空池子释放资源
  71. protected onDestroy(): void {
  72. this.stopAllTimer();
  73. super.onDestroy();
  74. }
  75. private bindGiftsBtns() {
  76. this.gifts?.children?.forEach((item, index) => {
  77. if (!item) return;
  78. addBtnClick(item, () => this.onGiftsBtnClick(index), this);
  79. const btn_buy = item.getChildByName('btn_buy');
  80. if (!btn_buy) return;
  81. addBtnClick(btn_buy, () => this.onGiftsBuy(index), this);
  82. })
  83. }
  84. private initView() {
  85. }
  86. private updateView() {
  87. // 默认选择
  88. const tiers = this._store.data?.tiers ?? [];
  89. const isDefault = this._default_gift == -1;
  90. if (isDefault) {
  91. const index = tiers.findIndex((item: any) => item?.has_subscription);
  92. this._default_gift = index >= 0 ? index : 0;
  93. }
  94. this.updateGifts();
  95. this.updateRewards();
  96. if (this.scrollView.checkInited(false)) this.scrollView.updateAll();
  97. }
  98. private updateGifts() {
  99. const tiers = this._store.data?.tiers ?? [];
  100. this.gifts?.children?.forEach((item, index) => {
  101. const selected = item.getChildByName('selected');
  102. const active = find("text_cycle/active", item);
  103. const cycle = find("text_cycle/cycle", item);
  104. const not_active = find("text_cycle/not_active", item);
  105. const btn_buy = item.getChildByName('btn_buy');
  106. selected.active = index == this._default_gift;
  107. const isActive = tiers[index]?.has_subscription;
  108. active.active = isActive;
  109. cycle.active = isActive;
  110. not_active.active = !isActive;
  111. if (isActive) {
  112. const days = tiers[index]?.days ?? [];
  113. cycle.getComponent(Label).string = `${(days?.length / 7)?.toFixed(0)} CYCLE`;
  114. }
  115. const money = tiers[index]?.purchase_gear?.money ?? 0;
  116. btn_buy.getChildByName("label").getComponent(Label).string = `BUY $${money}`
  117. })
  118. }
  119. private updateRewards() {
  120. const tiers = this._store.data?.tiers ?? [];
  121. const tier = tiers[this._default_gift] ?? {};
  122. // instant rewards
  123. const instant_rewards_data = tier?.instant_reward ?? {};
  124. const instant_layout = find("bg/center", this.instant_rewards);
  125. instant_layout?.children?.forEach(item => item.active = false);
  126. for (const [key, val] of Object.entries(instant_rewards_data)) {
  127. const propKey = `prop_${key}`;
  128. const item = instant_layout.getChildByName(propKey);
  129. if (!item || val == 0) continue;
  130. item.active = true;
  131. const num = item.getChildByName('num');
  132. const label = num.getComponent(Label);
  133. if (key == "sc" || key == "gc") {
  134. // label.string = `${(Number(val) / 100).toFixed(2)}`;
  135. label.string = formatNumShort(String(val), 999);
  136. } else {
  137. // label.string = `${val}`;
  138. label.string = formatNumShort(String(val), 999, 1);
  139. }
  140. }
  141. // total rewards
  142. const total_rewards_data = tier?.seven_day_total ?? {};
  143. const total_layout = find("bg/center", this.total_rewards);
  144. total_layout?.children?.forEach(item => item.active = false);
  145. for (const [key, val] of Object.entries(total_rewards_data)) {
  146. const propKey = `prop_${key}`;
  147. const item = total_layout.getChildByName(propKey);
  148. if (!item || val == 0) continue;
  149. item.active = true;
  150. const num = item.getChildByName('num');
  151. const label = num.getComponent(Label);
  152. if (key == "sc" || key == "gc") {
  153. // label.string = `${(Number(val) / 100).toFixed(2)}`;
  154. label.string = formatNumShort(String(val), 999);
  155. } else {
  156. // label.string = `${val}`;
  157. label.string = formatNumShort(String(val), 999, 1);
  158. }
  159. }
  160. // countdown
  161. const targetTs = tier?.end_at * 1000;
  162. this.stopTimerByLabel(this.countdown);
  163. this.startTimer(targetTs, this.countdown);
  164. this.valid.node.active = tier?.end_at != 0;
  165. if (tier?.end_at) {
  166. const timeStr = this.formatToMonthDayTime(targetTs);
  167. this.valid.string = `VALID UNTIL ${timeStr}`;
  168. }
  169. // available
  170. const days = tier?.days ?? [];
  171. const avail_num = days.filter(item => item?.status == "claimable")?.length;
  172. this.available.string = `${avail_num} REWARDS AVAILABLE`;
  173. if (avail_num == 0) {
  174. this.btn_claim_all.active = false;
  175. this.btn_grey.active = true;
  176. } else {
  177. this.btn_claim_all.active = true;
  178. this.btn_grey.active = false;
  179. const label = this.btn_claim_all?.getChildByName("label");
  180. if (label) label.getComponent(Label).string = `CLAIM ALL x${avail_num}`;
  181. }
  182. }
  183. private onBtnCloseClick() {
  184. AppKernel.ui.close(this.viewId);
  185. }
  186. private async onBtnClaimAllClick() {
  187. if (this._claiming) return;
  188. this._claiming = true;
  189. AppKernel.ui.loading(true);
  190. const idx = this._default_gift;
  191. if (idx < 0) return;
  192. const tier_id = idx == 0 ? "gold" : idx == 1 ? "silver" : "iron";
  193. const payload = {
  194. claim_all: 1,
  195. tier_id
  196. }
  197. try {
  198. const res = await AppKernel.stores.weeklyPassStore.reqWeeklyPassClaim(payload) as any;
  199. if (res) AppKernel.ui.open(UIViewID.WeeklyPassClaim, { data: res });
  200. } finally {
  201. AppKernel.ui.loading(false);
  202. this._claiming = false;
  203. }
  204. // const data = {
  205. // "tier_id": "gold",
  206. // "claimed": [
  207. // {
  208. // "subscription_id": 1001,
  209. // "tier_id": "gold",
  210. // "day": 6,
  211. // "reward": {
  212. // "gc": 6000,
  213. // "sc": 6
  214. // }
  215. // },
  216. // {
  217. // "subscription_id": 1001,
  218. // "tier_id": "gold",
  219. // "day": 7,
  220. // "reward": {
  221. // "gc": 7000,
  222. // "sc": 7
  223. // }
  224. // },
  225. // {
  226. // "subscription_id": 1008,
  227. // "tier_id": "gold",
  228. // "day": 1,
  229. // "reward": {
  230. // "gc": 1000,
  231. // "sc": 1
  232. // }
  233. // }
  234. // ],
  235. // "granted": {
  236. // "gc": 14000,
  237. // "sc": 14
  238. // },
  239. // "tiers": [
  240. // {
  241. // "tier_id": "gold",
  242. // "display_name": "GOLD",
  243. // "has_subscription": true,
  244. // "subscription_status": "active",
  245. // "root_subscription_id": 1001,
  246. // "periods": [
  247. // {
  248. // "subscription_id": 1001,
  249. // "status": "expired",
  250. // "days": [
  251. // {
  252. // "day": 6,
  253. // "status": "claimed"
  254. // },
  255. // {
  256. // "day": 7,
  257. // "status": "claimed"
  258. // }
  259. // ]
  260. // },
  261. // {
  262. // "subscription_id": 1008,
  263. // "status": "active",
  264. // "is_renewal": true,
  265. // "days": [
  266. // {
  267. // "day": 1,
  268. // "status": "claimed"
  269. // }
  270. // ]
  271. // }
  272. // ]
  273. // },
  274. // {
  275. // "tier_id": "silver",
  276. // "has_subscription": false,
  277. // "subscription_status": "none"
  278. // },
  279. // {
  280. // "tier_id": "iron",
  281. // "has_subscription": false,
  282. // "subscription_status": "none"
  283. // }
  284. // ]
  285. // }
  286. // AppKernel.ui.open(UIViewID.WeeklyPassClaim, {
  287. // data
  288. // });
  289. }
  290. private onGiftsBtnClick(index: number) {
  291. this._default_gift = index;
  292. const tiers = this._store.data?.tiers ?? [];
  293. const tier = tiers[index] ?? {};
  294. const days = tier?.days ?? [];
  295. this.scrollView.numItems = days?.length ?? 0;
  296. this.updateView();
  297. }
  298. private onGiftsBuy(index: number) {
  299. const tiers = this._store.data?.tiers ?? [];
  300. const tier = tiers[index] ?? {};
  301. const gear = tier?.purchase_gear;
  302. if (!gear) return;
  303. AppKernel.ui.open(UIViewID.WeeklyPassPurchase, { tier, gear, index });
  304. // const message = {
  305. // "cmd": "pay_finish",
  306. // "data": {
  307. // "Golds": 26300,
  308. // "PayNum": 300,
  309. // "event": "pay",
  310. // "params": {
  311. // "regtime": 1790150093,
  312. // "isd0": false,
  313. // "first": 0,
  314. // "golds": 30,
  315. // "udid": "0b5441baaf5426ddc107fd41cf23bba1",
  316. // "order_sn": "USDA1297603724682780008077"
  317. // }
  318. // }
  319. // }
  320. // AppKernel.ui.open(UIViewID.RewardView, {
  321. // reward: tier?.instant_reward,
  322. // type: index == 0 ? REWARD_OPEN_TYPE.COMMON : REWARD_OPEN_TYPE.INSTANT
  323. // });
  324. }
  325. private _cdTaskList: CDTask[] = [];
  326. /**
  327. * 开启倒计时
  328. * @param targetTs 结束时间戳(ms)
  329. * @param label 显示文字的Label
  330. * @param format 格式化回调,入参剩余秒数,返回要展示的字符串
  331. */
  332. private startTimer(targetTs: number, label: Label, format?: (timeStr: string) => string) {
  333. if (targetTs == null || isNaN(targetTs)) return;
  334. // 先查找这个label有没有正在跑的倒计时,存在就先停止旧的
  335. const existIdx = this._cdTaskList.findIndex(item => item.label === label);
  336. if (existIdx >= 0) {
  337. const oldTask = this._cdTaskList[existIdx];
  338. this.unschedule(oldTask.timerFunc);
  339. this._cdTaskList.splice(existIdx, 1);
  340. }
  341. // 计算当前剩余秒数
  342. const diff = targetTs - Date.now();
  343. const remainSec = Math.max(0, Math.ceil(diff / 1000));
  344. const timeStr = this.formatHMS(remainSec);
  345. // 有format就调用,没有直接用timeStr
  346. label.string = format ? format(timeStr) : timeStr;
  347. if (remainSec <= 0) {
  348. return;
  349. }
  350. // 新建任务
  351. const task: CDTask = {
  352. targetTs,
  353. label,
  354. format,
  355. timerFunc: () => this.onUpdateCDTask(task)
  356. };
  357. this._cdTaskList.push(task);
  358. this.onUpdateCDTask(task);
  359. this.schedule(task.timerFunc, 1);
  360. }
  361. private stopTimerByLabel(label: Label) {
  362. const idx = this._cdTaskList.findIndex(item => item.label === label);
  363. if (idx >= 0) {
  364. const task = this._cdTaskList[idx];
  365. this.unschedule(task.timerFunc);
  366. this._cdTaskList.splice(idx, 1);
  367. }
  368. }
  369. private stopAllTimer() {
  370. for (const task of this._cdTaskList) {
  371. this.unschedule(task.timerFunc);
  372. }
  373. this._cdTaskList.length = 0;
  374. }
  375. private onUpdateCDTask(task: CDTask) {
  376. const now = Date.now();
  377. const diff = task.targetTs - now;
  378. const remainSec = Math.max(0, Math.ceil(diff / 1000));
  379. const timeStr = this.formatHMS(remainSec);
  380. // 存在format回调就调用,没有直接使用时间字符串
  381. task.label.string = task.format ? task.format(timeStr) : timeStr;
  382. if (remainSec <= 0) {
  383. this.unschedule(task.timerFunc);
  384. const idx = this._cdTaskList.indexOf(task);
  385. if (idx > -1) {
  386. this._cdTaskList.splice(idx, 1);
  387. }
  388. }
  389. }
  390. private formatHMS(totalSec: number): string {
  391. const sec = Math.max(0, Math.floor(totalSec));
  392. const d = Math.floor(sec / (3600 * 24));
  393. const h = Math.floor((sec % (3600 * 24)) / 3600);
  394. const m = Math.floor((sec % 3600) / 60);
  395. const s = sec % 60;
  396. const pad = (n: number) => n.toString().padStart(2, '0');
  397. const hhmmss = `${pad(h)}:${pad(m)}:${pad(s)}`;
  398. if (d > 0) {
  399. return `${d}:${hhmmss}`;
  400. }
  401. return hhmmss;
  402. }
  403. /**
  404. * 格式化时间戳输出:SEPTEMBER 27, 17:47
  405. * @param ts 毫秒时间戳
  406. * @returns string
  407. */
  408. private formatToMonthDayTime(ts: number): string {
  409. const date = new Date(ts);
  410. // 英文月份全称
  411. const monthNames = [
  412. "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
  413. "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
  414. ];
  415. const month = monthNames[date.getMonth()];
  416. const day = date.getDate();
  417. const hh = String(date.getHours()).padStart(2, '0');
  418. const mm = String(date.getMinutes()).padStart(2, '0');
  419. return `${month} ${day}, ${hh}:${mm}`;
  420. }
  421. }