import { _decorator, Component, Node, Label, UITransform, tween, Vec3, director, ProgressBar, SpriteAtlas, error } from 'cc';
import { ResourceLoader } from './ResourceLoader';
import { sp, SpriteFrame, AudioClip, Font } from 'cc';
import { GameConstant } from './GameConstant';
import { Player } from './Player';

const { ccclass, property } = _decorator;

@ccclass('LoadingScene')
export class LoadingScene extends Component {
    @property(Node)
    progressBar!: Node;

    @property(Label)
    progressLabel!: Label;

    @property(Label)
    tipsLabel!: Label;

    private httpRetryCount: number = 0;
    private maxRetries: number = 3;
    private hasHttpResponse: boolean = false;

    start() {
        this.initLoader();
        this.startLoading();
    }

    initLoader() {
        const loader = ResourceLoader.instance;
        loader.addGroup("spine", sp.SkeletonData, 0.4);
        loader.addGroup("png", SpriteAtlas, 0.2);
        loader.addGroup("audio", AudioClip, 0.3);
        loader.addGroup("font", Font, 0.1);
    }

    startLoading() {
        const loader = ResourceLoader.instance;

        loader.loadAll(
            (percent) => {
                // 进度卡在 99%，等待 HTTP 回包
                const cappedPercent = Math.min(percent, 99);
                this.updateProgress(cappedPercent);
            },
            () => {
                this.tipsLabel.string = "加载完成，正在获取游戏信息...";
                this.sendHttpRequest();
            }
        );
    }

    /**
     * 发送游戏信息请求，失败会重试三次
     */
    private sendHttpRequest() {
        const url = GameConstant.HTTP_HOST + "game-api/" + GameConstant.GAMEID + "/v2/gameinfo";
        console.log("请求游戏信息:", url);

        GameConstant.httpRequest("GET", url)
            .then((res: any) => {
                console.log("HTTP 回包成功:", res);
                this.hasHttpResponse = true;
                this.updateProgress(100);

                const player = Player.getInstance();
                player.init({
                    playerId: 1,
                    nickname: "GUEST",
                    score: res.dt.bl,
                    betConfig: res.dt.cs,
                    currencyType: res.dt.cc
                });
                
                this.tipsLabel.string = "游戏信息加载成功，正在进入游戏...";
                this.scheduleOnce(() => {
                    director.loadScene("GameScene");
                }, 0.8);
            })
            .catch((err: any) => {
                this.httpRetryCount++;
                console.error(`HTTP 请求失败 (第 ${this.httpRetryCount} 次):`, err);

                if (this.httpRetryCount < this.maxRetries) {
                    this.tipsLabel.string = `请求失败，正在重试 (${this.httpRetryCount}/${this.maxRetries})...`;
                    this.scheduleOnce(() => this.sendHttpRequest(), 0.5);
                } else {
                    this.tipsLabel.string = "获取游戏信息失败，请检查网络连接。";
                    // TODO: 弹出提示框，提示用户重试或退出游戏
                    console.error("三次重试失败，停止请求。");
                }
            });
    }

    private updateProgress(percent: number) {
        const progressBar = this.progressBar.parent!.getComponent(ProgressBar);
        if (progressBar) {
            progressBar.progress = percent / 100;
        }
        this.progressLabel.string = `${percent.toFixed(1)}%`;
    }
}
