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

const { ccclass, property } = _decorator;

@ccclass('RankHistoryList')
export class RankHistoryList extends Component {
    // ==================== 历史排行榜 ====================
    rankHistoryList: Node = null;  // 历史排行榜节点
    rankHistoryLoadingNode: Node = null;  // 历史记录加载节点

    // 历史排行榜 - 翻页按钮
    rightBtn: Node = null;  // 右箭头按钮（下一期）
    leftBtn: Node = null;  // 左箭头按钮（上一期）

    closeBtn: Node = null;  // 关闭按钮

    rankingHistoryListVScroll: VirtualScrollView = null; // 历史排行榜虚拟列表
    selfInfo: Node = null; // 自己的信息节点

    // 历史排行榜 - 日周月切换
    rankHistoryRadioDWM: Node = null;  // 历史记录日周月单选按钮父节点
    rankHistoryRadioDayBtn: Node = null;  // 历史记录日榜单选按钮
    rankHistoryRadioWeekBtn: Node = null;  // 历史记录周榜单选按钮
    rankHistoryRadioMonthBtn: Node = null;  // 历史记录月榜单选按钮

    // 活动未开启提示
    activityNotOpenTip: Node = null; // 活动未开启提示 label

    currentHistoryType: string = '';
    historyIndex: number = 1; // 历史记录索引，1表示上一期，最大为10
    maxHistoryIndex: number = 10; // 最大历史记录数
    availableTypes: Set<string> = new Set(); // 可用的类型

    // 回调函数
    onBack: () => void = null;  // 返回到主列表

    init(rankHistoryListNode: Node) {
        this.rankHistoryList = rankHistoryListNode;

        let titleChange = this.rankHistoryList.getChildByName('titleChange');
        this.rightBtn = titleChange.getChildByName('rightBtn');
        this.leftBtn = titleChange.getChildByName('leftBtn');
        this.selfInfo = this.rankHistoryList.getChildByName('list').getChildByName('self');
        this.rankHistoryLoadingNode = this.rankHistoryList.getChildByName('list').getChildByName('loading');
        this.rankingHistoryListVScroll = this.rankHistoryList.getChildByName('list').getChildByName('vScroll').getComponent(VirtualScrollView);
        this.rankHistoryRadioDWM = this.rankHistoryList.getChildByName('rankHistoryRadioDWM');
        this.rankHistoryRadioDayBtn = this.rankHistoryRadioDWM.getChildByName('dayBtn');
        this.rankHistoryRadioWeekBtn = this.rankHistoryRadioDWM.getChildByName('weekBtn');
        this.rankHistoryRadioMonthBtn = this.rankHistoryRadioDWM.getChildByName('monthBtn');

        this.activityNotOpenTip = this.rankHistoryList.getChildByName('list').getChildByName('activityNotOpenTip');

        this.rankHistoryList.active = false;
        this.rankHistoryLoadingNode.active = false;
        this.activityNotOpenTip.active = false;
        this.closeBtn = this.rankHistoryList.getChildByName('closeHistory');

        this.rightBtn.on(Node.EventType.TOUCH_END, this.onClickRightBtn, this);
        this.leftBtn.on(Node.EventType.TOUCH_END, this.onClickLeftBtn, this);
        this.closeBtn.on(Node.EventType.TOUCH_END, this.closeRankHistoryPopup, this);

        this.rankHistoryRadioDayBtn.on(Node.EventType.TOUCH_END, this.onClickRankHistoryRadioDayBtn, this);
        this.rankHistoryRadioWeekBtn.on(Node.EventType.TOUCH_END, this.onClickRankHistoryRadioWeekBtn, this);
        this.rankHistoryRadioMonthBtn.on(Node.EventType.TOUCH_END, this.onClickRankHistoryRadioMonthBtn, this);
    }

    // ==================== 对外接口 ====================
    async show(type: string) {
        this.rankHistoryList.active = true;

        this.updateAvailableTypes();

        this.currentHistoryType = type;

        this.historyIndex = 1;

        this.updateHistoryArrows();
        this.refreshSelfRankingInfo(null);
        await this.loadHistoryData(this.currentHistoryType, this.historyIndex);
    }

    updateAvailableTypes() {
        let rankList = SlotRankingDataManager.instance.rankList;
        this.availableTypes.clear();
        if (rankList && rankList.List) {
            for (let item of rankList.List) {
                this.availableTypes.add(item.Type);
            }
        }
    }

    isTypeAvailable(type: string): boolean {
        return this.availableTypes.has(type);
    }

    showActivityNotOpenTip() {
        this.activityNotOpenTip.active = true;
        this.rankingHistoryListVScroll.setTotalCount(0);
    }

    hideActivityNotOpenTip() {
        this.activityNotOpenTip.active = false;
    }

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

    // ==================== 历史记录逻辑 ====================
    async loadHistoryData(type: string, index: number) {
        this.setRankHistoryRadioBtn(type);
        this.refreshSelfRankingInfo(null);
        if (!this.isTypeAvailable(type)) {
            console.log(`${type} 历史榜单活动未开启`);
            this.rankHistoryLoadingNode.active = false;
            this.showActivityNotOpenTip();
            return;
        }

        this.hideActivityNotOpenTip();

        this.rankingHistoryListVScroll.setTotalCount(0);

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

        let historyDate = this.getHistoryDate(type, index);

        let data = {
            Type: type,
            GameId: getGameId(),
            Date: historyDate,
        }

        try {
            let rankInfos = await callGameApiForRank('getRankInfos', data);

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

            this.openRankHistoryPopup(rankInfos);
            this.refreshSelfRankingInfo(rankInfos.Self);
        } catch (error) {
            console.error('获取历史排行榜数据失败:', error);

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

    refreshSelfRankingInfo(selfInfo: any) {
        if (!selfInfo) {
            this.selfInfo.getChildByName('Rank').getChildByName('sp_1').active = false;
            this.selfInfo.getChildByName('Rank').getChildByName('sp_2').active = false;
            this.selfInfo.getChildByName('Rank').getChildByName('sp_3').active = false;
            this.selfInfo.getChildByName('Rank').getChildByName('rankLab').active = true;
            this.selfInfo.getChildByName('Rank').getChildByName('rankLab').getComponent(Label).string = '-';
            this.selfInfo.getChildByName('Uid').getComponent(Label).string = '-';
            this.selfInfo.getChildByName('Shop').getComponent(Label).string = '-';
            this.selfInfo.getChildByName('Win').getComponent(Label).string = '-';
            return;
        }

        this.selfInfo.getChildByName('Rank').getChildByName('sp_1').active = selfInfo.Rank === 1;
        this.selfInfo.getChildByName('Rank').getChildByName('sp_2').active = selfInfo.Rank === 2;
        this.selfInfo.getChildByName('Rank').getChildByName('sp_3').active = selfInfo.Rank === 3;
        this.selfInfo.getChildByName('Rank').getChildByName('rankLab').active = selfInfo.Rank >= 4;
        this.selfInfo.getChildByName('Rank').getChildByName('rankLab').getComponent(Label).string = selfInfo.Rank.toString();
        if (selfInfo.Rank === -1) {
            this.selfInfo.getChildByName('Rank').getChildByName('rankLab').active = true;
            this.selfInfo.getChildByName('Rank').getChildByName('rankLab').getComponent(Label).string = '-';
        }
        this.selfInfo.getChildByName('Uid').getComponent(Label).string = truncateString(selfInfo.Uid);
        this.selfInfo.getChildByName('Shop').getComponent(Label).string = SlotRankingDataManager.instance.getRankListServerId() || '-';
        this.selfInfo.getChildByName('Win').getComponent(Label).string = selfInfo.Bet.toString();
    }

    getHistoryDate(type: string, index: number): string {
        let now = new Date();
        let date = new Date(now);

        if (type === 'day') {
            date.setDate(date.getDate() - index);
        } else if (type === 'week') {
            date.setDate(date.getDate() - index * 7);
        } else if (type === 'month') {
            date.setMonth(date.getMonth() - index);
        }

        let year = date.getFullYear();
        let month = (date.getMonth() + 1).toString();
        let day = date.getDate().toString();
        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;
        return `${year}${month}${day}`;
    }

    updateHistoryArrows() {
        this.rightBtn.active = this.historyIndex > 1;
        this.leftBtn.active = this.historyIndex < this.maxHistoryIndex;
    }

    openRankHistoryPopup(rankInfos: any) {
        this.rankingHistoryListVScroll.setTotalCount(rankInfos.List.length);
        this.rankingHistoryListVScroll.renderItemFn = (node: Node, idx: number) => {
            let itemData = rankInfos.List[idx];
            if (!itemData) {
                return;
            }
            node.getChildByName('bg').active = idx % 2 === 0;
            node.getChildByName('bg2').active = idx % 2 !== 0;
            node.getChildByName('Rank').getChildByName('sp_1').active = idx === 0;
            node.getChildByName('Rank').getChildByName('sp_2').active = idx === 1;
            node.getChildByName('Rank').getChildByName('sp_3').active = idx === 2;
            node.getChildByName('Rank').getChildByName('rankLab').active = idx >= 3;
            node.getChildByName('Rank').getChildByName('rankLab').getComponent(Label).string = (idx + 1).toString();
            node.getChildByName('Uid').getComponent(Label).string = truncateString(itemData.Uid);
            node.getChildByName('Shop').getComponent(Label).string = SlotRankingDataManager.instance.getRankListServerId() || '-';
            node.getChildByName('Win').getComponent(Label).string = itemData.Bet.toString();
        }

        this.rankingHistoryListVScroll.refreshList(rankInfos.List);
    }

    // ==================== 按钮状态管理 ====================
    setRankHistoryRadioBtn(type: string) {
        let selectedColor = new Color(219, 180, 180, 255);
        let unselectedColor = new Color(197, 255, 175, 255);

        this.setRadioBtnState(this.rankHistoryRadioDayBtn, type === 'day', selectedColor, unselectedColor);
        this.setRadioBtnState(this.rankHistoryRadioWeekBtn, type === 'week', selectedColor, unselectedColor);
        this.setRadioBtnState(this.rankHistoryRadioMonthBtn, type === 'month', selectedColor, unselectedColor);
    }

    setRadioBtnState(btn: Node, isSelected: boolean, selectedColor: Color, unselectedColor: Color) {
        let check = btn.getChildByName('check');
        let unCheck = btn.getChildByName('unCheck');
        let label = btn.getChildByName('label');
        let palette = label?.getComponent(Palette);

        if (isSelected) {
            check.active = true;
            unCheck.active = false;
            if (palette) {
                palette.colorLB = selectedColor;
                palette.colorRB = selectedColor;
            }
        } else {
            check.active = false;
            unCheck.active = true;
            if (palette) {
                palette.colorLB = unselectedColor;
                palette.colorRB = unselectedColor;
            }
        }
    }

    // ==================== 按钮事件 ====================
    async onClickLeftBtn() {
        AudioManager.instance.playSFX("Common_Button_Click");
        if (this.historyIndex >= this.maxHistoryIndex) {
            return;
        }

        this.historyIndex++;
        this.updateHistoryArrows();
        await this.loadHistoryData(this.currentHistoryType, this.historyIndex);
    }

    async onClickRightBtn() {
        AudioManager.instance.playSFX("Common_Button_Click");
        if (this.historyIndex <= 1) {
            return;
        }

        this.historyIndex--;
        this.updateHistoryArrows();
        await this.loadHistoryData(this.currentHistoryType, this.historyIndex);
    }

    async onClickRankHistoryRadioDayBtn() {
        AudioManager.instance.playSFX("Common_Button_Click");
        if (this.currentHistoryType === 'day') {
            return;
        }
        this.currentHistoryType = 'day';
        this.historyIndex = 1;
        this.updateHistoryArrows();
        await this.loadHistoryData('day', this.historyIndex);
    }

    async onClickRankHistoryRadioWeekBtn() {
        AudioManager.instance.playSFX("Common_Button_Click");
        if (this.currentHistoryType === 'week') {
            return;
        }
        this.currentHistoryType = 'week';
        this.historyIndex = 1;
        this.updateHistoryArrows();
        await this.loadHistoryData('week', this.historyIndex);
    }

    async onClickRankHistoryRadioMonthBtn() {
        AudioManager.instance.playSFX("Common_Button_Click");
        if (this.currentHistoryType === 'month') {
            return;
        }
        this.currentHistoryType = 'month';
        this.historyIndex = 1;
        this.updateHistoryArrows();
        await this.loadHistoryData('month', this.historyIndex);
    }

    closeRankHistoryPopup() {
        AudioManager.instance.playSFX("Common_Button_Click");
        this.onBack?.call(null);
    }

    onDestroy() {
        this.rightBtn.off(Node.EventType.TOUCH_END, this.onClickRightBtn, this);
        this.leftBtn.off(Node.EventType.TOUCH_END, this.onClickLeftBtn, this);
        this.rankHistoryRadioDayBtn.off(Node.EventType.TOUCH_END, this.onClickRankHistoryRadioDayBtn, this);
        this.rankHistoryRadioWeekBtn.off(Node.EventType.TOUCH_END, this.onClickRankHistoryRadioWeekBtn, this);
        this.rankHistoryRadioMonthBtn.off(Node.EventType.TOUCH_END, this.onClickRankHistoryRadioMonthBtn, this);
        this.closeBtn.off(Node.EventType.TOUCH_END, this.closeRankHistoryPopup, this);
    }
}
