import { _decorator, BlockInputEvents, Component, easing, Label, Node, Slider, tween, UITransform, v3 } from 'cc';
import { GameDataManager } from '../../../Loading/scripts/manager/GameDataManager';
import { NodePoolManager } from '../../../Loading/scripts/manager/NodePoolManager';
import { AudioManager } from '../../../Loading/scripts/manager/AudioManager';
let { ccclass, property } = _decorator;

@ccclass('AutoSpinPanel')
export class AutoSpinPanel extends Component {

    @property(Slider)
    private autoSlider: Slider = null;

    @property(Label)
    private autoCountLabel: Label = null;

    @property(Node)
    private mainNode: Node = null;

    @property(Node)
    private barFill: Node = null;

    private countArr: number[] = [10, 20, 30, 50, 70, 100, 500, 1000];
    private isDragging: boolean = false;
    private curIndex: number = 0;

    private closeCallback: Function = null;

    protected onLoad(): void {
        this.updateSliderAndLabel(0);
        this.setCount(100);

        this.autoSlider.node.on('slide', this.onSliderChange, this);
    }

    showTween() {
        this.mainNode.active = false;
        this.mainNode.setScale(v3(0, 0, 0));
        this.node.getComponent(BlockInputEvents).enabled = true;
        this.mainNode.active = true;
        tween(this.mainNode)
            .to(0.3, { scale: v3(1, 1, 1) }, { easing: easing.backOut })
            .call(() => {
                this.node.getComponent(BlockInputEvents).enabled = false;
            })
            .start();
    }



    setCloseCallback(callback: Function) {
        this.closeCallback = callback;
    }

    onSliderChange() {
        this.isDragging = true;
        let progress = this.autoSlider.progress;

        // 计算最近的档位
        let totalSteps = this.countArr.length - 1;
        let targetIndex = Math.round(progress * totalSteps);
        // 立即更新滑动条位置到目标档位
        let targetProgress = targetIndex / totalSteps;
        this.autoSlider.progress = targetProgress;
        if (targetIndex !== this.curIndex) {
            this.curIndex = targetIndex;
            // 立即更新滑动条位置到目标档位
            let targetProgress = targetIndex / totalSteps;
            this.autoSlider.progress = targetProgress;
            this.updateBarFill(targetProgress);
            this.updateLabel(targetIndex);
        }
    }
    updateBarFill(progress: number) {
        if (this.barFill) {
            // 获取 UITransform 组件
            const transform = this.barFill.getComponent(UITransform);
            if (transform) {
                // 获取原始宽度（可以在 onLoad 中缓存）
                const maxWidth = this.autoSlider.node.getComponent(UITransform).width;
                // 更新填充条宽度
                transform.width = maxWidth * progress;
            }
        }
    }


    updateSliderAndLabel(index: number) {
        // 直接更新滑动条位置
        let totalSteps = this.countArr.length - 1;
        let progress = index / totalSteps;
        this.autoSlider.progress = progress;

        // 更新显示的值        
        this.updateBarFill(progress);
        this.updateLabel(index);
        this.curIndex = index;
    }

    updateLabel(index: number) {
        // 确保索引在有效范围内
        index = Math.min(Math.max(index, 0), this.countArr.length - 1);

        // 更新显示的值
        let value = this.countArr[index];
        if (this.autoCountLabel) {
            this.autoCountLabel.string = value.toString();
        }
    }

    onBtnStartAutoSpin() {
        GameDataManager.instance.autoCount = this.countArr[this.curIndex]
        if (this.closeCallback) {
            this.closeCallback();
        }
        
        this.close();
    }

    setCount(count: number) {
        let index = this.countArr.findIndex((v, i) => {
            if (i === this.countArr.length - 1) return true;
            return count <= v;
        });
        
        this.updateSliderAndLabel(index);
    }

    close() {
        AudioManager.instance.playSFX('Common_Button_Click');
        NodePoolManager.instance.putNodeToPool("AutoSpinPanel", this.node);
    }

    onDestroy() {
        // 清理事件监听
        this.autoSlider.node.off('slide', this.onSliderChange, this);
    }
}

