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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
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/modules/BookingContext/index.ts
var BookingContext_exports = {};
__export(BookingContext_exports, {
  BookingContextModule: () => BookingContextModule,
  buildBookingConfigQueryKey: () => buildBookingConfigQueryKey,
  buildBookingResourcesQueryKey: () => buildBookingResourcesQueryKey
});
module.exports = __toCommonJS(BookingContext_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_BaseModule = require("../BaseModule");
var import_request = require("../../plugins/request");
var import_types = require("./types");
var import_formatResourceList = require("./utils/formatResourceList");
__reExport(BookingContext_exports, require("./types"), module.exports);
__reExport(BookingContext_exports, require("./utils"), module.exports);
var EMPTY_STATE = {
  bookingConfig: null,
  resourcesOrigin: [],
  resourcesOriginMap: {},
  date: null
};
var DEFAULT_BOOKING_CONFIG_PARAMS = {
  item_type: "appointment_booking",
  sub_type: "ticket"
};
var BOARD_CONFIG_CACHE = {
  useCache: true,
  cache: {
    mode: import_request.RequestModeENUM.REMOTE_LOCAL,
    type: "indexDB",
    updateCache: true
  }
};
var RESOURCE_LIST_CACHE = {
  useCache: true,
  cache: {
    mode: import_request.RequestModeENUM.REMOTE_LOCAL,
    type: "memory"
  }
};
function normalizeDate(input) {
  if (input === null || input === void 0)
    return null;
  if (typeof input === "string")
    return input || null;
  if (input instanceof Date)
    return input.toISOString();
  if (typeof input.format === "function") {
    try {
      return input.format() || null;
    } catch {
      return null;
    }
  }
  return null;
}
function toScheduleQueryDate(input) {
  const normalized = normalizeDate(input);
  if (!normalized)
    return (0, import_dayjs.default)().format("YYYY-MM-DD");
  const parsed = (0, import_dayjs.default)(normalized);
  return parsed.isValid() ? parsed.format("YYYY-MM-DD") : (0, import_dayjs.default)().format("YYYY-MM-DD");
}
function buildResourcesMap(resources) {
  const map = {};
  resources.forEach((resource) => {
    if (resource && resource.id !== void 0 && resource.id !== null) {
      map[String(resource.id)] = resource;
    }
  });
  return map;
}
function buildBookingConfigQueryKey(params = {}) {
  const merged = { ...DEFAULT_BOOKING_CONFIG_PARAMS, ...params };
  const keys = Object.keys(merged).sort();
  const sorted = {};
  keys.forEach((k) => {
    sorted[k] = merged[k];
  });
  return JSON.stringify(sorted);
}
function buildBookingResourcesQueryKey(params = {}) {
  const date = toScheduleQueryDate(params.date);
  const ids = (params.bookingIds || []).filter((id) => typeof id === "number" && Number.isFinite(id)).sort((a, b) => a - b);
  return `${date}|${ids.join(",")}`;
}
var BookingContextModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "bookingContext";
    this.defaultVersion = "1.0.0";
    this.store = { ...EMPTY_STATE };
    /** 上次成功 loadBookingConfig 的 query key；命中则不再请求。 */
    this.lastConfigQueryKey = null;
    /** 上次成功 loadResources 的 query key（date|bookingIds）；命中则不再请求。 */
    this.lastResourcesQueryKey = null;
  }
  async initialize(core, options = {}) {
    this.core = core;
    this.request = core.getPlugin("request");
    if (!this.request) {
      throw new Error("BookingContextModule 需要 request 插件支持");
    }
    this.store = {
      bookingConfig: null,
      resourcesOrigin: [],
      resourcesOriginMap: {},
      date: null
    };
    const initialState = options.initialState || {};
    if (initialState.bookingConfig) {
      this.store.bookingConfig = initialState.bookingConfig;
    }
    if (Array.isArray(initialState.resourcesOrigin)) {
      this.store.resourcesOrigin = initialState.resourcesOrigin;
      this.store.resourcesOriginMap = buildResourcesMap(initialState.resourcesOrigin);
    }
    if (initialState.date) {
      this.store.date = initialState.date;
    }
  }
  async loadBookingConfig(params = {}) {
    const configKey = buildBookingConfigQueryKey(params);
    if (this.store.bookingConfig != null && this.lastConfigQueryKey === configKey) {
      return this.store.bookingConfig;
    }
    const query = {
      ...DEFAULT_BOOKING_CONFIG_PARAMS,
      ...params
    };
    const res = await this.request.get(
      "/core/board/management/config",
      query,
      BOARD_CONFIG_CACHE
    );
    const config = (res == null ? void 0 : res.data) ?? null;
    console.log("config123", config);
    this.setBookingConfig(config);
    this.lastConfigQueryKey = buildBookingConfigQueryKey(params);
    return config;
  }
  async loadResources(params = {}) {
    const date = toScheduleQueryDate(params.date ?? this.store.date);
    const resourcesKey = buildBookingResourcesQueryKey({
      date,
      bookingIds: params.bookingIds
    });
    if (this.lastResourcesQueryKey === resourcesKey) {
      return this.getResourcesOrigin();
    }
    const res = await this.request.get(
      "/schedule/resource/list",
      { date },
      RESOURCE_LIST_CACHE
    );
    const { list } = (0, import_formatResourceList.formatResourceListAndMap)(res == null ? void 0 : res.data, params.bookingIds || []);
    this.setResources(list);
    this.lastResourcesQueryKey = buildBookingResourcesQueryKey({
      date,
      bookingIds: params.bookingIds
    });
    return list;
  }
  /**
   * store 内是否已具备与本次 init 入参等价的 config / resources（不再打接口）。
   */
  isBookingContextReady(params = {}) {
    const configKey = buildBookingConfigQueryKey(params.bookingConfigParams);
    const dateInput = params.date ?? this.store.date ?? (0, import_dayjs.default)();
    const queryDate = toScheduleQueryDate(dateInput);
    const resourcesKey = buildBookingResourcesQueryKey({
      date: queryDate,
      bookingIds: params.bookingIds
    });
    const configReady = this.store.bookingConfig != null && this.lastConfigQueryKey === configKey;
    const resourcesReady = params.loadResources === false || this.lastResourcesQueryKey === resourcesKey;
    return configReady && resourcesReady;
  }
  async initBookingContext(params = {}) {
    const dateInput = params.date ?? this.store.date ?? (0, import_dayjs.default)();
    const queryDate = toScheduleQueryDate(dateInput);
    this.setDate(dateInput);
    if (!params.forceRefresh && this.isBookingContextReady(params)) {
      return this.getState();
    }
    const configKey = buildBookingConfigQueryKey(params.bookingConfigParams);
    const resourcesKey = buildBookingResourcesQueryKey({
      date: queryDate,
      bookingIds: params.bookingIds
    });
    const needConfig = params.forceRefresh || this.store.bookingConfig == null || this.lastConfigQueryKey !== configKey;
    const needResources = params.loadResources !== false && (params.forceRefresh || this.lastResourcesQueryKey !== resourcesKey);
    if (needConfig) {
      await this.loadBookingConfig(params.bookingConfigParams);
    }
    if (needResources) {
      await this.loadResources({
        date: queryDate,
        bookingIds: params.bookingIds
      });
    }
    return this.getState();
  }
  setBookingConfig(config) {
    this.store.bookingConfig = config || null;
    this.core.effects.emit(
      `${this.name}:${import_types.BookingContextEvent.OnBookingConfigChange}`,
      this.store.bookingConfig
    );
  }
  getBookingConfig() {
    return this.store.bookingConfig;
  }
  setResources(resources) {
    const list = Array.isArray(resources) ? resources : [];
    this.store.resourcesOrigin = list;
    this.store.resourcesOriginMap = buildResourcesMap(list);
    this.core.effects.emit(`${this.name}:${import_types.BookingContextEvent.OnResourcesChange}`, {
      resourcesOrigin: this.store.resourcesOrigin,
      resourcesOriginMap: this.store.resourcesOriginMap
    });
  }
  getResourcesOrigin() {
    return [...this.store.resourcesOrigin];
  }
  getResourcesOriginMap() {
    return this.store.resourcesOriginMap;
  }
  setDate(date) {
    this.store.date = normalizeDate(date);
    this.core.effects.emit(`${this.name}:${import_types.BookingContextEvent.OnDateChange}`, this.store.date);
  }
  getDate() {
    return this.store.date;
  }
  getState() {
    return {
      bookingConfig: this.store.bookingConfig,
      resourcesOrigin: [...this.store.resourcesOrigin],
      resourcesOriginMap: this.store.resourcesOriginMap,
      date: this.store.date
    };
  }
  clear() {
    this.lastConfigQueryKey = null;
    this.lastResourcesQueryKey = null;
    this.store = {
      bookingConfig: null,
      resourcesOrigin: [],
      resourcesOriginMap: {},
      date: null
    };
    this.core.effects.emit(`${this.name}:${import_types.BookingContextEvent.OnBookingConfigChange}`, null);
    this.core.effects.emit(`${this.name}:${import_types.BookingContextEvent.OnResourcesChange}`, {
      resourcesOrigin: [],
      resourcesOriginMap: {}
    });
    this.core.effects.emit(`${this.name}:${import_types.BookingContextEvent.OnDateChange}`, null);
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BookingContextModule,
  buildBookingConfigQueryKey,
  buildBookingResourcesQueryKey,
  ...require("./types"),
  ...require("./utils")
});
