import { _decorator, Button, Component, Label, Node, Prefab, sp, Sprite, Tween, tween, UIOpacity, v3, Vec3 } from 'cc';
import { NodePoolManager } from '../../../Loading/scripts/manager/NodePoolManager';
import { gold2cash } from '../../../Loading/scripts/comm';
import { AudioManager } from '../../../Loading/scripts/manager/AudioManager';
const { ccclass, property } = _decorator;

@ccclass('TotalWin')
export class TotalWin extends Component {
    @property(Prefab)
    totalWinUiPre: Prefab = null;

    totalWinUINode: Node = null;
    freeSpinTimes: Label = null;
    totalWinNodeOpacity: UIOpacity | null = null;
    totalWinSpine: sp.Skeleton | null = null;
    totalWinSprite: Sprite | null = null;
    NumNodeOpacityCom: UIOpacity | null = null;
    scoreLabel: Label | null = null;        // 分数节点
    winScore: number = 0;                   // 最终赢分
    currentScore: number = 0;               // 当前赢分    
    scrollTime: number = 3.6;
    isScrolling: boolean = true;            // 分数是否在滚动

    // 添加一个标记来区分是否是点击跳过
    isSkipByTouch: boolean = false;

    btn: Button | null = null;

    closeCallBack: (() => void) | null = null;


    show(winScore: number, totalFreeTimes: number, closeCallBack: (() => void) | null = null) {
        this.totalWinUINode = NodePoolManager.instance.getNodeFromPoolStatic('totalWinUI', this.totalWinUiPre);
        this.totalWinSpine = this.totalWinUINode.getChildByName('spine').getComponent(sp.Skeleton);

        let titleNode = this.totalWinSpine.node.getChildByName('TitleNode');
        this.totalWinNodeOpacity = titleNode.getComponent(UIOpacity);
        this.totalWinNodeOpacity.opacity = 255;
        this.totalWinSprite = titleNode.getChildByName('TOTALWIN').getComponent(Sprite);
        this.freeSpinTimes = titleNode.getChildByPath('freeSpin/spinTime').getComponent(Label);
        this.freeSpinTimes.string = totalFreeTimes.toString()

        let numNode = this.totalWinSpine.node.getChildByName('NumNode');
        this.NumNodeOpacityCom = numNode.getComponent(UIOpacity);
        this.NumNodeOpacityCom.opacity = 255;
        this.scoreLabel = numNode.getChildByName('Label').getComponent(Label);
        Tween.stopAllByTarget(this.NumNodeOpacityCom.node);

        let btnNode = this.totalWinSpine.node.getChildByName('BtnNode');
        this.btn = btnNode.getChildByName('btnCollect').getComponent(Button);
        this.resetState()
        this.btn.node.on(Button.EventType.CLICK, this.onClose, this);

        this.winScore = winScore;
        // this.scoreLabel.string = gold2cash(winScore);
        this.startScoreAni()
        this.btn.node.active = false;
        this.node.addChild(this.totalWinUINode);
        this.playAnimation();
        AudioManager.instance.playSFX('Total_Settle_Sound');

        this.totalWinUINode.on(Node.EventType.TOUCH_START, this.onTouch, this);

        this.closeCallBack = closeCallBack;
    }

    resetState() {
        this.currentScore = 0;
        this.isScrolling = true;

        this.scoreLabel.node.scale = v3(1, 1, 1);
        Tween.stopAllByTarget(this.scoreLabel.node);
    }

    startScoreAni() {
        // 修改这里的滚动逻辑
        let startTime = 0;


        let updateScore = function (dt: number) {
            startTime += dt;
            let progress = Math.min(startTime / this.scrollTime, 1);

            let easedProgress = this.easeOutQuad(progress);
            this.currentScore = this.winScore * easedProgress;

            this.updateScoreLabel();

            if (progress >= 1) {
                this.updateScoreLabel();
                this.unschedule(updateScore);
                this.isScrolling = false
                this.btn.node.active = true
                AudioManager.instance.playSFX('Total_Settle_Sound_End');
            }
        }.bind(this);

        this.schedule(updateScore, 0.01);
    }

    // 添加缓动函数
    easeOutQuad(t: number): number {
        return t * (2 - t);
    }

    updateScoreLabel() {
        if (this.scoreLabel) this.scoreLabel.string = gold2cash(this.currentScore);
    }

    async onTouch() {
        if (!this.totalWinUINode) return;  // 添加节点存在检查
        if (this.isScrolling) {
            this.isSkipByTouch = true;

            // 立即完成当前动画
            this.isScrolling = false;
            this.unscheduleAllCallbacks();

            // 直接设置为最终分数
            this.currentScore = this.winScore;
            this.updateScoreLabel();
            AudioManager.instance.stopAllSFX()
            AudioManager.instance.playSFX('Total_Settle_Sound_End');
            this.btn.node.active = true
        }
    }

    playAnimation() {
        this.totalWinSpine.clearTracks();
        this.totalWinSpine.setAnimation(0, 'animation', true);
        this.totalWinSpine.node.getComponent(UIOpacity).opacity = 0

        tween(this.totalWinSpine.node.getComponent(UIOpacity))
            .to(0.5, { opacity: 255 })
            .call(() => {
                this.scheduleOnce(() => {
                    this.onClose();
                }, 6)
            })
            .start()
    }

    // 加入回调
    onClose() {
        this.btn.node.off(Button.EventType.CLICK, this.onClose, this);
        this.btn.node.active = false;
        this.unscheduleAllCallbacks();

        tween(this.totalWinSpine.node.getComponent(UIOpacity))
            .to(0.5, { opacity: 0 })
            .call(() => {
                this.totalWinUINode.off(Node.EventType.TOUCH_START, this.onTouch, this);
                this.totalWinUINode.removeFromParent();
                NodePoolManager.instance.putNodeToPool('totalWinUI', this.totalWinUINode);
                this.closeCallBack && this.closeCallBack();
            })
            .start()
    }
}


