import { _decorator, find, instantiate, Label, Node, NodePool, Prefab, ProgressBar } from 'cc'; import { UIView } from '@scripts/framework/ui/UIView'; import { AppKernel } from '@scripts/app/AppKernel'; import { UIViewID } from '@scripts/define/UIDefine'; import { addBtnClick } from '@scripts/utils/UIHelper'; import VirtualList from '@scripts/components/virtualList/VirtualList'; import { RewardItem } from './RewardItem'; import { REWARD_OPEN_TYPE } from '../RewardView/RewardView'; import { formatNumShort } from '@scripts/utils/Helper'; const { ccclass, property } = _decorator; interface CDTask { targetTs: number; label: Label; format?: (timeStr: string) => string; // 改成接收已经格式化好的时间字符串,可选 timerFunc: () => void; } @ccclass('WeeklyPassView') export class WeeklyPassView extends UIView { readonly viewId = UIViewID.WeeklyPassView; @property(Node) private btn_close: Node = null; @property(Node) private btn_claim_all: Node = null; @property(Node) private btn_grey: Node = null; @property(Node) private gifts: Node = null; @property(Node) private instant_rewards: Node = null; @property(Node) private total_rewards: Node = null; @property(Label) private countdown: Label = null; @property(Label) private valid: Label = null; @property(Label) private available: Label = null; @property(VirtualList) private scrollView: VirtualList; private _store: any = {}; private _default_gift: number = -1; private _claiming: boolean = false; protected async onBeforeOpen(_params: unknown): Promise { const res = await this._store.reqWeeklyPassInfo(); return res; } protected onCreate(): void | Promise { this._store = AppKernel.stores.weeklyPassStore; AppKernel.events.on('weeklyPass:update', this.updateView, this); addBtnClick(this.btn_close, this.onBtnCloseClick, this); addBtnClick(this.btn_claim_all, this.onBtnClaimAllClick, this); this.bindGiftsBtns(); this.initView(); } protected onOpen(_params: unknown): void | Promise { const tiers = this._store.data?.tiers ?? []; const tier = tiers[this._default_gift] ?? {}; const days = tier?.days ?? []; this.scrollView.numItems = days?.length ?? 0; } onRenderRewardItem(item: Node, index: number) { const tiers = this._store.data?.tiers ?? []; const tier = tiers[this._default_gift] ?? {}; const days = tier?.days ?? []; const data = days[index]; const rewardItem = item.getComponent(RewardItem); rewardItem.initItem(data); item.active = true; } // 弹窗销毁,清空池子释放资源 protected onDestroy(): void { this.stopAllTimer(); super.onDestroy(); } private bindGiftsBtns() { this.gifts?.children?.forEach((item, index) => { if (!item) return; addBtnClick(item, () => this.onGiftsBtnClick(index), this); const btn_buy = item.getChildByName('btn_buy'); if (!btn_buy) return; addBtnClick(btn_buy, () => this.onGiftsBuy(index), this); }) } private initView() { } private updateView() { // 默认选择 const tiers = this._store.data?.tiers ?? []; const isDefault = this._default_gift == -1; if (isDefault) { const index = tiers.findIndex((item: any) => item?.has_subscription); this._default_gift = index >= 0 ? index : 0; } this.updateGifts(); this.updateRewards(); if (this.scrollView.checkInited(false)) this.scrollView.updateAll(); } private updateGifts() { const tiers = this._store.data?.tiers ?? []; this.gifts?.children?.forEach((item, index) => { const selected = item.getChildByName('selected'); const active = find("text_cycle/active", item); const cycle = find("text_cycle/cycle", item); const not_active = find("text_cycle/not_active", item); const btn_buy = item.getChildByName('btn_buy'); selected.active = index == this._default_gift; const isActive = tiers[index]?.has_subscription; active.active = isActive; cycle.active = isActive; not_active.active = !isActive; if (isActive) { const days = tiers[index]?.days ?? []; cycle.getComponent(Label).string = `${(days?.length / 7)?.toFixed(0)} CYCLE`; } const money = tiers[index]?.purchase_gear?.money ?? 0; btn_buy.getChildByName("label").getComponent(Label).string = `BUY $${money}` }) } private updateRewards() { const tiers = this._store.data?.tiers ?? []; const tier = tiers[this._default_gift] ?? {}; // instant rewards const instant_rewards_data = tier?.instant_reward ?? {}; const instant_layout = find("bg/center", this.instant_rewards); instant_layout?.children?.forEach(item => item.active = false); for (const [key, val] of Object.entries(instant_rewards_data)) { const propKey = `prop_${key}`; const item = instant_layout.getChildByName(propKey); if (!item || val == 0) continue; item.active = true; const num = item.getChildByName('num'); const label = num.getComponent(Label); if (key == "sc" || key == "gc") { // label.string = `${(Number(val) / 100).toFixed(2)}`; label.string = formatNumShort(String(val), 999); } else { // label.string = `${val}`; label.string = formatNumShort(String(val), 999, 1); } } // total rewards const total_rewards_data = tier?.seven_day_total ?? {}; const total_layout = find("bg/center", this.total_rewards); total_layout?.children?.forEach(item => item.active = false); for (const [key, val] of Object.entries(total_rewards_data)) { const propKey = `prop_${key}`; const item = total_layout.getChildByName(propKey); if (!item || val == 0) continue; item.active = true; const num = item.getChildByName('num'); const label = num.getComponent(Label); if (key == "sc" || key == "gc") { // label.string = `${(Number(val) / 100).toFixed(2)}`; label.string = formatNumShort(String(val), 999); } else { // label.string = `${val}`; label.string = formatNumShort(String(val), 999, 1); } } // countdown const targetTs = tier?.end_at * 1000; this.stopTimerByLabel(this.countdown); this.startTimer(targetTs, this.countdown); this.valid.node.active = tier?.end_at != 0; if (tier?.end_at) { const timeStr = this.formatToMonthDayTime(targetTs); this.valid.string = `VALID UNTIL ${timeStr}`; } // available const days = tier?.days ?? []; const avail_num = days.filter(item => item?.status == "claimable")?.length; this.available.string = `${avail_num} REWARDS AVAILABLE`; if (avail_num == 0) { this.btn_claim_all.active = false; this.btn_grey.active = true; } else { this.btn_claim_all.active = true; this.btn_grey.active = false; const label = this.btn_claim_all?.getChildByName("label"); if (label) label.getComponent(Label).string = `CLAIM ALL x${avail_num}`; } } private onBtnCloseClick() { AppKernel.ui.close(this.viewId); } private async onBtnClaimAllClick() { if (this._claiming) return; this._claiming = true; AppKernel.ui.loading(true); const idx = this._default_gift; if (idx < 0) return; const tier_id = idx == 0 ? "gold" : idx == 1 ? "silver" : "iron"; const payload = { claim_all: 1, tier_id } try { const res = await AppKernel.stores.weeklyPassStore.reqWeeklyPassClaim(payload) as any; if (res) AppKernel.ui.open(UIViewID.WeeklyPassClaim, { data: res }); } finally { AppKernel.ui.loading(false); this._claiming = false; } // const data = { // "tier_id": "gold", // "claimed": [ // { // "subscription_id": 1001, // "tier_id": "gold", // "day": 6, // "reward": { // "gc": 6000, // "sc": 6 // } // }, // { // "subscription_id": 1001, // "tier_id": "gold", // "day": 7, // "reward": { // "gc": 7000, // "sc": 7 // } // }, // { // "subscription_id": 1008, // "tier_id": "gold", // "day": 1, // "reward": { // "gc": 1000, // "sc": 1 // } // } // ], // "granted": { // "gc": 14000, // "sc": 14 // }, // "tiers": [ // { // "tier_id": "gold", // "display_name": "GOLD", // "has_subscription": true, // "subscription_status": "active", // "root_subscription_id": 1001, // "periods": [ // { // "subscription_id": 1001, // "status": "expired", // "days": [ // { // "day": 6, // "status": "claimed" // }, // { // "day": 7, // "status": "claimed" // } // ] // }, // { // "subscription_id": 1008, // "status": "active", // "is_renewal": true, // "days": [ // { // "day": 1, // "status": "claimed" // } // ] // } // ] // }, // { // "tier_id": "silver", // "has_subscription": false, // "subscription_status": "none" // }, // { // "tier_id": "iron", // "has_subscription": false, // "subscription_status": "none" // } // ] // } // AppKernel.ui.open(UIViewID.WeeklyPassClaim, { // data // }); } private onGiftsBtnClick(index: number) { this._default_gift = index; const tiers = this._store.data?.tiers ?? []; const tier = tiers[index] ?? {}; const days = tier?.days ?? []; this.scrollView.numItems = days?.length ?? 0; this.updateView(); } private onGiftsBuy(index: number) { const tiers = this._store.data?.tiers ?? []; const tier = tiers[index] ?? {}; const gear = tier?.purchase_gear; if (!gear) return; AppKernel.ui.open(UIViewID.WeeklyPassPurchase, { tier, gear, index }); // const message = { // "cmd": "pay_finish", // "data": { // "Golds": 26300, // "PayNum": 300, // "event": "pay", // "params": { // "regtime": 1790150093, // "isd0": false, // "first": 0, // "golds": 30, // "udid": "0b5441baaf5426ddc107fd41cf23bba1", // "order_sn": "USDA1297603724682780008077" // } // } // } // AppKernel.ui.open(UIViewID.RewardView, { // reward: tier?.instant_reward, // type: index == 0 ? REWARD_OPEN_TYPE.COMMON : REWARD_OPEN_TYPE.INSTANT // }); } private _cdTaskList: CDTask[] = []; /** * 开启倒计时 * @param targetTs 结束时间戳(ms) * @param label 显示文字的Label * @param format 格式化回调,入参剩余秒数,返回要展示的字符串 */ private startTimer(targetTs: number, label: Label, format?: (timeStr: string) => string) { if (targetTs == null || isNaN(targetTs)) return; // 先查找这个label有没有正在跑的倒计时,存在就先停止旧的 const existIdx = this._cdTaskList.findIndex(item => item.label === label); if (existIdx >= 0) { const oldTask = this._cdTaskList[existIdx]; this.unschedule(oldTask.timerFunc); this._cdTaskList.splice(existIdx, 1); } // 计算当前剩余秒数 const diff = targetTs - Date.now(); const remainSec = Math.max(0, Math.ceil(diff / 1000)); const timeStr = this.formatHMS(remainSec); // 有format就调用,没有直接用timeStr label.string = format ? format(timeStr) : timeStr; if (remainSec <= 0) { return; } // 新建任务 const task: CDTask = { targetTs, label, format, timerFunc: () => this.onUpdateCDTask(task) }; this._cdTaskList.push(task); this.onUpdateCDTask(task); this.schedule(task.timerFunc, 1); } private stopTimerByLabel(label: Label) { const idx = this._cdTaskList.findIndex(item => item.label === label); if (idx >= 0) { const task = this._cdTaskList[idx]; this.unschedule(task.timerFunc); this._cdTaskList.splice(idx, 1); } } private stopAllTimer() { for (const task of this._cdTaskList) { this.unschedule(task.timerFunc); } this._cdTaskList.length = 0; } private onUpdateCDTask(task: CDTask) { const now = Date.now(); const diff = task.targetTs - now; const remainSec = Math.max(0, Math.ceil(diff / 1000)); const timeStr = this.formatHMS(remainSec); // 存在format回调就调用,没有直接使用时间字符串 task.label.string = task.format ? task.format(timeStr) : timeStr; if (remainSec <= 0) { this.unschedule(task.timerFunc); const idx = this._cdTaskList.indexOf(task); if (idx > -1) { this._cdTaskList.splice(idx, 1); } } } private formatHMS(totalSec: number): string { const sec = Math.max(0, Math.floor(totalSec)); const d = Math.floor(sec / (3600 * 24)); const h = Math.floor((sec % (3600 * 24)) / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; const pad = (n: number) => n.toString().padStart(2, '0'); const hhmmss = `${pad(h)}:${pad(m)}:${pad(s)}`; if (d > 0) { return `${d}:${hhmmss}`; } return hhmmss; } /** * 格式化时间戳输出:SEPTEMBER 27, 17:47 * @param ts 毫秒时间戳 * @returns string */ private formatToMonthDayTime(ts: number): string { const date = new Date(ts); // 英文月份全称 const monthNames = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ]; const month = monthNames[date.getMonth()]; const day = date.getDate(); const hh = String(date.getHours()).padStart(2, '0'); const mm = String(date.getMinutes()).padStart(2, '0'); return `${month} ${day}, ${hh}:${mm}`; } }