import { _decorator, assetManager, Game, SpriteAtlas, SpriteFrame } from 'cc';

export class GameDataManager {
    private static _instance: GameDataManager = null;
    static get instance(): GameDataManager {
        if (!this._instance) {
            this._instance = new GameDataManager();
        }
        return this._instance;
    }


    // 游戏信息
    private _gameInfo: any = null;
    set gameInfo(info: any) { this._gameInfo = info; this._frb = info.Frb; }
    get gameInfo(): any { return this._gameInfo; }


    private _frb: any = null;
    set frb(info: any) { this._frb = info; }
    get frb(): any { return this._frb; }

    // 自动次数
    private _autoCount: number = 0;
    set autoCount(count: number) { this._autoCount = count; }
    get autoCount(): number { return this._autoCount; }


    // 缓存图标框
    private _frameTypeCache: Map<string, SpriteFrame> = new Map();

    getFrameTypeCache(name: string): SpriteFrame {
        return this._frameTypeCache.get(name);
    }
    /**
     * 预加载框架类型缓存
     * @returns Promise 在加载完成时解析
     */
    public preloadFrameTypeCache(): Promise<void> {
        // 定义帧类型名称
        const frameNames = [
            'fr01_IronFrame',
            'fr02_SilverFrame',
            'fr03_GoldFrame',
        ];

        const blurFrameNames = [
            'fr01_IronFrame_blur',
            'fr02_SilverFrame_blur',
            'fr03_GoldFrame_blur',
        ];

        // 返回Promise，让调用者可以等待加载完成
        return new Promise<void>((resolve, reject) => {
            // 加载Game bundle
            assetManager.loadBundle('Game', (bundleErr, bundle) => {
                if (bundleErr) {
                    console.error('[GameDataManager] Failed to load Game bundle:', bundleErr);
                    reject(new Error('Failed to load Game bundle: ' + bundleErr.message));
                    return;
                }

                // 收集错误信息
                const errors: string[] = [];

                // 需要完成的加载任务数量
                let tasksToComplete = 2; // 两个图集

                // 检查是否所有任务都完成
                const checkAllTasksCompleted = () => {
                    tasksToComplete--;
                    if (tasksToComplete <= 0) {
                        if (errors.length > 0) {
                            // 有错误发生，拒绝Promise
                            reject(new Error('Frame type loading failed: ' + errors.join('; ')));
                        } else {
                            // 所有加载成功，解析Promise
                            resolve();
                        }
                    }
                };

                // 加载普通图集
                const path = 'textures/Images/icons/symbolsFrame';
                bundle.load(path, SpriteAtlas, (atlasErr, atlas: SpriteAtlas) => {
                    if (atlasErr) {
                        const errorMsg = `Failed to load normal frame atlas: ${atlasErr.message}`;
                        console.error('[GameDataManager]', errorMsg);
                        errors.push(errorMsg);
                        checkAllTasksCompleted();
                        return;
                    }

                    if (!atlas) {
                        const errorMsg = 'Normal frame atlas is null';
                        console.error('[GameDataManager]', errorMsg);
                        errors.push(errorMsg);
                        checkAllTasksCompleted();
                        return;
                    }

                    // 检查是否所有需要的帧都存在
                    const missingFrames: string[] = [];

                    // 遍历普通帧并缓存，直接使用名称作为key
                    for (const name of frameNames) {
                        const spriteFrame = atlas.getSpriteFrame(name);
                        if (spriteFrame) {
                            this._frameTypeCache.set(name, spriteFrame);
                        } else {
                            missingFrames.push(name);
                        }
                    }

                    if (missingFrames.length > 0) {
                        const errorMsg = `Missing normal frames: ${missingFrames.join(', ')}`;
                        console.warn('[GameDataManager]', errorMsg);
                        errors.push(errorMsg);
                    }

                    checkAllTasksCompleted();
                });

                // 加载模糊图集
                const blurPath = 'textures/Images/icons/symbolsFrame_blur';
                bundle.load(blurPath, SpriteAtlas, (blurAtlasErr, blurAtlas: SpriteAtlas) => {
                    if (blurAtlasErr) {
                        const errorMsg = `Failed to load blur frame atlas: ${blurAtlasErr.message}`;
                        console.error('[GameDataManager]', errorMsg);
                        errors.push(errorMsg);
                        checkAllTasksCompleted();
                        return;
                    }

                    if (!blurAtlas) {
                        const errorMsg = 'Blur frame atlas is null';
                        console.error('[GameDataManager]', errorMsg);
                        errors.push(errorMsg);
                        checkAllTasksCompleted();
                        return;
                    }

                    // 检查是否所有需要的模糊帧都存在
                    const missingBlurFrames: string[] = [];

                    // 遍历模糊帧并缓存，直接使用名称作为key
                    for (const name of blurFrameNames) {
                        const spriteFrame = blurAtlas.getSpriteFrame(name);
                        if (spriteFrame) {
                            this._frameTypeCache.set(name, spriteFrame);
                        } else {
                            missingBlurFrames.push(name);
                        }
                    }

                    if (missingBlurFrames.length > 0) {
                        const errorMsg = `Missing blur frames: ${missingBlurFrames.join(', ')}`;
                        console.warn('[GameDataManager]', errorMsg);
                        errors.push(errorMsg);
                    }

                    checkAllTasksCompleted();
                });
            });
        });
    }



    // 添加图标缓存
    private _symbolCache: Map<string, SpriteFrame> = new Map();

    getSymbolCache(name: string): SpriteFrame {
        return this._symbolCache.get(name);
    }

    /**
     * 预加载图标缓存
     */
    public preloadSymbolCache(): Promise<void> {
        // 直接定义图标名称数组
        const symbolNames = [
            's03', 's04', 's05', 's06', 's07',
            's08', 's09', 's10', 's11', 's12', 's13'
        ];

        return new Promise<void>((resolve, reject) => {
            assetManager.loadBundle('Game', (bundleErr, bundle) => {
                if (bundleErr) {
                    console.error('[GameDataManager] Failed to load Game bundle:', bundleErr);
                    reject(new Error('Failed to load Game bundle: ' + bundleErr.message));
                    return;
                }

                const path = 'textures/Images/icons/symbols_01';
                bundle.load(path, SpriteAtlas, (atlasErr, atlas: SpriteAtlas) => {
                    if (atlasErr) {
                        const errorMsg = `Failed to load symbols atlas: ${atlasErr.message}`;
                        console.error('[GameDataManager]', errorMsg);
                        reject(new Error(errorMsg));
                        return;
                    }

                    if (!atlas) {
                        const errorMsg = 'Symbols atlas is null';
                        console.error('[GameDataManager]', errorMsg);
                        reject(new Error(errorMsg));
                        return;
                    }

                    // 检查是否所有需要的图标都存在
                    const missingSymbols: string[] = [];

                    // 遍历图标并缓存
                    for (const name of symbolNames) {
                        const spriteFrame = atlas.getSpriteFrame(name);
                        if (spriteFrame) {
                            this._symbolCache.set(name, spriteFrame);
                        } else {
                            missingSymbols.push(name);
                        }
                    }

                    if (missingSymbols.length > 0) {
                        const errorMsg = `Missing symbols: ${missingSymbols.join(', ')}`;
                        console.warn('[GameDataManager]', errorMsg);
                        reject(new Error(errorMsg));
                        return;
                    }

                    resolve();
                });
            });
        });
    }

    // 获取随机图标
    getRandomSymbol(): SpriteFrame {
        const symbols = Array.from(this._symbolCache.values());
        if (symbols.length === 0) return null;

        const randomIndex = Math.floor(Math.random() * symbols.length);
        return symbols[randomIndex];
    }
}