var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/server/modules/menu/index.ts
var menu_exports = {};
__export(menu_exports, {
  MenuModule: () => MenuModule
});
module.exports = __toCommonJS(menu_exports);
var import_lodash_es = require("lodash-es");
var import_BaseModule = require("../../../modules/BaseModule");
var import_types = require("./types");
var INDEXDB_STORE_NAME = "menu";
var MenuModule = class extends import_BaseModule.BaseModule {
  // LoggerManager 实例
  constructor(name, version) {
    super(name, version);
    this.defaultName = "menu";
    this.defaultVersion = "1.0.0";
  }
  async initialize(core, options) {
    var _a;
    this.core = core;
    this.store = options == null ? void 0 : options.store;
    this.request = core.getPlugin("request");
    if (!this.request) {
      throw new Error("MenuModule 需要 request 插件支持");
    }
    if (Array.isArray((_a = options == null ? void 0 : options.initialState) == null ? void 0 : _a.menuList)) {
      this.store.menuList = options == null ? void 0 : options.initialState.menuList;
      this.syncMenuMap();
      this.core.effects.emit(import_types.MenuHooks.onMenuChanged, this.store.menuList);
    } else {
      this.store.menuList = [];
      this.store.map = /* @__PURE__ */ new Map();
    }
    const appPlugin = core.getPlugin("app");
    if (appPlugin) {
      const app = appPlugin.getApp();
      this.dbManager = app.dbManager;
      this.logger = app.logger;
      if (this.dbManager) {
        console.log("[Menu] IndexDB Manager 已初始化");
      } else {
        console.warn("[Menu] IndexDB Manager 未找到");
      }
    }
    this.logInfo("模块初始化完成", {
      hasDbManager: !!this.dbManager,
      hasLogger: !!this.logger,
      initialMenuCount: this.store.menuList.length
    });
  }
  /**
   * 加载餐牌列表（从服务器）
   */
  async loadMenuList() {
    var _a;
    this.logInfo("开始从服务器加载餐牌列表");
    const startTime = Date.now();
    try {
      const response = await this.request.get(
        `/form/data/v1`,
        {
          skip: 1,
          num: 999,
          code: "menu_list"
        },
        { cache: void 0 }
      );
      const menuList = ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.list) || [];
      const duration = Date.now() - startTime;
      this.logInfo("从服务器加载餐牌列表成功", {
        menuCount: menuList.length,
        duration: `${duration}ms`
      });
      await this.saveMenuToIndexDB(menuList);
      await this.setMenuList(menuList);
      return menuList;
    } catch (error) {
      const duration = Date.now() - startTime;
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error("[Menu] 加载餐牌数据失败:", error);
      this.logError("从服务器加载餐牌列表失败", {
        duration: `${duration}ms`,
        error: errorMessage
      });
      return [];
    }
  }
  /**
   * 设置餐牌列表
   */
  async setMenuList(menuList) {
    this.store.menuList = menuList;
    this.syncMenuMap();
    await this.core.effects.emit(import_types.MenuHooks.onMenuLoaded, menuList);
  }
  /**
   * 获取餐牌列表
   */
  getMenuList() {
    return this.store.menuList;
  }
  /**
   * 根据 form_record_id 数组获取餐牌详情
   * 使用 Map 快速查询，时间复杂度 O(m)，m 为 ids 数量
   */
  getMenuByIds(ids) {
    if (!ids || ids.length === 0) {
      this.logInfo("getMenuByIds: 未提供有效的 ids", { idsCount: 0 });
      return [];
    }
    const result = [];
    for (const id of ids) {
      const menu = this.store.map.get(id);
      if (menu) {
        result.push(menu);
      }
    }
    this.logInfo("getMenuByIds: 查询完成", {
      requestedCount: ids.length,
      foundCount: result.length,
      notFoundCount: ids.length - result.length
    });
    return result;
  }
  /**
   * 同步更新餐牌 Map 缓存
   * 将 menuList 中的餐牌同步到 map，以 form_record_id 为 key
   * @private
   */
  syncMenuMap() {
    this.store.map.clear();
    for (const menu of this.store.menuList) {
      this.store.map.set(menu.form_record_id, menu);
    }
    console.log(`[Menu] Map 缓存已同步，共 ${this.store.map.size} 个餐牌`);
  }
  /**
   * 清空缓存
   */
  async clear() {
    this.logInfo("开始清空缓存", {
      currentMenuCount: this.store.menuList.length
    });
    this.store.menuList = [];
    this.store.map.clear();
    this.store.currentMenu = void 0;
    if (this.dbManager) {
      try {
        await this.dbManager.clear(INDEXDB_STORE_NAME);
        console.log("[Menu] IndexDB 缓存已清空");
        this.logInfo("IndexDB 缓存已清空");
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        console.error("[Menu] 清空 IndexDB 缓存失败:", error);
        this.logError("清空 IndexDB 缓存失败", { error: errorMessage });
      }
    }
    console.log("[Menu] 缓存已清空");
    this.logInfo("缓存清空完成");
  }
  /**
   * 从 IndexDB 加载餐牌数据
   * @private
   */
  async loadMenuFromIndexDB() {
    if (!this.dbManager) {
      this.logWarning("loadMenuFromIndexDB: dbManager 不可用");
      return [];
    }
    try {
      const menuList = await this.dbManager.getAll(INDEXDB_STORE_NAME);
      this.logInfo("从 IndexDB 加载餐牌数据", {
        menuCount: (menuList == null ? void 0 : menuList.length) ?? 0
      });
      return menuList || [];
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error("[Menu] 从 IndexDB 读取数据失败:", error);
      this.logError("从 IndexDB 读取数据失败", { error: errorMessage });
      return [];
    }
  }
  /**
   * 保存餐牌数据到 IndexDB
   * @private
   */
  async saveMenuToIndexDB(menuList) {
    if (!this.dbManager) {
      this.logWarning("saveMenuToIndexDB: dbManager 不可用");
      return;
    }
    this.logInfo("开始保存餐牌数据到 IndexDB", { menuCount: menuList.length });
    try {
      await this.dbManager.clear(INDEXDB_STORE_NAME);
      const savePromises = menuList.map(
        (menu) => this.dbManager.add(INDEXDB_STORE_NAME, menu)
      );
      await Promise.all(savePromises);
      console.log(`[Menu] 已将 ${menuList.length} 条餐牌数据保存到 IndexDB`);
      this.logInfo("餐牌数据已保存到 IndexDB", { menuCount: menuList.length });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error("[Menu] 保存数据到 IndexDB 失败:", error);
      this.logError("保存数据到 IndexDB 失败", {
        menuCount: menuList.length,
        error: errorMessage
      });
    }
  }
  /**
   * 预加载模块数据（统一接口）
   * 在模块注册后自动调用
   */
  async preload() {
    console.log("[Menu] 开始预加载数据...");
    const startTime = Date.now();
    this.logInfo("开始预加载数据");
    try {
      const cachedData = await this.loadMenuFromIndexDB();
      if (cachedData && cachedData.length > 0) {
        console.log(`[Menu] 从 IndexDB 加载了 ${cachedData.length} 条餐牌数据`);
        this.store.menuList = (0, import_lodash_es.cloneDeep)(cachedData);
        this.syncMenuMap();
        this.core.effects.emit(import_types.MenuHooks.onMenuChanged, this.store.menuList);
        const duration = Date.now() - startTime;
        this.logInfo("预加载完成（从 IndexDB）", {
          menuCount: cachedData.length,
          duration: `${duration}ms`,
          source: "IndexDB"
        });
        return;
      }
      console.log("[Menu] IndexDB 中没有缓存数据，从服务器加载...");
      this.logInfo("IndexDB 中没有缓存数据，准备从服务器加载");
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.warn("[Menu] 从 IndexDB 加载数据失败:", error);
      this.logWarning("从 IndexDB 加载数据失败，准备从服务器加载", { error: errorMessage });
    }
    const menuList = await this.loadMenuList();
    if (menuList && menuList.length > 0) {
      await this.saveMenuToIndexDB(menuList);
      this.store.menuList = (0, import_lodash_es.cloneDeep)(menuList);
      this.syncMenuMap();
      this.core.effects.emit(import_types.MenuHooks.onMenuChanged, this.store.menuList);
      const duration = Date.now() - startTime;
      this.logInfo("预加载完成（从服务器）", {
        menuCount: menuList.length,
        duration: `${duration}ms`,
        source: "Server"
      });
    } else {
      const duration = Date.now() - startTime;
      this.logWarning("预加载完成但未获取到数据", {
        duration: `${duration}ms`
      });
    }
  }
  /**
   * 获取模块的路由定义
   * 返回该模块需要注册的 API 路由
   */
  getRoutes() {
    return [
      // GET /api/menu - 获取所有餐牌
      {
        method: "get",
        path: "/api/menu",
        handler: async () => {
          const menuList = this.getMenuList();
          return {
            success: true,
            data: menuList,
            total: menuList.length
          };
        }
      }
    ];
  }
  /**
   * 记录信息日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logInfo(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "info",
          title: `[MenuModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  /**
   * 记录警告日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logWarning(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "warning",
          title: `[MenuModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  /**
   * 记录错误日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logError(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "error",
          title: `[MenuModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MenuModule
});
