import { _decorator, Component, Label, math, Node } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 调用事例
 * this.combatLable.startCounting(data.total);
 */

//数字自增长
@ccclass('NumRaiseLable')
export class NumRaiseLable extends Label {
    // 动画持续时间（秒）
    @property({ tooltip: '数字增长动画持续时间（秒）' })
    private _duration: number = 0.5;
    @property
    public get duration(): number {
        return this._duration;
    }
    public set duration(value: number) {
        this._duration = math.clamp(value, 0.1, 5);
    }
    // 当前显示的数字
    private _currentValue: number = 0;
    // 目标数字
    private _targetValue: number = 0;
    // 是否正在播放动画
    private _isAnimating: boolean = false;
    // 每帧增量
    private _incrementPerFrame: number = 0;

    /**
     * 开始数字增长动画
     * @param targetValue 目标数值
     * @param duration 可选，动画持续时间（秒），默认使用组件设置的duration
     */
    public startCounting(targetValue: number, duration?: number) {
        if (this._isAnimating) {
            this.stopCounting();
        }
        //使用传入的duration或默认值
        const animDuration = duration ?? this._duration;
        this._targetValue = targetValue;
        this._currentValue = 0;
        this._isAnimating = true;
        //计算每帧增量（假设60FPS）
        this._incrementPerFrame = this._targetValue / (animDuration * 60);
        //取消之前的调度
        this.unschedule(this.updateNumber);
        //开始新的调度
        this.schedule(this.updateNumber, 1/60);
    }

    /**
     * 停止数字增长动画
     */
    public stopCounting() {
        this._isAnimating = false;
        this.unschedule(this.updateNumber);
        this._currentValue = this._targetValue;
        this.updateDisplay();
    }

    /**
     * 立即完成动画
     */
    public completeCounting() {
        this.stopCounting();
        this._currentValue = this._targetValue;
        this.updateDisplay();
    }

    /**
     * 每帧更新数字
     */
    private updateNumber() {
        if (!this._isAnimating) return;
        this._currentValue += this._incrementPerFrame;
        //确保不超过目标值
        if (this._currentValue >= this._targetValue) {
            this._currentValue = this._targetValue;
            this._isAnimating = false;
            this.unschedule(this.updateNumber);
        }
        this.updateDisplay();
    }

    /**
     * 更新显示文本
     */
    private updateDisplay() {
        this.string = Math.floor(this._currentValue).toString();
    }

    //组件销毁时清理
    public onDestroy() {
        this.unschedule(this.updateNumber);
    }
}


