function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { getScheduleStartEndTimePoints } from "../modules/schedule/utils";
import { getUniqueId } from "../../modules/Cart/utils";
export function perfMark(label, durationMs, meta) {
  try {
    var w = typeof window !== 'undefined' ? window : typeof globalThis !== 'undefined' ? globalThis : null;
    if (!w) return;
    if (!w.__PERF__) w.__PERF__ = {
      records: []
    };
    w.__PERF__.records.push(_objectSpread({
      label: label,
      duration: Math.round(durationMs * 100) / 100,
      ts: Date.now()
    }, meta));
  } catch (_unused) {/* noop */}
}

/**
 * 构建价格数据的 Map 索引结构
 * 使用三层 Map 实现 O(1) 查询，大幅提升性能
 * @param priceData 价格数据数组
 * @returns 三层 Map 索引：商品、variant、bundle
 */
function buildPriceIndexMap(priceData) {
  // 1. 商品主价格 Map: productId -> priceInfo
  var priceMap = new Map(priceData.map(function (p) {
    return [p.id, p];
  }));

  // 2. Variant 价格 Map: productId -> (variantId -> variantPriceInfo)
  var variantMap = new Map();
  priceData.forEach(function (p) {
    if (p.variant && p.variant.length > 0) {
      var variantById = new Map(p.variant.map(function (v) {
        return [v.id, v];
      }));
      variantMap.set(p.id, variantById);
    }
  });

  // 3. Bundle 价格 Map: productId -> (groupId -> (itemId -> itemPriceInfo))
  var bundleMap = new Map();
  priceData.forEach(function (p) {
    if (p.bundle_group && p.bundle_group.length > 0) {
      var groupMap = new Map();
      p.bundle_group.forEach(function (bg) {
        var itemMap = new Map((bg.bundle_item || []).map(function (bi) {
          return [bi.id, bi];
        }));
        groupMap.set(bg.id, itemMap);
      });
      bundleMap.set(p.id, groupMap);
    }
  });
  return {
    priceMap: priceMap,
    variantMap: variantMap,
    bundleMap: bundleMap
  };
}

/**
 * 将价格数据应用到商品列表（高性能版本）
 * 通过预构建 Map 索引，将时间复杂度从 O(n×m) 优化到 O(n+m)
 * @param products 商品列表
 * @param priceData 价格数据
 * @returns 应用价格后的商品列表
 */
export function applyPriceDataToProducts(products, priceData) {
  var t0 = performance.now();
  if (!priceData || priceData.length === 0) {
    console.log('[applyPriceDataToProducts] 没有价格数据，返回原商品');
    return products;
  }
  var t1 = performance.now();
  var _buildPriceIndexMap = buildPriceIndexMap(priceData),
    priceMap = _buildPriceIndexMap.priceMap,
    variantMap = _buildPriceIndexMap.variantMap,
    bundleMap = _buildPriceIndexMap.bundleMap;
  perfMark('buildPriceIndexMap', performance.now() - t1, {
    priceCount: priceData.length
  });
  var t2 = performance.now();
  var updatedProducts = products.map(function (product) {
    var priceInfo = priceMap.get(product.id);
    if (!priceInfo) {
      return product;
    }
    var updatedProduct = _objectSpread({}, product);
    updatedProduct.price = priceInfo.price;
    updatedProduct.base_price = priceInfo.base_price;
    if (updatedProduct.variant && updatedProduct.variant.length > 0) {
      var productVariantMap = variantMap.get(product.id);
      if (productVariantMap) {
        updatedProduct.variant = updatedProduct.variant.map(function (v) {
          var priceVariant = productVariantMap.get(v.id);
          if (priceVariant) {
            return _objectSpread(_objectSpread({}, v), {}, {
              price: String(priceVariant.price),
              base_price: String(priceVariant.base_price)
            });
          }
          return v;
        });
      }
    }
    if (updatedProduct.bundle_group && updatedProduct.bundle_group.length > 0) {
      var productBundleMap = bundleMap.get(product.id);
      if (productBundleMap) {
        updatedProduct.bundle_group = updatedProduct.bundle_group.map(function (bg) {
          var groupItemMap = productBundleMap.get(bg.id);
          if (!groupItemMap) return bg;
          return _objectSpread(_objectSpread({}, bg), {}, {
            bundle_item: bg.bundle_item.map(function (bi) {
              var priceBi = groupItemMap.get(bi.id);
              if (priceBi) {
                var price = priceBi.price;
                return _objectSpread(_objectSpread({}, 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;
}
export var getIsSessionProduct = function getIsSessionProduct(product) {
  return ['session_product', 'session_ticket'].includes(product.extension_type);
};

/**
 * 获取是否打开详情弹窗
 * @param product 商品
 * @param context 格式化器上下文
 * @returns 是否打开详情弹窗
 */
var getIsOpenDetailModal = function getIsOpenDetailModal(product, context) {
  /** 是否为套餐组商品 */
  var isBundleProduct = product.bundle_group_count > 0;

  /** 是否为选项组商品 */
  var isOptionProduct = product.option_group_count > 0;

  /** 是否为组合规格商品 */
  var isVariantProduct = product.is_variant > 0;

  /** 是否为日程商品 */
  var isSessionProduct = getIsSessionProduct(product);

  // 获取商品关联的日程时间段
  var scheduleTimeSlots = [];
  if (isSessionProduct && product['schedule.ids'] && context.scheduleModule) {
    var scheduleIds = product['schedule.ids'];
    // 从 context 中获取完整的 scheduleList，然后过滤出商品关联的 schedule
    var productSchedules = context.scheduleModule.getScheduleByIds(scheduleIds);
    // 获取当前日期的所有时间段
    scheduleTimeSlots = getScheduleStartEndTimePoints(context.schedule_date, productSchedules);
  }

  // 是否打开详情弹窗 套餐组、选项组、组合规格、日程商品、日程时间段大于1个 打开详情弹窗
  var isOpenDetailModal = isBundleProduct || isOptionProduct || isVariantProduct || scheduleTimeSlots.length > 1;
  return {
    isOpenDetailModal: isOpenDetailModal,
    scheduleTimeSlots: scheduleTimeSlots
  };
};
var I18N_FIELD_MAP = {
  title_i18n: 'title',
  subtitle_i18n: 'subtitle',
  description_i18n: 'description',
  cover_i18n: 'cover'
};

/**
 * 根据 locale 将商品的 i18n 字段覆盖到对应原始字段
 */
export function applyI18nToProducts(products, locale) {
  if (!locale) return products;
  return products.map(function (product) {
    var _patched;
    var patched = null;
    for (var _i = 0, _Object$entries = Object.entries(I18N_FIELD_MAP); _i < _Object$entries.length; _i++) {
      var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
        i18nKey = _Object$entries$_i[0],
        originalKey = _Object$entries$_i[1];
      var i18nDict = product[i18nKey];
      if (!i18nDict) continue;
      var localizedValue = i18nDict[locale];
      if (localizedValue) {
        if (!patched) patched = _objectSpread({}, product);
        patched[originalKey] = localizedValue;
      }
    }
    return (_patched = patched) !== null && _patched !== void 0 ? _patched : product;
  });
}
var formatDataKey = function formatDataKey(data) {
  var _data$option, _data$bundle;
  var _data = _objectSpread({}, data);
  var key = "".concat(_data.product_id);
  var rowKey = key;

  // 组合规格
  if (_data.product_variant_id) {
    var str = "_".concat(_data.product_variant_id);
    key += str;
    rowKey += str;
  }

  // 单规格
  if (_data !== null && _data !== void 0 && (_data$option = _data.option) !== null && _data$option !== void 0 && _data$option.length) {
    var _iterator = _createForOfIteratorHelper(_data.option),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var item = _step.value;
        var _str = "_".concat(item.option_group_id, "_").concat(item.option_group_item_id);
        key += _str;
        rowKey += "".concat(_str, "_").concat(item.quantity || item.num);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }

  // 套餐
  if (_data !== null && _data !== void 0 && (_data$bundle = _data.bundle) !== null && _data$bundle !== void 0 && _data$bundle.length) {
    var _iterator2 = _createForOfIteratorHelper(_data.bundle),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var _item = _step2.value;
        var _str2 = "_".concat(_item.group_id, "_").concat(_item.bundle_product_id);
        key += _str2;
        rowKey += "".concat(_str2, "_").concat(_item.quantity || _item.num);
        // 如果有单规格
        if (_item !== null && _item !== void 0 && _item.option) {
          var _iterator3 = _createForOfIteratorHelper(_item.option),
            _step3;
          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              var opt = _step3.value;
              var _str3 = "_".concat(opt.option_group_id, "_").concat(opt.option_group_item_id);
              key += _str3;
              rowKey += "".concat(_str3, "_").concat(opt.quantity || opt.num);
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
        }
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
  }

  // session time
  if (_data !== null && _data !== void 0 && _data.session) {
    var _data$session;
    var _str4 = "_".concat(_data === null || _data === void 0 || (_data$session = _data.session) === null || _data$session === void 0 ? void 0 : _data$session.key);
    key += _str4;
    rowKey += _str4;
  }
  if (_data !== null && _data !== void 0 && _data.schedule) {
    var _data$schedule;
    var _str5 = "_".concat(_data === null || _data === void 0 || (_data$schedule = _data.schedule) === null || _data$schedule === void 0 ? void 0 : _data$schedule.key);
    key += _str5;
    rowKey += _str5;
  }
  _data.key = key;
  _data.rowKey = rowKey;
  return _data;
};

/**
 * 生成购物车详情值
 * @param product 商品
 * @param context 格式化器上下文
 * @returns 购物车详情值
 */
var genCartDetailValue = function genCartDetailValue(product, scheduleTimeSlots) {
  var params = {
    product_id: product === null || product === void 0 ? void 0 : product.id,
    option: [],
    bundle: [],
    product_variant_id: 0,
    quantity: 1,
    unique: getUniqueId(),
    session: null
  };
  if (scheduleTimeSlots.length) {
    params.session = scheduleTimeSlots.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        unique: getUniqueId()
      });
    })[0];
  }
  if (product !== null && product !== void 0 && product.service_times) {
    params.service_times = product === null || product === void 0 ? void 0 : product.service_times;
  }

  // 票务订单需要返回对应的扩展属性
  if (product !== null && product !== void 0 && product.machine_code) {
    params.machine_code = product.machine_code;
  }
  if (product !== null && product !== void 0 && product['schedule.ids']) {
    params.schedule_id = product['schedule.ids'];
  }

  // 协议id
  if (product !== null && product !== void 0 && product.policy) {
    params.policy_id = product === null || product === void 0 ? void 0 : product.policy;
  }

  // appointment预约商品
  if (product !== null && product !== void 0 && product.duration) {
    params.duration = product.duration;
  }
  return formatDataKey(params);
};

/**
 * 将详情值数据应用到商品列表
 * @param products 商品列表
 * @param context 格式化器上下文
 * @returns 应用详情值后的商品列表
 */
export function applyDetailValueToProducts(products, context) {
  var t0 = performance.now();
  var newProducts = products.map(function (product) {
    var _getIsOpenDetailModal = getIsOpenDetailModal(product, context),
      isOpenDetailModal = _getIsOpenDetailModal.isOpenDetailModal,
      scheduleTimeSlots = _getIsOpenDetailModal.scheduleTimeSlots;
    var cartDetailValue = null;
    if (!isOpenDetailModal) {
      cartDetailValue = genCartDetailValue(product, scheduleTimeSlots);
    }
    return _objectSpread(_objectSpread({}, product), {}, {
      isOpenDetailModal: isOpenDetailModal,
      cartDetailValue: cartDetailValue
    });
  });
  perfMark('applyDetailValueToProducts', performance.now() - t0, {
    count: products.length
  });
  return newProducts;
}