System.register(["__unresolved_0", "cc", "__unresolved_1", "__unresolved_2", "__unresolved_3"], function (_export, _context) {
  "use strict";

  var _reporterNs, _cclegacy, __checkObsolete__, __checkObsoleteInNamespace__, _decorator, assetManager, SpriteFrame, Singleton, bundleConfig, Logger, _dec, _class, _crd, ccclass, property, BundleManager, bundleMgr;

  function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

  function _reportPossibleCrUseOfSingleton(extras) {
    _reporterNs.report("Singleton", "./Singleton", _context.meta, extras);
  }

  function _reportPossibleCrUseOfbundleConfig(extras) {
    _reporterNs.report("bundleConfig", "../configs/BundleConfig", _context.meta, extras);
  }

  function _reportPossibleCrUseOfLogger(extras) {
    _reporterNs.report("Logger", "../extend/Logger", _context.meta, extras);
  }

  return {
    setters: [function (_unresolved_) {
      _reporterNs = _unresolved_;
    }, function (_cc) {
      _cclegacy = _cc.cclegacy;
      __checkObsolete__ = _cc.__checkObsolete__;
      __checkObsoleteInNamespace__ = _cc.__checkObsoleteInNamespace__;
      _decorator = _cc._decorator;
      assetManager = _cc.assetManager;
      SpriteFrame = _cc.SpriteFrame;
    }, function (_unresolved_2) {
      Singleton = _unresolved_2.Singleton;
    }, function (_unresolved_3) {
      bundleConfig = _unresolved_3.bundleConfig;
    }, function (_unresolved_4) {
      Logger = _unresolved_4.Logger;
    }],
    execute: function () {
      _crd = true;

      _cclegacy._RF.push({}, "b9fe7I+vydCg6zfBnZ7lFyl", "BundleManager", undefined);

      __checkObsolete__(['_decorator', 'Asset', 'assetManager', 'AssetManager', 'Constructor', 'SpriteFrame']);

      ({
        ccclass,
        property
      } = _decorator);
      /** wws
       * Bundle 中的单个资源定义
       */

      /**Bundle 配置项*/

      /**Bundle 配置表类型（Map结构） Key: Bundle名称 Value: Bundle配置*/

      /**加载进度信息*/

      /**
       * 进度回调函数类型
       * @param progress 当前加载进度信息
       */

      /**
       * 调用实例
       *  bundleMgr.preloadConfigAllRes((progress) => {
              const percent = Math.floor(progress.totalProgress * 100);
              this.loadUI.progressLabel.string = `加载进度: ${percent}%`;
              this.loadUI.tipLabel.string = `${progress.currentBundle} (${progress.completedSteps}/${progress.totalSteps})`;
              // 更新进度条
              this.progressBar.progress = progress.totalProgress;
              this.progressBar.progress = progress.bundleProgress;
              //调试信息（可选）
              Logger.log(`当前加载: ${progress.currentAsset}`);
          });
       */
      BundleManager = (_dec = ccclass('BundleManager'), _dec(_class = class BundleManager extends (_crd && Singleton === void 0 ? (_reportPossibleCrUseOfSingleton({
        error: Error()
      }), Singleton) : Singleton) {
        constructor() {
          super(...arguments);
          //已加载的Bundle缓存（包含引用计数）
          this._bundles = new Map();
          //资源结果缓存cache (path -> asset)
          this._assetCache = new Map();
          //Bundle配置表
          this._settings = new Map();
          //当前加载进度状态
          this._loadProgress = {
            totalSteps: 0,
            completedSteps: 0,
            currentBundle: '',
            currentAsset: '',
            bundleProgress: 0,
            totalProgress: 0
          };
        }

        /**
         * 加载配置bundle下的所有资源
         * @param onProgress 加载的进度回调
         * @example 调用事例:
            bundleMgr.preloadConfigAllRes((progress) => {
            //更新UI进度显示
            const percent = Math.floor(progress.totalProgress * 100);
            this.loadUI.progressLabel.string = `加载进度: ${percent}%`;
            this.loadUI.tipLabel.string = `${progress.currentBundle} | ${progress.currentAsset} 
            (${progress.completedSteps}/${progress.totalSteps})`;
            //更新进度条
            this.progressBar.progress = progress.totalProgress;
            //this.progressBar.progress = progress.bundleProgress;
            //调试信息（可选）
            Logger.log(`当前加载: ${progress.currentBundle}` +  `${progress.currentAsset}`);
            if(progress.totalProgress == 1){
                this.loadComplete = true;
            }
        });
         */
        preloadConfigAllRes(onProgress) {
          return _asyncToGenerator(function* () {
            //初始化Bundle配置
            bundleMgr.initConfig(_crd && bundleConfig === void 0 ? (_reportPossibleCrUseOfbundleConfig({
              error: Error()
            }), bundleConfig) : bundleConfig);

            try {
              // 开始加载并显示进度
              yield bundleMgr.loadLaunchBundles(onProgress);
            } catch (error) {
              (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                error: Error()
              }), Logger) : Logger).error('资源加载失败:', error);
            }
          })();
        }
        /**
         * 初始化Bundle配置
         * @param settings Bundle配置表
         */


        initConfig(settings) {
          this._settings = settings;

          this._calculateTotalSteps();
        }
        /**
         * 加载启动时必须的Bundle（根据配置表中loadAtLaunch=true的配置）
         * @param onProgress 进度回调函数（可选）
         */


        loadLaunchBundles(onProgress) {
          var _this = this;

          return _asyncToGenerator(function* () {
            //重置进度状态
            _this._resetProgress(); //获取需要加载的Bundle配置


            var bundlesToLoad = Array.from(_this._settings.entries()).filter(_ref => {
              var [_, setting] = _ref;
              return setting.loadAtLaunch;
            }); //顺序加载每个Bundle

            for (var [bundleName, setting] of bundlesToLoad) {
              _this._loadProgress.currentBundle = bundleName;

              try {
                if (setting.autoLoadAll) {
                  yield _this._loadAutoBundle(bundleName, setting, onProgress);
                } else if (setting.preloadAssets) {
                  yield _this._loadConfiguredBundle(bundleName, setting.preloadAssets, onProgress);
                }
              } catch (err) {
                (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                  error: Error()
                }), Logger) : Logger).error("\u52A0\u8F7DBundle\u5931\u8D25 [" + bundleName + "]:", err);
              }
            }
          })();
        }
        /**
         * 加载指定Bundle
         * @param bundleName Bundle名称
         * @param onComplete 加载完成回调
         */


        loadBundle(bundleName, onComplete) {
          //检查是否已加载
          var bundleInfo = this._bundles.get(bundleName);

          if (bundleInfo) {
            bundleInfo.refCount++;
            onComplete == null || onComplete(null, bundleInfo.bundle);
            return;
          } //加载新Bundle


          assetManager.loadBundle(bundleName, (err, bundle) => {
            if (err) {
              (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                error: Error()
              }), Logger) : Logger).error("\u52A0\u8F7DBundle\u5931\u8D25 [" + bundleName + "]:", err);
              onComplete == null || onComplete(err);
              return;
            } //缓存Bundle并设置引用计数


            this._bundles.set(bundleName, {
              bundle: bundle,
              refCount: 1
            });

            onComplete == null || onComplete(null, bundle);
          });
        }
        /**
         * 获取Bundle内资源路径列表
         */


        _getBundleAssets(bundle, options) {
          return _asyncToGenerator(function* () {
            if (options === void 0) {
              options = {};
            }

            var {
              excludeFolders = true,
              excludeExtensions = []
            } = options;

            try {
              var _bundle$config;

              var paths = []; //方法1：直接从配置的paths._map中获取所有键（路径）

              if ((_bundle$config = bundle['config']) != null && (_bundle$config = _bundle$config.paths) != null && _bundle$config._map) {
                //直接从配置的paths._map中获取所有键（路径）
                paths = Array.from(Object.keys(bundle['config'].paths._map));
              } else if (bundle['_assetMap']) {
                //方法2：兼容旧的_assetMap方式
                paths = Array.from(bundle['_assetMap'].keys());
              } else {
                //方法3：回退方案
                paths = bundle.getDirWithPath('').map(item => item.path);
              } //过滤处理 排除文件夹路径


              var result = paths;

              if (excludeFolders) {
                result = result.filter(p => !p.endsWith('/'));
              } //排除特定扩展名


              if (excludeExtensions != null && excludeExtensions.length) {
                result = result.filter(p => !excludeExtensions.some(ext => p.endsWith(ext)));
              }

              return result;
            } catch (error) {
              (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                error: Error()
              }), Logger) : Logger).error("\u83B7\u53D6Bundle\u8D44\u6E90\u8DEF\u5F84\u5931\u8D25:", error);
              throw error;
            }
          })();
        }
        /**
         * 加载Bundle内的多个资源
         */


        _loadBundleAssets(bundleName, bundle, assets, onProgress) {
          var _this2 = this;

          return _asyncToGenerator(function* () {
            var totalAssets = assets.length;
            var loadedAssets = 0; //顺序加载每个资源（保持进度准确）

            var _loop = function* _loop(_asset) {
              yield new Promise(resolve => {
                _this2.loadAsset(bundleName, _asset.path, _asset.type, err => {
                  if (!err) {
                    //更新进度状态
                    loadedAssets++;
                    _this2._loadProgress.completedSteps++;
                    _this2._loadProgress.currentAsset = _asset.path;
                    _this2._loadProgress.bundleProgress = loadedAssets / totalAssets; //计算总进度（限制最大0.999避免提前显示100%）

                    _this2._loadProgress.totalProgress = Math.min(_this2._loadProgress.completedSteps / _this2._loadProgress.totalSteps, 1); // 触发进度回调

                    _this2._updateProgress(onProgress);
                  }

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

            for (var _asset of assets) {
              yield* _loop(_asset);
            }
          })();
        }
        /**调用事例
        await this.loadMultipleAssets("levels",
            [{ path: "map", type: Prefab },
            { path: "textures/trees", type: SpriteFrame },
            ],
            (progress) => {//直接更新UI进度条（0~1）
              this.loadingBar.progress = progress;
            }
            (err, asset, path) => {
                if (err) {
                    Logger.error(`资源 ${path} 加载失败:`, err);
                } else {
                    Logger.log(`资源 ${path} 加载成功:`, asset);
                }
            }
        );
        * 加载Bundle内的多个资源（仅计算当前Bundle的进度）
        * @param bundleName Bundle名称
        * @param assets 资源列表
        * @param onProgress 进度回调（当前Bundle的进度，范围0~1）
        */


        loadMultipleAssets(bundleName, assets, onProgress, onComplete) {
          var _this3 = this;

          return _asyncToGenerator(function* () {
            var totalAssets = assets.length;
            var loadedAssets = 0;

            var _loop2 = function* _loop2(_asset2) {
              yield new Promise(resolve => {
                _this3.loadAsset(bundleName, _asset2.path, _asset2.type, (err, loadedAsset) => {
                  if (err) {
                    (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                      error: Error()
                    }), Logger) : Logger).error("\u52A0\u8F7D\u8D44\u6E90\u5931\u8D25 [" + bundleName + "] " + _asset2.path + ":", err);
                    onComplete == null || onComplete(err, undefined, _asset2.path);
                  } else {
                    loadedAssets++;
                    var bundleProgress = loadedAssets / totalAssets;
                    onProgress == null || onProgress(bundleProgress);
                    onComplete == null || onComplete(null, loadedAsset, _asset2.path);
                  }

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

            for (var _asset2 of assets) {
              yield* _loop2(_asset2);
            }
          })();
        }
        /**调用事例 
         await bundleMgr.loadAsset(bundleName,path,AudioClip,(err: Error, clip: AudioClip) => {
            if(err) {
                Logger.error("加载资源失败:", err);
                return;
            }});
         * 加载Bundle内的指定资源
         * @param bundleName Bundle名称
         * @param assetPath 资源路径
         * @param type 资源类型（可选）
         * @param onComplete 加载完成回调
         */


        loadAsset(bundleName, assetPath, type, onComplete) {
          return new Promise((resolve, reject) => {
            var cacheKey = "" + assetPath; //从资源缓存中caches取

            var cachedAsset = this._assetCache.get(cacheKey);

            if (cachedAsset) {
              (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                error: Error()
              }), Logger) : Logger).log("[Cache Hit] Using cached asset: " + cacheKey);
              onComplete == null || onComplete(null, cachedAsset);
              resolve(cachedAsset);
              return;
            }

            this.loadBundle(bundleName, (err, bundle) => {
              if (err) {
                onComplete == null || onComplete(err);
                reject(null);
                return;
              } //特殊处理SpriteFrame的路径提示


              var isSpriteFrame = type && type.name === 'SpriteFrame';

              if (isSpriteFrame && !assetPath.endsWith('/spriteFrame')) {
                (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                  error: Error()
                }), Logger) : Logger).warn("SpriteFrame\u8DEF\u5F84\u5EFA\u8BAE: " + assetPath + " -> " + assetPath + "/spriteFrame", "\n(\u8BF7\u786E\u8BA4\u662F\u5426\u4F7F\u7528\u5B8C\u6574SpriteFrame\u8DEF\u5F84)");
              }

              bundle.load(assetPath, type, (err, asset) => {
                if (err || !asset) {
                  (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                    error: Error()
                  }), Logger) : Logger).error("\u52A0\u8F7D\u5931\u8D25 [" + bundleName + "] " + assetPath + ":", err.message);
                  var warning = isSpriteFrame ? "\n\u53EF\u80FD\u539F\u56E0:\n1. \u4F7F\u7528\u5B8C\u6574\u8DEF\u5F84\u5982 " + assetPath + "/spriteFrame \u7C7B\u578B\u4E3ASpriteFrame\n2. \u6216\u8005\u52A0\u8F7DTexture: " + assetPath + "/texture \u7C7B\u578B\u4E3ATexture" : "\n\u8BF7\u68C0\u67E5\u8D44\u6E90\u8DEF\u5F84\u662F\u5426\u6B63\u786E";
                  (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                    error: Error()
                  }), Logger) : Logger).warn("\u7A7A\u8D44\u6E90 [" + bundleName + "] " + assetPath, warning);
                  reject(null);
                } else {
                  this._assetCache.set(cacheKey, asset);

                  resolve(asset);
                }

                onComplete == null || onComplete(err, asset);
              });
            });
          });
        }
        /**
         * 释放Bundle
         * @param bundleName Bundle名称
         * @param force 是否强制释放（即使还有引用）
         */


        releaseBundle(bundleName, force) {
          if (force === void 0) {
            force = false;
          }

          var bundleInfo = this._bundles.get(bundleName);

          if (!bundleInfo) return; //减少引用计数

          bundleInfo.refCount--; // 当引用计数归零或强制释放时

          if (bundleInfo.refCount <= 0 || force) {
            assetManager.removeBundle(bundleInfo.bundle);

            this._bundles.delete(bundleName);

            (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
              error: Error()
            }), Logger) : Logger).log("\u5DF2\u91CA\u653EBundle: " + bundleName);
          }
        }
        /**
         * 获取已加载的Bundle实例
         * @param bundleName Bundle名称
         * @returns Bundle实例或null
         */


        getBundle(bundleName) {
          var _this4 = this;

          return _asyncToGenerator(function* () {
            var _this4$_bundles$get;

            //先从缓存中查找
            var cachedBundle = (_this4$_bundles$get = _this4._bundles.get(bundleName)) == null ? void 0 : _this4$_bundles$get.bundle;

            if (cachedBundle) {
              return cachedBundle;
            }

            try {
              //如果缓存中没有，则加载bundle
              var _bundle = yield new Promise((resolve, reject) => {
                assetManager.loadBundle(bundleName, (err, bundle) => {
                  err ? reject(err) : resolve(bundle);
                });
              });

              return _bundle;
            } catch (error) {
              (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                error: Error()
              }), Logger) : Logger).error("\u52A0\u8F7DBundle " + bundleName + " \u5931\u8D25:", error);
              return null;
            }
          })();
        }
        /**
         * 检查Bundle是否已加载
         * @param bundleName Bundle名称
         */


        hasBundle(bundleName) {
          return this._bundles.has(bundleName);
        }
        /**
         * 获取Bundle的引用计数
         * @param bundleName Bundle名称
         */


        getRefCount(bundleName) {
          var _this$_bundles$get;

          return ((_this$_bundles$get = this._bundles.get(bundleName)) == null ? void 0 : _this$_bundles$get.refCount) || 0;
        }
        /**
         * 释放所有Bundle
         * @param force 是否强制释放
         */


        releaseAll(force) {
          if (force === void 0) {
            force = false;
          }

          this._bundles.forEach((_, name) => this.releaseBundle(name, force));
        }
        /**
         * 计算总加载步骤数（用于进度计算）
         */


        _calculateTotalSteps() {
          var total = 0;

          this._settings.forEach((setting, bundleName) => {
            if (!setting.loadAtLaunch) return;

            if (setting.autoLoadAll) {
              var _this$_bundles$get2, _bundle2$config;

              //获取实际资源数量（需要先加载bundle）
              var _bundle2 = (_this$_bundles$get2 = this._bundles.get(bundleName)) == null ? void 0 : _this$_bundles$get2.bundle;

              if (_bundle2 && (_bundle2$config = _bundle2['config']) != null && (_bundle2$config = _bundle2$config.paths) != null && _bundle2$config._map) {
                total += Object.keys(_bundle2['config'].paths._map).length;
              } else {
                //自动加载模式先预估为1步，实际加载时会修正
                total += 1;
              }
            } else if (setting.preloadAssets) {
              //只统计需要加载的资源（skipLoading=false的）
              total += setting.preloadAssets.filter(asset => !asset.skipLoading).length;
            }
          });

          this._loadProgress.totalSteps = total;
        }
        /**
         * 重置加载进度状态
         */


        _resetProgress() {
          this._loadProgress = {
            totalSteps: this._loadProgress.totalSteps,
            // 保持总步骤数
            completedSteps: 0,
            currentBundle: '',
            currentAsset: '',
            bundleProgress: 0,
            totalProgress: 0
          };
        }
        /**
         * 自动加载Bundle内所有资源
         */


        _loadAutoBundle(bundleName, setting, onProgress) {
          var _this5 = this;

          return _asyncToGenerator(function* () {
            //1.加载Bundle
            var bundle = yield _this5.getBundle(bundleName);

            try {
              //2.获取Bundle内所有资源路径
              var assetPaths = yield _this5._getBundleAssets(bundle, {
                excludeExtensions: setting.excludeExtensions
              }); //3.应用排除规则

              var pathsToLoad = assetPaths.filter(path => {
                var _setting$excludePaths;

                return !((_setting$excludePaths = setting.excludePaths) != null && _setting$excludePaths.some(exclude => path.startsWith(exclude)));
              }); //4.更新总步骤数（替换之前预估的1步）

              _this5._loadProgress.totalSteps += pathsToLoad.length - 1;

              _this5._updateProgress(onProgress); //5.加载所有资源


              yield _this5._loadBundleAssets(bundleName, bundle, pathsToLoad.map(path => ({
                path
              })), onProgress);
            } catch (err) {
              (_crd && Logger === void 0 ? (_reportPossibleCrUseOfLogger({
                error: Error()
              }), Logger) : Logger).error("\u626B\u63CFBundle\u8D44\u6E90\u5931\u8D25 [" + bundleName + "]:", err);
              throw err;
            }
          })();
        }
        /**
         * 根据配置加载Bundle资源
         */


        _loadConfiguredBundle(bundleName, assets, onProgress) {
          var _this6 = this;

          return _asyncToGenerator(function* () {
            //1.加载Bundle
            var bundle = yield _this6.getBundle(bundleName); //2.过滤出需要加载的资源

            var assetsToLoad = assets.filter(asset => !asset.skipLoading); //3.加载资源

            yield _this6._loadBundleAssets(bundleName, bundle, assetsToLoad.map(asset => ({
              path: asset.path,
              type: asset.type
            })), onProgress);
          })();
        }
        /**
         * 触发进度回调
         */


        _updateProgress(onProgress) {
          //传递进度状态的副本，避免外部修改
          onProgress == null || onProgress(_extends({}, this._loadProgress));
        }
        /**
         * 明确指定元组类型
         * @param asset 未使用这个方法 之前在测试
         * { path: 'texture/msg_hint/spriteFrame', type: SpriteFrame },
           { path: 'texture/test_01/texture', type: Texture2D },
            这两种的时候有写到
         */


        _getLoadArguments(asset) {
          // 返回元组类型
          if (asset.type === SpriteFrame) {
            return [asset.path, asset.type];
          }

          return asset.type ? [asset.path, asset.type] : [asset.path];
        }

      }) || _class); //全局单例

      _export("bundleMgr", bundleMgr = BundleManager.ins());

      _cclegacy._RF.pop();

      _crd = false;
    }
  };
});
//# sourceMappingURL=28813155b5206098ac05365416bd58ff90bbc96b.js.map