import { _decorator, Component, ProgressBar, Label, assetManager, director, SpriteFrame, Prefab } from 'cc';
import { ResourceManager } from './ResourceManager';
const { ccclass, property } = _decorator;

@ccclass('Loading')
export class Loading extends Component {
    @property(ProgressBar)
    progressBar: ProgressBar | null = null;

    @property(Label)
    progressLabel: Label | null = null;

    @property
    nextScene: string = "StartScene";

    onLoad() {
        // if (typeof wx !== 'undefined' && wx.hideLoading) {
        //     wx.hideLoading();
        // }
        this.startLoading();
    }

    startLoading() {
        assetManager.loadBundle("resources", (err, bundle) => {
            if (err) {
                console.error("加载 resources 失败:", err);
                return;
            }
            console.log(11111111111,2222)

            // 加载整个 resources 下的内容
            bundle.loadDir(".", (finished, total, item) => {
                let ratio = finished / total;
            console.log(11111111111,ratio)

                this.updateProgress(ratio);
            }, (err, assets) => {
                if (err) {
                    console.error("资源加载失败:", err);
                    return;
                }

                // 缓存资源
                assets.forEach(asset => {
                    ResourceManager.instance.set(asset.name, asset);
                    asset.addRef(); // 增加引用计数，避免被自动释放
                });

                // 进入主场景
                director.loadScene(this.nextScene);
            });
        });
    }

    updateProgress(ratio: number) {
        console.log(111111, ratio)
        if (this.progressBar) {
            this.progressBar.progress = ratio;
        }
        if (this.progressLabel) {
            this.progressLabel.string = `${Math.floor(ratio * 100)}%`;
        }
    }
}
