var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/server/modules/schedule/index.ts
var schedule_exports = {};
__export(schedule_exports, {
  ScheduleModuleEx: () => ScheduleModuleEx
});
module.exports = __toCommonJS(schedule_exports);
var import_lodash_es = require("lodash-es");
var import_BaseModule = require("../../../modules/BaseModule");
var import_dayjs = __toESM(require("dayjs"));
var import_isSameOrBefore = __toESM(require("dayjs/plugin/isSameOrBefore"));
var import_isSameOrAfter = __toESM(require("dayjs/plugin/isSameOrAfter"));
var import_utils = require("../../../solution/ShopDiscount/utils");
import_dayjs.default.extend(import_isSameOrBefore.default);
import_dayjs.default.extend(import_isSameOrAfter.default);
var INDEXDB_STORE_NAME = "schedule";
var ScheduleModuleEx = class extends import_BaseModule.BaseModule {
  // LoggerManager 实例
  constructor(name, version) {
    super(name, version);
    this.defaultName = "schedule";
    this.defaultVersion = "1.1.0";
    this.store = {};
  }
  /**
   * 记录信息日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logInfo(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "info",
          title: `[ScheduleModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  /**
   * 记录警告日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logWarning(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "warning",
          title: `[ScheduleModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  /**
   * 记录错误日志
   * @param title 日志标题
   * @param metadata 日志元数据
   */
  logError(title, metadata) {
    try {
      if (this.logger) {
        this.logger.addLog({
          type: "error",
          title: `[ScheduleModule] ${title}`,
          metadata: metadata || {}
        });
      }
    } catch {
    }
  }
  async initialize(core, options) {
    this.core = core;
    this.request = core.getPlugin("request");
    if (!this.request) {
      throw new Error("ScheduleModule 需要 request 插件支持");
    }
    this.store = options == null ? void 0 : options.store;
    if (options.initialState) {
      this.store.scheduleList = options.initialState.scheduleList;
      this.syncScheduleMap();
    } else {
      this.store.scheduleList = [];
      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("[Schedule] IndexDB Manager 已初始化");
      } else {
        console.warn("[Schedule] IndexDB Manager 未找到");
      }
    }
    this.logInfo("模块初始化完成", {
      hasDbManager: !!this.dbManager,
      hasLogger: !!this.logger,
      initialScheduleCount: this.store.scheduleList.length
    });
  }
  /**
   * 加载当前店铺下所有 schedule（从服务器）
   */
  async loadAllSchedule() {
    var _a;
    this.logInfo("开始从服务器加载日程列表");
    const startTime = Date.now();
    try {
      const scheduleList = await this.request.get(
        `/schedule`,
        { num: 999 },
        { cache: void 0 }
      );
      const list = ((_a = scheduleList.data) == null ? void 0 : _a.list) || [];
      const duration = Date.now() - startTime;
      this.logInfo("从服务器加载日程列表成功", {
        scheduleCount: list.length,
        duration: `${duration}ms`
      });
      await this.saveScheduleToIndexDB(list);
      this.setScheduleList(list);
      return list;
    } catch (error) {
      const duration = Date.now() - startTime;
      const errorMessage = error instanceof Error ? error.message : String(error);
      this.logError("从服务器加载日程列表失败", {
        duration: `${duration}ms`,
        error: errorMessage
      });
      throw error;
    }
  }
  setScheduleList(list) {
    this.store.scheduleList = list;
    this.syncScheduleMap();
  }
  /**
   * 获取所有日程列表
   */
  getScheduleList() {
    return this.store.scheduleList;
  }
  /**
   * 根据 schedule IDs 获取日程数据
   * 使用 Map 快速查询，时间复杂度 O(m)，m 为 ids 数量
   */
  getScheduleByIds(ids) {
    if (!ids || ids.length === 0) {
      this.logInfo("getScheduleByIds: 未提供有效的 ids", { idsCount: 0 });
      return [];
    }
    const result = [];
    const scheduleList = this.store.scheduleList || [];
    for (const id of ids) {
      const schedule = this.store.map.get(id) || scheduleList.find((item) => String(item.id) === String(id));
      if (schedule) {
        result.push(schedule);
      }
    }
    this.logInfo("getScheduleByIds: 查询完成", {
      requestedCount: ids.length,
      foundCount: result.length,
      notFoundCount: ids.length - result.length
    });
    return result;
  }
  /**
   * 同步更新日程 Map 缓存
   * 将 scheduleList 中的日程同步到 map，以 id 为 key
   * @private
   */
  syncScheduleMap() {
    this.store.map.clear();
    for (const schedule of this.store.scheduleList) {
      this.store.map.set(schedule.id, schedule);
    }
    console.log(`[Schedule] Map 缓存已同步，共 ${this.store.map.size} 个日程`);
  }
  /**
   * 清除缓存
   */
  async clear() {
    this.logInfo("开始清空缓存", {
      currentScheduleCount: this.store.scheduleList.length
    });
    this.store.scheduleList = [];
    this.store.map.clear();
    if (this.dbManager) {
      try {
        await this.dbManager.clear(INDEXDB_STORE_NAME);
        console.log("[Schedule] IndexDB 缓存已清空");
        this.logInfo("IndexDB 缓存已清空");
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        console.error("[Schedule] 清空 IndexDB 缓存失败:", error);
        this.logError("清空 IndexDB 缓存失败", { error: errorMessage });
      }
    }
    this.logInfo("缓存清空完成");
  }
  /**
   * 判断日期是否在日程范围内
   * @param date 日期
   * @param scheduleList 日程列表
   * @returns 是否在日程范围内
   */
  getDateIsInSchedule(date, scheduleList) {
    const scheduleListData = [];
    scheduleList.forEach((item) => {
      if (typeof item === "number") {
        scheduleListData.push(...this.getScheduleByIds([item]));
      } else {
        scheduleListData.push(item);
      }
    });
    const result = (0, import_utils.getDateIsInSchedule)(date, scheduleListData);
    this.logInfo("getDateIsInSchedule: 判断日期是否在日程范围内", {
      date,
      scheduleCount: scheduleListData.length,
      isInSchedule: result
    });
    return result;
  }
  /**
   * 从 IndexDB 加载日程数据
   * @private
   */
  async loadScheduleFromIndexDB() {
    if (!this.dbManager) {
      this.logWarning("loadScheduleFromIndexDB: dbManager 不可用");
      return [];
    }
    try {
      const scheduleList = await this.dbManager.getAll(INDEXDB_STORE_NAME);
      this.logInfo("从 IndexDB 加载日程数据", {
        scheduleCount: (scheduleList == null ? void 0 : scheduleList.length) ?? 0
      });
      return scheduleList || [];
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error("[Schedule] 从 IndexDB 读取数据失败:", error);
      this.logError("从 IndexDB 读取数据失败", { error: errorMessage });
      return [];
    }
  }
  /**
   * 保存日程数据到 IndexDB
   * @private
   */
  async saveScheduleToIndexDB(scheduleList) {
    if (!this.dbManager) {
      this.logWarning("saveScheduleToIndexDB: dbManager 不可用");
      return;
    }
    this.logInfo("开始保存日程数据到 IndexDB", { scheduleCount: scheduleList.length });
    try {
      await this.dbManager.clear(INDEXDB_STORE_NAME);
      const savePromises = scheduleList.map(
        (schedule) => this.dbManager.add(INDEXDB_STORE_NAME, schedule)
      );
      await Promise.all(savePromises);
      console.log(
        `[Schedule] 已将 ${scheduleList.length} 条日程数据保存到 IndexDB`
      );
      this.logInfo("日程数据已保存到 IndexDB", { scheduleCount: scheduleList.length });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.error("[Schedule] 保存数据到 IndexDB 失败:", error);
      this.logError("保存数据到 IndexDB 失败", {
        scheduleCount: scheduleList.length,
        error: errorMessage
      });
    }
  }
  /**
   * 预加载模块数据（统一接口）
   * 在模块注册后自动调用
   */
  async preload() {
    console.log("[Schedule] 开始预加载数据...");
    const startTime = Date.now();
    this.logInfo("开始预加载数据");
    try {
      const cachedData = await this.loadScheduleFromIndexDB();
      if (cachedData && cachedData.length > 0) {
        console.log(
          `[Schedule] 从 IndexDB 加载了 ${cachedData.length} 条日程数据`
        );
        this.store.scheduleList = (0, import_lodash_es.cloneDeep)(cachedData);
        this.syncScheduleMap();
        const duration = Date.now() - startTime;
        this.logInfo("预加载完成（从 IndexDB）", {
          scheduleCount: cachedData.length,
          duration: `${duration}ms`,
          source: "IndexDB"
        });
        return;
      }
      console.log("[Schedule] IndexDB 中没有缓存数据，从服务器加载...");
      this.logInfo("IndexDB 中没有缓存数据，准备从服务器加载");
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      console.warn("[Schedule] 从 IndexDB 加载数据失败:", error);
      this.logWarning("从 IndexDB 加载数据失败，准备从服务器加载", { error: errorMessage });
    }
    const scheduleList = await this.loadAllSchedule();
    if (scheduleList && scheduleList.length > 0) {
      await this.saveScheduleToIndexDB(scheduleList);
      this.store.scheduleList = (0, import_lodash_es.cloneDeep)(scheduleList);
      this.syncScheduleMap();
      const duration = Date.now() - startTime;
      this.logInfo("预加载完成（从服务器）", {
        scheduleCount: scheduleList.length,
        duration: `${duration}ms`,
        source: "Server"
      });
    } else {
      const duration = Date.now() - startTime;
      this.logWarning("预加载完成但未获取到数据", {
        duration: `${duration}ms`
      });
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ScheduleModuleEx
});
