import { _decorator, Component, Label, Node, Tween, tween } from 'cc';
import { VirtualScrollView } from './VScrollView';
import { callGameApiForRank } from 'db://assets/Loading/scripts/comm';
import { I18nManager } from 'db://assets/Loading/scripts/manager/I18nManager';
import { AudioManager } from 'db://assets/Loading/scripts/manager/AudioManager';

const { ccclass, property } = _decorator;

@ccclass('RewardHistoryList')
export class RewardHistoryList extends Component {
    rewardHistoryList: Node = null;  // 历史记录列表节点
    rewardHistoryLoadingNode: Node = null;  // 历史记录加载节点
    closeBtn: Node = null; // 关闭按钮
    rewardHistoryListVScroll: VirtualScrollView = null; // 历史记录列表虚拟列表

    historyData: any[] = [];

    // 回调函数
    onBack: () => void = null;

    init(rewardHistoryListNode: Node) {
        this.rewardHistoryList = rewardHistoryListNode;
        this.rewardHistoryLoadingNode = this.rewardHistoryList.getChildByName('list').getChildByName('loading');
        this.rewardHistoryListVScroll = this.rewardHistoryList.getChildByName('list').getChildByName('vScroll').getComponent(VirtualScrollView);
        this.closeBtn = this.rewardHistoryList.getChildByName('closeHistory');

        this.rewardHistoryList.active = false;
        this.rewardHistoryLoadingNode.active = false;

        this.closeBtn.on(Node.EventType.TOUCH_END, this.onClickCloseBtn, this);
    }

    // ==================== 对外接口 ====================
    async show() {
        this.rewardHistoryList.active = true;
        await this.loadHistoryData();
    }

    hide() {
        this.rewardHistoryList.active = false;
    }

    // ==================== 历史记录逻辑 ====================
    async loadHistoryData() {
        this.rewardHistoryListVScroll.setTotalCount(0);

        Tween.stopAllByTarget(this.rewardHistoryLoadingNode);
        this.rewardHistoryLoadingNode.active = true;
        tween(this.rewardHistoryLoadingNode)
            .by(0.3, { angle: 360 })
            .repeatForever()
            .start();

        try {
            let historyData = await callGameApiForRank('getRewardsHistory', {});

            Tween.stopAllByTarget(this.rewardHistoryLoadingNode);
            this.rewardHistoryLoadingNode.active = false;

            this.openHistoryPopup(historyData);
        } catch (error) {
            console.error('获取奖励历史记录失败:', error);

            Tween.stopAllByTarget(this.rewardHistoryLoadingNode);
            this.rewardHistoryLoadingNode.active = false;
        }
    }

    openHistoryPopup(historyData: any) {
        if (!historyData || !historyData.List || historyData.List.length === 0) {
            this.rewardHistoryListVScroll.setTotalCount(0);
            return;
        }

        this.historyData = historyData.List;
        this.rewardHistoryListVScroll.setTotalCount(this.historyData.length);
        this.rewardHistoryListVScroll.renderItemFn = (node: Node, idx: number) => {
            let itemData = this.historyData[idx];
            if (!itemData) {
                return;
            }

            let typeMap: { [key: string]: string } = {
                'day': I18nManager.instance.t('Daily Ranking'),
                'week': I18nManager.instance.t('Weekly Ranking'),
                'month': I18nManager.instance.t('Monthly Ranking')
            };
            let typeLabel = typeMap[itemData.Type] || itemData.Type;

            node.getChildByName('Activity').getComponent(Label).string = typeLabel;

            node.getChildByName('ActivityTime').getComponent(Label).string = itemData.Date;

            node.getChildByName('Rank').getChildByName('sp_1').active = itemData.Rank === 1;
            node.getChildByName('Rank').getChildByName('sp_2').active = itemData.Rank === 2;
            node.getChildByName('Rank').getChildByName('sp_3').active = itemData.Rank === 3;
            node.getChildByName('Rank').getChildByName('rankLab').active = itemData.Rank >= 4;
            node.getChildByName('Rank').getChildByName('rankLab').getComponent(Label).string = itemData.Rank.toString();

            node.getChildByName('Win').getComponent(Label).string = itemData.Rewards.toString();

            let received = node.getChildByName('HasReceived').getChildByName('received');
            let unReceived = node.getChildByName('HasReceived').getChildByName('unReceived');
            received.active = true;
            unReceived.active = false;
        }

        this.rewardHistoryListVScroll.refreshList(this.historyData);
    }

    // ==================== 按钮事件 ====================
    onClickCloseBtn() {
        AudioManager.instance.playSFX("Common_Button_Click");
        this.onBack?.call(null);
    }

    onDestroy() {
        if (this.closeBtn) {
            this.closeBtn.off(Node.EventType.TOUCH_END, this.onClickCloseBtn, this);
        }
    }
}
