import { _decorator, Component, Node, ProgressBar, Label, Button, view, VideoPlayer, UITransform, AssetManager, tween, ResolutionPolicy, game, director, Director, sys, macro, JsonAsset } from 'cc';
import { callGameApi, getIsRB7, getLanguage, initReqAddr } from './comm';
import { GameDataManager } from './manager/GameDataManager';
import { ResManager } from './manager/ResManager';
import { AudioManager } from './manager/AudioManager';
import { NodePoolManager } from './manager/NodePoolManager';
import { I18nManager } from './manager/I18nManager';
import { LocalizedSprite } from './i18n/LocalizedSprite';
let { ccclass, property } = _decorator;

@ccclass('LoadingUI')
export class LoadingUI extends Component {
    //test
    @property(Node)
    BG: Node = null;

    @property(Node)
    LoadingUINode: Node = null;

    @property(ProgressBar)
    progressBar: ProgressBar = null;

    @property(Label)
    progressLabel: Label = null;

    @property(Label)
    loadingTipLabel: Label = null;

    @property(Label)
    retryTipLabel: Label = null;

    @property(Button)
    startBtn: Button = null;

    @property(Label)
    startBtnLabel: Label = null;

    @property(Node)
    GameNode: Node = null;

    @property(JsonAsset)
    languageJson: JsonAsset = null;

    private _networkComplete = false;
    private _retryCount = 0;
    private readonly MAX_RETRY = 5;
    private INITIAL_PROGRESS = 0.3;
    private _instanceGameNode = null;


    // 新增动画
    private maskUITransform: UITransform = null;
    private lightNode: Node = null;

    protected async onLoad() {
        // 初始显示状态
        this.initUI();
        this.LoadingUINode.active = false;
    }


    async start() {
        try {
            initReqAddr();
            this.LoadingUINode.getChildByName('Logo_RB7').active = getIsRB7();
            await I18nManager.instance.init(getLanguage(), this.languageJson);
            I18nManager.instance.updateSceneRenderers();

            this.LoadingUINode.active = true;
            // 更新进度条到 0.4
            this.updateProgress(0.4);

            AudioManager.instance.init();
            game.setFrameRate(61);
            // this.checkStartLoading();
            // 开始网络请求
            this.initNetwork();

        } catch (error) {
            console.error('Network initialization failed:', error);
            this.handleError(error);
        }

    }

    private initUI() {
        this.BG.active = true;
        this.startBtn.node.active = false;
        this.maskUITransform = this.LoadingUINode.getChildByName('mask').getComponent(UITransform);
        this.lightNode = this.LoadingUINode.getChildByName('light');
        this.updateProgress(this.INITIAL_PROGRESS);
    }


    private async initNetwork() {
        try {
            // 更新进度条到 0.6
            this.updateProgress(0.6);
            this.loadingTipLabel.string = `${I18nManager.instance.t('AID_LOADING')}`;
            this.retryTipLabel.string = '';
            let gameInfo = await callGameApi("gameinfo", {});
            if (!gameInfo) throw new Error('Get game info failed');
            GameDataManager.instance.gameInfo = gameInfo;

            // 更新进度条到 0.8
            this.updateProgress(0.8);

            this._networkComplete = true;

            // await GameDataManager.instance.preloadFrameTypeCache();
            // await GameDataManager.instance.preloadSymbolCache();
            this.checkStartLoading();
        } catch (error) {
            console.error('Network initialization failed:', error);
            this.handleError(error);
        }
    }

    private checkStartLoading() {
        if (this._networkComplete) {
            this.LoadingUINode.active = true;
            this.startLoadingGameBundle();
        }
    }

    private async startLoadingGameBundle() {
        try {
            // 显示加载UI
            this.loadingTipLabel.string = `${I18nManager.instance.t('AID_LOADING')}`;
            this.retryTipLabel.string = '';
            this.startBtn.node.active = false;

            // 从 0.8 开始加载
            let startProgress = 0.8;

            // 使用新的合并函数加载 Bundle 和预制体
            this._instanceGameNode = await ResManager.instance.loadPrefabFromBundle(
                'Game',
                'prefabs/SlotScene',
                (finished: number, total: number) => {
                    if (total <= 0) return;
                    let bundleProgress = finished / total;
                    // 将加载进度映射到 0.8-1 的范围
                    let mappedProgress = startProgress + (bundleProgress * (1 - startProgress));
                    this.updateProgress(mappedProgress);
                }
            );

            this.updateProgress(1);
            this.onLoadComplete();
        } catch (error) {
            console.error('Loading error:', error);
            this.handleError(error);
        }
    }


    private updateProgress(progress: number) {
        // 使用 tween 使进度条更新更平滑
        tween(this.progressBar)
            .to(0.2, { progress: progress }, {
                easing: 'smooth',
                onUpdate: (target: any, ratio: number) => {
                    this.progressLabel.string = `${Math.floor(target.progress * 100)}%`;
                    this.maskUITransform.width = target.progress * 494;
                    this.lightNode.setPosition(target.progress * 496 - 274, -519, 0);
                }
            })
            .start();
    }

    private onLoadComplete() {
        // 开始游戏
        // AudioManager.instance.playBGM('Normal_Mode_BGM');
        this.scheduleOnce(() => {
            this.loadingTipLabel.string = '';
            this.retryTipLabel.string = '';
            this.startBtn.node.active = true;
            this.startBtnLabel.string = I18nManager.instance.t('AID_GET_STARTED');
            this.progressBar.node.active = false;
            this.progressLabel.node.active = false;

            this.maskUITransform.node.active = false;
            this.lightNode.active = false;
        }, 0.3);
    }

    private handleError(error: Error) {
        this._retryCount++;
        this.loadingTipLabel.string = '';
        if (this._retryCount <= this.MAX_RETRY) {
            // 自动重试
            switch (this._retryCount) {
                case 1:
                    this.retryTipLabel.string = I18nManager.instance.t('AID_NETWORK_RETRY_1');
                    break
                case 2:
                    this.retryTipLabel.string = I18nManager.instance.t('AID_NETWORK_RETRY_2');
                    break
                case 3:
                    this.retryTipLabel.string = I18nManager.instance.t('AID_NETWORK_RETRY_3');
                    break
                case 4:
                    this.retryTipLabel.string = I18nManager.instance.t('AID_NETWORK_RETRY_4');
                    break
                case 5:
                    this.retryTipLabel.string = I18nManager.instance.t('AID_NETWORK_RETRY_5');
                    break

            }
            this.scheduleOnce(() => {
                if (!this._networkComplete) {
                    this.initNetwork();
                } else {
                    this.startLoadingGameBundle();
                }
            }, 2);
        } else {
            // 显示重试按钮
            this.loadingTipLabel.string = `${I18nManager.instance.t('AID_LOADING')}`;
            this.retryTipLabel.string = '';
            this.startBtn.node.active = true;
            this.progressBar.node.active = false;
            this.progressLabel.node.active = false;
            this.loadingTipLabel.node.active = false;

            this.maskUITransform.node.active = false;
            this.lightNode.active = false;

            this.startBtnLabel.string = I18nManager.instance.t('AID_ERROR_RETRY_BUTTON');
        }
    }

    onStartBtnClick() {
        if (this.startBtnLabel.string === I18nManager.instance.t('AID_ERROR_RETRY_BUTTON')) {
            // 重试逻辑
            this._retryCount = 0;
            this.startBtn.node.active = false;
            this.progressBar.node.active = true;
            this.progressLabel.node.active = true;


            this.maskUITransform.node.active = true;
            this.lightNode.active = true;

            if (!this._networkComplete) {
                this.initNetwork();
            } else {
                this.startLoadingGameBundle();
            }
        } else if (this.startBtnLabel.string === I18nManager.instance.t('AID_GET_STARTED')) {

            // 确保 GameNode 存在
            if (!this.GameNode) {
                throw new Error('GameNode is not set');
            }
            // 添加到场景
            this.GameNode.addChild(this._instanceGameNode);
            // 隐藏加载界面
            this.LoadingUINode.destroy();
        }
    }

    onDestroy() {
        this.unscheduleAllCallbacks();
        tween(this.progressBar).stop();
        AudioManager.instance.destroy();
        NodePoolManager.instance.clearAll();
    }



    // UNKNOWN = 0,        // 未知平台
    // WINDOWS = 1,        // Windows
    // LINUX = 2,          // Linux
    // MACOS = 3,          // macOS
    // ANDROID = 4,        // Android
    // IOS = 5,            // iOS
    // MOBILE_BROWSER = 6, // 移动端浏览器
    // DESKTOP_BROWSER = 7,// 桌面端浏览器
    // WECHAT_GAME = 8,    // 微信小游戏
    // BAIDU_MINI_GAME = 9,// 百度小游戏
    // XIAOMI_QUICK_GAME = 10,// 小米快游戏
    // ALIPAY_MINI_GAME = 11, // 支付宝小游戏
    // BYTEDANCE_MINI_GAME = 12,// 字节跳动小游戏
    // OPPO_MINI_GAME = 13,// OPPO小游戏
    // VIVO_MINI_GAME = 14,// vivo小游戏
    // HUAWEI_QUICK_GAME = 15,// 华为快游戏
    // COCOSPLAY = 16,     // Cocos Play
    // LINKSURE_MINI_GAME = 17,// 连尚小游戏
    // QTT_MINI_GAME = 18  // 趣头条小游戏



}
