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/utils/product.ts
var product_exports = {};
__export(product_exports, {
  applyDetailValueToProducts: () => applyDetailValueToProducts,
  applyI18nToProducts: () => applyI18nToProducts,
  applyPriceDataToProducts: () => applyPriceDataToProducts,
  getIsSessionProduct: () => getIsSessionProduct,
  perfMark: () => perfMark
});
module.exports = __toCommonJS(product_exports);
var import_utils = require("../modules/schedule/utils");
var import_utils2 = require("../../modules/Cart/utils");
function perfMark(label, durationMs, meta) {
  try {
    const w = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : null;
    if (!w)
      return;
    if (!w.__PERF__)
      w.__PERF__ = { records: [] };
    w.__PERF__.records.push({ label, duration: Math.round(durationMs * 100) / 100, ts: Date.now(), ...meta });
  } catch {
  }
}
function buildPriceIndexMap(priceData) {
  const priceMap = new Map(
    priceData.map((p) => [p.id, p])
  );
  const variantMap = /* @__PURE__ */ new Map();
  priceData.forEach((p) => {
    if (p.variant && p.variant.length > 0) {
      const variantById = new Map(p.variant.map((v) => [v.id, v]));
      variantMap.set(p.id, variantById);
    }
  });
  const bundleMap = /* @__PURE__ */ new Map();
  priceData.forEach((p) => {
    if (p.bundle_group && p.bundle_group.length > 0) {
      const groupMap = /* @__PURE__ */ new Map();
      p.bundle_group.forEach((bg) => {
        const itemMap = new Map((bg.bundle_item || []).map((bi) => [bi.id, bi]));
        groupMap.set(bg.id, itemMap);
      });
      bundleMap.set(p.id, groupMap);
    }
  });
  return { priceMap, variantMap, bundleMap };
}
function applyPriceDataToProducts(products, priceData) {
  const t0 = performance.now();
  if (!priceData || priceData.length === 0) {
    console.log("[applyPriceDataToProducts] 没有价格数据，返回原商品");
    return products;
  }
  const t1 = performance.now();
  const { priceMap, variantMap, bundleMap } = buildPriceIndexMap(priceData);
  perfMark("buildPriceIndexMap", performance.now() - t1, { priceCount: priceData.length });
  const t2 = performance.now();
  const updatedProducts = products.map((product) => {
    const priceInfo = priceMap.get(product.id);
    if (!priceInfo) {
      return product;
    }
    const updatedProduct = { ...product };
    updatedProduct.price = priceInfo.price;
    updatedProduct.base_price = priceInfo.base_price;
    if (updatedProduct.variant && updatedProduct.variant.length > 0) {
      const productVariantMap = variantMap.get(product.id);
      if (productVariantMap) {
        updatedProduct.variant = updatedProduct.variant.map((v) => {
          const priceVariant = productVariantMap.get(v.id);
          if (priceVariant) {
            return {
              ...v,
              price: String(priceVariant.price),
              base_price: String(priceVariant.base_price)
            };
          }
          return v;
        });
      }
    }
    if (updatedProduct.bundle_group && updatedProduct.bundle_group.length > 0) {
      const productBundleMap = bundleMap.get(product.id);
      if (productBundleMap) {
        updatedProduct.bundle_group = updatedProduct.bundle_group.map(
          (bg) => {
            const groupItemMap = productBundleMap.get(bg.id);
            if (!groupItemMap)
              return bg;
            return {
              ...bg,
              bundle_item: bg.bundle_item.map((bi) => {
                const priceBi = groupItemMap.get(bi.id);
                if (priceBi) {
                  let price = priceBi.price;
                  return {
                    ...bi,
                    price: String(price),
                    base_price: String(priceBi.base_price)
                  };
                }
                return bi;
              })
            };
          }
        );
      }
    }
    return updatedProduct;
  });
  perfMark("applyPriceDataToProducts.mapProducts", performance.now() - t2, { count: products.length });
  perfMark("applyPriceDataToProducts", performance.now() - t0, {
    productCount: products.length,
    priceCount: priceData.length
  });
  return updatedProducts;
}
var getIsSessionProduct = (product) => {
  return ["session_product", "session_ticket"].includes(product.extension_type);
};
var getIsOpenDetailModal = (product, context) => {
  const isBundleProduct = product.bundle_group_count > 0;
  const isOptionProduct = product.option_group_count > 0;
  const isVariantProduct = product.is_variant > 0;
  const isSessionProduct = getIsSessionProduct(product);
  let scheduleTimeSlots = [];
  if (isSessionProduct && product["schedule.ids"] && context.scheduleModule) {
    const scheduleIds = product["schedule.ids"];
    const productSchedules = context.scheduleModule.getScheduleByIds(scheduleIds);
    scheduleTimeSlots = (0, import_utils.getScheduleStartEndTimePoints)(
      context.schedule_date,
      productSchedules
    );
  }
  const isOpenDetailModal = isBundleProduct || isOptionProduct || isVariantProduct || scheduleTimeSlots.length > 1;
  return {
    isOpenDetailModal,
    scheduleTimeSlots
  };
};
var I18N_FIELD_MAP = {
  title_i18n: "title",
  subtitle_i18n: "subtitle",
  description_i18n: "description",
  cover_i18n: "cover"
};
function applyI18nToProducts(products, locale) {
  if (!locale)
    return products;
  return products.map((product) => {
    let patched = null;
    for (const [i18nKey, originalKey] of Object.entries(I18N_FIELD_MAP)) {
      const i18nDict = product[i18nKey];
      if (!i18nDict)
        continue;
      const localizedValue = i18nDict[locale];
      if (localizedValue) {
        if (!patched)
          patched = { ...product };
        patched[originalKey] = localizedValue;
      }
    }
    return patched ?? product;
  });
}
var formatDataKey = (data) => {
  var _a, _b, _c, _d;
  const _data = {
    ...data
  };
  let key = `${_data.product_id}`;
  let rowKey = key;
  if (_data.product_variant_id) {
    let str = `_${_data.product_variant_id}`;
    key += str;
    rowKey += str;
  }
  if ((_a = _data == null ? void 0 : _data.option) == null ? void 0 : _a.length) {
    for (const item of _data.option) {
      let str = `_${item.option_group_id}_${item.option_group_item_id}`;
      key += str;
      rowKey += `${str}_${item.quantity || item.num}`;
    }
  }
  if ((_b = _data == null ? void 0 : _data.bundle) == null ? void 0 : _b.length) {
    for (const item of _data.bundle) {
      let str = `_${item.group_id}_${item.bundle_product_id}`;
      key += str;
      rowKey += `${str}_${item.quantity || item.num}`;
      if (item == null ? void 0 : item.option) {
        for (const opt of item.option) {
          let str2 = `_${opt.option_group_id}_${opt.option_group_item_id}`;
          key += str2;
          rowKey += `${str2}_${opt.quantity || opt.num}`;
        }
      }
    }
  }
  if (_data == null ? void 0 : _data.session) {
    let str = `_${(_c = _data == null ? void 0 : _data.session) == null ? void 0 : _c.key}`;
    key += str;
    rowKey += str;
  }
  if (_data == null ? void 0 : _data.schedule) {
    let str = `_${(_d = _data == null ? void 0 : _data.schedule) == null ? void 0 : _d.key}`;
    key += str;
    rowKey += str;
  }
  _data.key = key;
  _data.rowKey = rowKey;
  return _data;
};
var genCartDetailValue = (product, scheduleTimeSlots) => {
  const params = {
    product_id: product == null ? void 0 : product.id,
    option: [],
    bundle: [],
    product_variant_id: 0,
    quantity: 1,
    unique: (0, import_utils2.getUniqueId)(),
    session: null
  };
  if (scheduleTimeSlots.length) {
    params.session = scheduleTimeSlots.map((item) => ({
      ...item,
      unique: (0, import_utils2.getUniqueId)()
    }))[0];
  }
  if (product == null ? void 0 : product.service_times) {
    params.service_times = product == null ? void 0 : product.service_times;
  }
  if (product == null ? void 0 : product.machine_code) {
    params.machine_code = product.machine_code;
  }
  if (product == null ? void 0 : product["schedule.ids"]) {
    params.schedule_id = product["schedule.ids"];
  }
  if (product == null ? void 0 : product.policy) {
    params.policy_id = product == null ? void 0 : product.policy;
  }
  if (product == null ? void 0 : product.duration) {
    params.duration = product.duration;
  }
  return formatDataKey(params);
};
function applyDetailValueToProducts(products, context) {
  const t0 = performance.now();
  const newProducts = products.map((product) => {
    const { isOpenDetailModal, scheduleTimeSlots } = getIsOpenDetailModal(
      product,
      context
    );
    let cartDetailValue = null;
    if (!isOpenDetailModal) {
      cartDetailValue = genCartDetailValue(product, scheduleTimeSlots);
    }
    return {
      ...product,
      isOpenDetailModal,
      cartDetailValue
    };
  });
  perfMark("applyDetailValueToProducts", performance.now() - t0, { count: products.length });
  return newProducts;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  applyDetailValueToProducts,
  applyI18nToProducts,
  applyPriceDataToProducts,
  getIsSessionProduct,
  perfMark
});
