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 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); }
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 _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; }
import { isWalkInCustomer } from "../selectors";
import { pickIdentity } from "./identity";
import { resolveLocalizedText } from "./resolveLocalizedText";
import { getDetailProductOptions, getLineProductOptions, normalizeOptionForDisplay } from "./productSkuOptions";
import { formatProductsByVariant } from "../../../components/shoppingCart/utils";

/**
 * 按优先级解析首个非空展示文案（i18n 对象须 resolve，空对象不阻断后续 fallback）。
 *
 * @example
 * resolveFirstLocalizedText(
 *   { auto: null, original: null },
 *   '桌台费',
 * ); // => '桌台费'
 */
function resolveFirstLocalizedText() {
  for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
    sources[_key] = arguments[_key];
  }
  for (var _i = 0, _sources = sources; _i < _sources.length; _i++) {
    var source = _sources[_i];
    var resolved = resolveLocalizedText(source);
    if (resolved) return resolved;
  }
  return '';
}

/**
 * 与 editCartLineBooking.findBookingForLine 对齐：优先 child booking（parent_id !== 0）。
 *
 * @example
 * pickBookingForProductUid([parent, child]); // child
 */
function pickBookingForProductUid(bookings) {
  if (!Array.isArray(bookings) || bookings.length === 0) return undefined;
  var childBooking = bookings.find(function (booking) {
    return booking.parent_id !== 0 && booking.parent_id !== null && booking.parent_id !== undefined;
  });
  return childBooking !== null && childBooking !== void 0 ? childBooking : bookings[0];
}

/**
 * 宽松比较业务 id，兼容接口返回 number/string 两种形态。
 *
 * @example
 * isSameBusinessId('10269', 10269); // true
 */
function isSameBusinessId(left, right) {
  if (left === undefined || left === null || left === '') return false;
  if (right === undefined || right === null || right === '') return false;
  return String(left) === String(right);
}

/**
 * 读取规格项 id，兼容 OS 协议与旧 UI 选择器协议。
 *
 * @example
 * getOptionItemId({ option_group_item_id: 10269 }); // 10269
 */
function getOptionItemId(option) {
  var _ref, _option$option_group_;
  return (_ref = (_option$option_group_ = option === null || option === void 0 ? void 0 : option.option_group_item_id) !== null && _option$option_group_ !== void 0 ? _option$option_group_ : option === null || option === void 0 ? void 0 : option.product_option_item_id) !== null && _ref !== void 0 ? _ref : option === null || option === void 0 ? void 0 : option.id;
}

/**
 * 读取规格组 id，兼容顶层规格和套餐子规格。
 *
 * @example
 * getOptionGroupId({ option_group_id: 2624 }); // 2624
 */
function getOptionGroupId(option) {
  return option === null || option === void 0 ? void 0 : option.option_group_id;
}

/**
 * 在扁平规格数组中按 group/item id 定位规格项。
 *
 * @example
 * findFlatOptionItem({ option_group_item_id: 1 }, [{ product_option_item_id: 1 }]);
 */
function findFlatOptionItem(option, optionItems) {
  if (!Array.isArray(optionItems) || optionItems.length === 0) return null;
  var optionItemId = getOptionItemId(option);
  var optionGroupId = getOptionGroupId(option);
  return optionItems.find(function (item) {
    if (!isSameBusinessId(getOptionItemId(item), optionItemId)) return false;
    var itemGroupId = getOptionGroupId(item);
    if (optionGroupId === undefined || optionGroupId === null || optionGroupId === '') {
      return true;
    }
    if (itemGroupId === undefined || itemGroupId === null || itemGroupId === '') {
      return true;
    }
    return isSameBusinessId(itemGroupId, optionGroupId);
  }) || null;
}

/**
 * 在商品快照的 option_group.option_item 中按 group/item id 定位规格项。
 *
 * @example
 * findGroupedOptionItem(
 *   { option_group_id: 2624, option_group_item_id: 10269 },
 *   [{ option_group: [{ id: 2624, option_item: [{ id: 10269, name: 'Large' }] }] }],
 * );
 */
function findGroupedOptionItem(option, sources) {
  var optionItemId = getOptionItemId(option);
  var optionGroupId = getOptionGroupId(option);
  var _iterator = _createForOfIteratorHelper(sources),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var source = _step.value;
      var groups = Array.isArray(source === null || source === void 0 ? void 0 : source.option_group) ? source.option_group : [];
      var _iterator2 = _createForOfIteratorHelper(groups),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var group = _step2.value;
          if (optionGroupId !== undefined && optionGroupId !== null && optionGroupId !== '' && !isSameBusinessId(group === null || group === void 0 ? void 0 : group.id, optionGroupId)) {
            continue;
          }
          var matched = findFlatOptionItem(option, group === null || group === void 0 ? void 0 : group.option_item);
          if (matched && isSameBusinessId(getOptionItemId(matched), optionItemId)) {
            return matched;
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return null;
}

/**
 * 在商品快照中定位套餐子商品，后续用于查找该子商品自己的 option_group。
 *
 * @example
 * findBundleSource({ bundle_group_id: 1, bundle_id: 2 }, [product]);
 */
function findBundleSource(bundle, sources) {
  var _bundle$bundle_id, _ref2, _bundle$bundle_produc, _bundle$bundle_group_;
  var bundleId = (_bundle$bundle_id = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_id) !== null && _bundle$bundle_id !== void 0 ? _bundle$bundle_id : bundle === null || bundle === void 0 ? void 0 : bundle.id;
  var bundleProductId = (_ref2 = (_bundle$bundle_produc = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_product_id) !== null && _bundle$bundle_produc !== void 0 ? _bundle$bundle_produc : bundle === null || bundle === void 0 ? void 0 : bundle._bundle_product_id) !== null && _ref2 !== void 0 ? _ref2 : bundle === null || bundle === void 0 ? void 0 : bundle.product_id;
  var bundleGroupId = (_bundle$bundle_group_ = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_group_id) !== null && _bundle$bundle_group_ !== void 0 ? _bundle$bundle_group_ : bundle === null || bundle === void 0 ? void 0 : bundle.group_id;
  var _iterator3 = _createForOfIteratorHelper(sources),
    _step3;
  try {
    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      var source = _step3.value;
      var groups = Array.isArray(source === null || source === void 0 ? void 0 : source.bundle_group) ? source.bundle_group : [];
      var _iterator4 = _createForOfIteratorHelper(groups),
        _step4;
      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var group = _step4.value;
          if (bundleGroupId !== undefined && bundleGroupId !== null && bundleGroupId !== '' && !isSameBusinessId(group === null || group === void 0 ? void 0 : group.id, bundleGroupId)) {
            continue;
          }
          var matched = ((group === null || group === void 0 ? void 0 : group.bundle_item) || []).find(function (item) {
            var _item$id2, _ref4, _item$bundle_product_2;
            var sourceBundleId = (_item$id2 = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id2 !== void 0 ? _item$id2 : item === null || item === void 0 ? void 0 : item.bundle_id;
            var sourceProductId = (_ref4 = (_item$bundle_product_2 = item === null || item === void 0 ? void 0 : item.bundle_product_id) !== null && _item$bundle_product_2 !== void 0 ? _item$bundle_product_2 : item === null || item === void 0 ? void 0 : item._bundle_product_id) !== null && _ref4 !== void 0 ? _ref4 : item === null || item === void 0 ? void 0 : item.product_id;
            return isSameBusinessId(sourceBundleId, bundleId) || isSameBusinessId(sourceProductId, bundleProductId);
          });
          if (matched) return matched;
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }
      var flatMatched = ((source === null || source === void 0 ? void 0 : source.bundles) || []).find(function (item) {
        var _item$id, _ref3, _item$bundle_product_;
        var sourceBundleId = (_item$id = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id !== void 0 ? _item$id : item === null || item === void 0 ? void 0 : item.bundle_id;
        var sourceProductId = (_ref3 = (_item$bundle_product_ = item === null || item === void 0 ? void 0 : item.bundle_product_id) !== null && _item$bundle_product_ !== void 0 ? _item$bundle_product_ : item === null || item === void 0 ? void 0 : item._bundle_product_id) !== null && _ref3 !== void 0 ? _ref3 : item === null || item === void 0 ? void 0 : item.product_id;
        return isSameBusinessId(sourceBundleId, bundleId) || isSameBusinessId(sourceProductId, bundleProductId);
      });
      if (flatMatched) return flatMatched;
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }
  return null;
}

/**
 * 解析规格展示标题，优先保留明细/行自身文案，再回落商品快照。
 *
 * @example
 * resolveOptionTitle({ option_group_item_id: 10269 }, [], [catalog]);
 */
function resolveOptionTitle(option, detailOptions, productSources) {
  var matchedDetail = findFlatOptionItem(option, detailOptions);
  var matchedGrouped = findGroupedOptionItem(option, productSources);
  var matchedFlat = productSources.map(function (source) {
    return findFlatOptionItem(option, source === null || source === void 0 ? void 0 : source.options);
  }).find(Boolean);
  return resolveFirstLocalizedText(matchedDetail === null || matchedDetail === void 0 ? void 0 : matchedDetail.title, matchedDetail === null || matchedDetail === void 0 ? void 0 : matchedDetail.name, option === null || option === void 0 ? void 0 : option.title, option === null || option === void 0 ? void 0 : option.name, matchedGrouped === null || matchedGrouped === void 0 ? void 0 : matchedGrouped.title, matchedGrouped === null || matchedGrouped === void 0 ? void 0 : matchedGrouped.name, matchedFlat === null || matchedFlat === void 0 ? void 0 : matchedFlat.title, matchedFlat === null || matchedFlat === void 0 ? void 0 : matchedFlat.name);
}

/**
 * 为规格项补齐 title 字段，供购物车 UI 直接消费。
 *
 * @example
 * enrichOptionForDisplay(option, detailOptions, [catalog]);
 */
function enrichOptionForDisplay(option, detailOptions, productSources) {
  var name = resolveOptionTitle(option, detailOptions, productSources);
  return _objectSpread(_objectSpread({}, option), {}, {
    name: name
  });
}
function normalizeBundleForDisplay(bundle) {
  var _bundle$metadata, _ref5, _ref6, _ref7, _ref8, _bundle$bundle_sum_pr, _bundle$bundle_paymen, _bundle$bundle_sellin, _bundle$custom_price;
  var origin = (bundle === null || bundle === void 0 || (_bundle$metadata = bundle.metadata) === null || _bundle$metadata === void 0 ? void 0 : _bundle$metadata.origin) || (bundle === null || bundle === void 0 ? void 0 : bundle.origin) || (bundle === null || bundle === void 0 ? void 0 : bundle.product);
  var title = resolveFirstLocalizedText(bundle === null || bundle === void 0 ? void 0 : bundle.bundle_title, bundle === null || bundle === void 0 ? void 0 : bundle.title, bundle === null || bundle === void 0 ? void 0 : bundle.name, bundle === null || bundle === void 0 ? void 0 : bundle.product_title, origin === null || origin === void 0 ? void 0 : origin.title, origin === null || origin === void 0 ? void 0 : origin.name);
  var price = (_ref5 = (_ref6 = (_ref7 = (_ref8 = (_bundle$bundle_sum_pr = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_sum_price) !== null && _bundle$bundle_sum_pr !== void 0 ? _bundle$bundle_sum_pr : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_payment_price) !== null && _ref8 !== void 0 ? _ref8 : bundle === null || bundle === void 0 ? void 0 : bundle.custom_price) !== null && _ref7 !== void 0 ? _ref7 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref6 !== void 0 ? _ref6 : bundle === null || bundle === void 0 ? void 0 : bundle.selling_price) !== null && _ref5 !== void 0 ? _ref5 : origin === null || origin === void 0 ? void 0 : origin.price;
  return _objectSpread(_objectSpread({}, bundle), {}, {
    bundle_title: title !== null && title !== void 0 ? title : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_title,
    bundle_sum_price: price !== null && price !== void 0 ? price : bundle === null || bundle === void 0 ? void 0 : bundle.bundle_sum_price,
    bundle_payment_price: (_bundle$bundle_paymen = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_payment_price) !== null && _bundle$bundle_paymen !== void 0 ? _bundle$bundle_paymen : price,
    bundle_selling_price: (_bundle$bundle_sellin = bundle === null || bundle === void 0 ? void 0 : bundle.bundle_selling_price) !== null && _bundle$bundle_sellin !== void 0 ? _bundle$bundle_sellin : price,
    custom_price: (_bundle$custom_price = bundle === null || bundle === void 0 ? void 0 : bundle.custom_price) !== null && _bundle$custom_price !== void 0 ? _bundle$custom_price : price
  });
}

/**
 * enrichCartItem 多源合并（仅活在 React 内存，不污染 OS tempOrder.products 提交契约）。
 *
 * 数据来源按字段优先级：
 *  - title / cover / variant_title / option / bundle 标题：bookings*.detail（编辑态权威）
 *      → productsCatalog 兜底（新建态从商品列表点加购，编辑态做兜底）
 *  - duration / product_resource / capacity：bookings*.product（编辑态商品快照）
 *      → productsCatalog 兜底
 *  - start_at / end_at / resource_id：bookings 主资源（仅编辑态）
 *  - note：detail.note → line.note（行级备注）
 *
 * 入参严格遵守 .cursor/rules/data-field-semantics.mdc：bookings 通过 product_uid 反查
 * （不发明 booking_id ↔ product 之间的等价关系），catalog 通过 product_id 字符串比对。
 */
export function enrichCartItem(line, ctx) {
  var _line$metadata, _ctx$bookingDetailMap, _ctx$productsByUid, _ref9, _line$metadata2, _catalog$variants, _lineAny$_extend, _lineOrigin$_extend, _ref12, _ref13, _ref14, _detail$product_cover, _ref15, _detail$note, _ref16, _productSummary$durat, _ref17, _productSummary$produ, _productSummary$capac, _matched$relation_id;
  var productUid = (_line$metadata = line.metadata) === null || _line$metadata === void 0 ? void 0 : _line$metadata.unique_identification_number;
  var matchedBookings = productUid ? (_ctx$bookingDetailMap = ctx.bookingDetailMap) === null || _ctx$bookingDetailMap === void 0 ? void 0 : _ctx$bookingDetailMap[String(productUid)] : undefined;
  var matched = pickBookingForProductUid(matchedBookings);
  var detail = matched === null || matched === void 0 ? void 0 : matched.detail;
  var productSummary = matched === null || matched === void 0 ? void 0 : matched.product;
  var catalog = ctx.productsCatalog.find(function (p) {
    return String(p.id) === String(line.product_id);
  });
  var runtimeOrigin = productUid ? (_ctx$productsByUid = ctx.productsByUid) === null || _ctx$productsByUid === void 0 || (_ctx$productsByUid = _ctx$productsByUid[String(productUid)]) === null || _ctx$productsByUid === void 0 ? void 0 : _ctx$productsByUid.origin : undefined;
  var lineOrigin = (_ref9 = (_line$metadata2 = line.metadata) === null || _line$metadata2 === void 0 ? void 0 : _line$metadata2.origin) !== null && _ref9 !== void 0 ? _ref9 : runtimeOrigin;
  var lineExtend = line._extend || (lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin._extend) || {};
  var variant = catalog === null || catalog === void 0 || (_catalog$variants = catalog.variants) === null || _catalog$variants === void 0 ? void 0 : _catalog$variants.find(function (v) {
    return (v === null || v === void 0 ? void 0 : v.id) === line.product_variant_id;
  });
  var detailBundles = Array.isArray(detail === null || detail === void 0 ? void 0 : detail.product_bundle) ? detail.product_bundle : [];
  var detailOptions = getDetailProductOptions(detail);
  var catalogBundles = Array.isArray(catalog === null || catalog === void 0 ? void 0 : catalog.bundles) ? catalog.bundles : [];
  var productOptionSources = [catalog, lineOrigin].filter(Boolean);
  var enrichedProductOptions = getLineProductOptions(line).map(function (o) {
    return normalizeOptionForDisplay(enrichOptionForDisplay(o, detailOptions, productOptionSources));
  });
  var enrichedProductBundles = (line.product_bundle || []).map(function (b) {
    var matchedDetail = detailBundles.find(function (db) {
      var _db$bundle_id, _b$bundle_id;
      return isSameBusinessId((_db$bundle_id = db === null || db === void 0 ? void 0 : db.bundle_id) !== null && _db$bundle_id !== void 0 ? _db$bundle_id : db === null || db === void 0 ? void 0 : db.id, (_b$bundle_id = b === null || b === void 0 ? void 0 : b.bundle_id) !== null && _b$bundle_id !== void 0 ? _b$bundle_id : b === null || b === void 0 ? void 0 : b.id);
    });
    var matchedCatalog = catalogBundles.find(function (cb) {
      var _cb$id, _b$bundle_id2;
      return isSameBusinessId((_cb$id = cb === null || cb === void 0 ? void 0 : cb.id) !== null && _cb$id !== void 0 ? _cb$id : cb === null || cb === void 0 ? void 0 : cb.bundle_id, (_b$bundle_id2 = b === null || b === void 0 ? void 0 : b.bundle_id) !== null && _b$bundle_id2 !== void 0 ? _b$bundle_id2 : b === null || b === void 0 ? void 0 : b.id);
    });
    var matchedBundleSource = findBundleSource(b, productOptionSources);
    var bundleOptionSources = [matchedDetail, matchedCatalog, matchedBundleSource, b].filter(Boolean);
    var option = (b.option || []).map(function (o) {
      return enrichOptionForDisplay(o, (matchedDetail === null || matchedDetail === void 0 ? void 0 : matchedDetail.option) || [], bundleOptionSources);
    });
    var normalizedBundle = normalizeBundleForDisplay(b);
    return _objectSpread(_objectSpread({}, normalizedBundle), {}, {
      option: option,
      bundle_title: resolveFirstLocalizedText(matchedDetail === null || matchedDetail === void 0 ? void 0 : matchedDetail.title, matchedCatalog === null || matchedCatalog === void 0 ? void 0 : matchedCatalog.title, normalizedBundle.bundle_title, b === null || b === void 0 ? void 0 : b.bundle_title, b === null || b === void 0 ? void 0 : b.title, b === null || b === void 0 ? void 0 : b.name)
    });
  });
  var bundleTitles = enrichedProductBundles.map(function (b) {
    return b.bundle_title || '';
  });
  var optionTitles = enrichedProductOptions.map(function (o) {
    return o.title || o.name || '';
  });
  var startAt = matched && matched.start_date && matched.start_time ? "".concat(matched.start_date, " ").concat(matched.start_time) : null;
  var endAt = matched && matched.end_date && matched.end_time ? "".concat(matched.end_date, " ").concat(matched.end_time) : null;

  // 促销 tag / 赠品标识从 metadata 映射到顶层，ProductCard.LineItem 直接读：
  // - `_promotionTags`：与商品列表保持同名；优先取 metadata._promotionTags（appendPromotionTags 写入），
  //   否则基于 metadata._promotion 单条派生一个 tag，让购物车行能展示促销 chip
  // - `_isGiftPromotion`：legacy 视图复用字段，赠品行（metadata._giftInfo）置 true
  var lineAny = line;
  var metadataAny = lineAny.metadata || {};
  var promotionInfo = metadataAny._promotion;
  var giftInfo = metadataAny._giftInfo;
  var promotionTags = Array.isArray(metadataAny._promotionTags) ? metadataAny._promotionTags : undefined;
  if (!promotionTags && promotionInfo) {
    var _ref10, _ref11, _strategyMeta$display, _strategyMeta$display2;
    var strategyMeta = promotionInfo.strategyMetadata || {};
    var text = (_ref10 = (_ref11 = (_strategyMeta$display = (_strategyMeta$display2 = strategyMeta.display) === null || _strategyMeta$display2 === void 0 ? void 0 : _strategyMeta$display2.text) !== null && _strategyMeta$display !== void 0 ? _strategyMeta$display : strategyMeta.name) !== null && _ref11 !== void 0 ? _ref11 : strategyMeta.title) !== null && _ref10 !== void 0 ? _ref10 : '';
    if (text) {
      var _strategyMeta$display3;
      promotionTags = [{
        text: text,
        type: ((_strategyMeta$display3 = strategyMeta.display) === null || _strategyMeta$display3 === void 0 ? void 0 : _strategyMeta$display3.type) || 'info',
        strategyId: promotionInfo.strategyId
      }];
    }
  }

  // 促销 tag：CartSkuCard Promotion 直接渲染 promotions[].text，必须是 string 不能是 i18n 对象
  var resolvedPromotionTags = promotionTags ? promotionTags.map(function (tag) {
    var _tag$text;
    return _objectSpread(_objectSpread({}, tag), {}, {
      text: resolveLocalizedText((_tag$text = tag === null || tag === void 0 ? void 0 : tag.text) !== null && _tag$text !== void 0 ? _tag$text : tag === null || tag === void 0 ? void 0 : tag.title)
    });
  }) : undefined;
  var resolvedTitle = resolveFirstLocalizedText(detail === null || detail === void 0 ? void 0 : detail.product_title, lineAny.product_title, metadataAny.product_title, productSummary === null || productSummary === void 0 ? void 0 : productSummary.title, productSummary === null || productSummary === void 0 ? void 0 : productSummary.name, catalog === null || catalog === void 0 ? void 0 : catalog.title, lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.title, lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.name, lineExtend === null || lineExtend === void 0 ? void 0 : lineExtend.product_name, metadataAny.product_name);
  var productOptionString = resolveFirstLocalizedText((_lineAny$_extend = lineAny._extend) === null || _lineAny$_extend === void 0 || (_lineAny$_extend = _lineAny$_extend.other) === null || _lineAny$_extend === void 0 ? void 0 : _lineAny$_extend.product_option_string, lineOrigin === null || lineOrigin === void 0 || (_lineOrigin$_extend = lineOrigin._extend) === null || _lineOrigin$_extend === void 0 || (_lineOrigin$_extend = _lineOrigin$_extend.other) === null || _lineOrigin$_extend === void 0 ? void 0 : _lineOrigin$_extend.product_option_string, lineAny === null || lineAny === void 0 ? void 0 : lineAny.product_option_string, lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.product_option_string);
  return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, line), {}, {
    product_option_item: enrichedProductOptions,
    product_bundle: enrichedProductBundles,
    _identity: pickIdentity(line),
    _extend: {
      booking: matched !== null && matched !== void 0 ? matched : null
    }
  }, resolvedPromotionTags !== null && resolvedPromotionTags !== void 0 && resolvedPromotionTags.length ? {
    _promotionTags: resolvedPromotionTags,
    promotions: resolvedPromotionTags
  } : {}), giftInfo ? {
    _isGiftPromotion: true,
    _giftInfo: giftInfo,
    isGift: true
  } : {}), {}, {
    title: resolvedTitle,
    cover: (_ref12 = (_ref13 = (_ref14 = (_detail$product_cover = detail === null || detail === void 0 ? void 0 : detail.product_cover) !== null && _detail$product_cover !== void 0 ? _detail$product_cover : catalog === null || catalog === void 0 ? void 0 : catalog.cover) !== null && _ref14 !== void 0 ? _ref14 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.cover) !== null && _ref13 !== void 0 ? _ref13 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.cover_url) !== null && _ref12 !== void 0 ? _ref12 : '',
    variant_title: resolveFirstLocalizedText(detail === null || detail === void 0 ? void 0 : detail.variant_title, variant === null || variant === void 0 ? void 0 : variant.title, lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.variant_title),
    bundle_titles: bundleTitles,
    option_titles: optionTitles,
    product_option_string: productOptionString,
    note: (_ref15 = (_detail$note = detail === null || detail === void 0 ? void 0 : detail.note) !== null && _detail$note !== void 0 ? _detail$note : line.note) !== null && _ref15 !== void 0 ? _ref15 : '',
    duration: (_ref16 = (_productSummary$durat = productSummary === null || productSummary === void 0 ? void 0 : productSummary.duration) !== null && _productSummary$durat !== void 0 ? _productSummary$durat : catalog === null || catalog === void 0 ? void 0 : catalog.duration) !== null && _ref16 !== void 0 ? _ref16 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.duration,
    product_resource: (_ref17 = (_productSummary$produ = productSummary === null || productSummary === void 0 ? void 0 : productSummary.product_resource) !== null && _productSummary$produ !== void 0 ? _productSummary$produ : catalog === null || catalog === void 0 ? void 0 : catalog.product_resource) !== null && _ref17 !== void 0 ? _ref17 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.product_resource,
    capacity: (_productSummary$capac = productSummary === null || productSummary === void 0 ? void 0 : productSummary.capacity) !== null && _productSummary$capac !== void 0 ? _productSummary$capac : lineExtend === null || lineExtend === void 0 ? void 0 : lineExtend.capacity,
    start_at: startAt,
    end_at: endAt,
    resource_id: (_matched$relation_id = matched === null || matched === void 0 ? void 0 : matched.relation_id) !== null && _matched$relation_id !== void 0 ? _matched$relation_id : null
  });
}

/**
 * 为主商品构建 giftData（legacy formatGiftData 对齐）。
 *
 * @example
 * const giftData = buildGiftDataForMainLine(mainLine, allLines);
 */
function buildGiftDataForMainLine(line, allLines) {
  var _line$metadata3, _line$metadata4;
  var giftOptions = (_line$metadata3 = line.metadata) === null || _line$metadata3 === void 0 || (_line$metadata3 = _line$metadata3._promotion) === null || _line$metadata3 === void 0 || (_line$metadata3 = _line$metadata3.giftInfo) === null || _line$metadata3 === void 0 ? void 0 : _line$metadata3.giftOptions;
  if (!Array.isArray(giftOptions) || giftOptions.length === 0) return null;
  var mainUid = String(((_line$metadata4 = line.metadata) === null || _line$metadata4 === void 0 ? void 0 : _line$metadata4.unique_identification_number) || '');
  if (!mainUid) return null;
  var pureMainUid = mainUid.replace(/___.*/, '');
  var selectedOriginGifts = allLines.filter(function (giftLine) {
    var _giftLine$metadata;
    var giftMeta = (_giftLine$metadata = giftLine.metadata) === null || _giftLine$metadata === void 0 ? void 0 : _giftLine$metadata._giftInfo;
    if (!giftMeta) return false;
    var pureSource = String(giftMeta.sourceProductId || '').replace(/___.*/, '');
    return mainUid.includes(pureSource) || pureSource === pureMainUid;
  });
  var selectedGifts = selectedOriginGifts.filter(function (gift) {
    return gift.product_id != null;
  }).map(function (gift) {
    return {
      id: gift.product_id,
      title: gift.title,
      image: gift.cover
    };
  });
  var totalCount = formatProductsByVariant(giftOptions).length;
  return {
    isShow: true,
    totalCount: totalCount,
    selectedGifts: selectedGifts,
    _selectedOriginGifts: selectedOriginGifts
  };
}

/**
 * 批量挂载 giftData（需全量商品行，含赠品行）。
 */
export function attachGiftDataToCartItems(lines) {
  if (!Array.isArray(lines) || lines.length === 0) return [];
  return lines.map(function (line) {
    var _line$metadata5;
    if ((_line$metadata5 = line.metadata) !== null && _line$metadata5 !== void 0 && _line$metadata5._giftInfo) return line;
    var giftData = buildGiftDataForMainLine(line, lines);
    return giftData ? _objectSpread(_objectSpread({}, line), {}, {
      giftData: giftData
    }) : line;
  });
}

/**
 * 批量 enrich 并挂载 giftData，保留行顺序。
 */
export function enrichCartItems(lines, ctx) {
  if (!Array.isArray(lines) || lines.length === 0) return [];
  var enriched = lines.map(function (line) {
    return enrichCartItem(line, ctx);
  });
  return attachGiftDataToCartItems(enriched);
}

/**
 * 客户视图：selected 优先（OS CustomerModule 给出的最完整客户对象），
 * 缺失时回落到 tempOrder.customer_*（编辑态服务端 hydrate 后写入 tempOrder 顶层）。
 *
 * 不复用 ticketBooking 老 _formatBookingDetail 中的兜底链
 * （`customer_id || customer?.id || customer?.customer_id || 1`），避免盲推断 walk-in 语义。
 */
export function enrichCustomer(selected, tempOrder) {
  if (selected && selected.id !== undefined && selected.id !== null && selected.id !== '' && selected.id !== 0) {
    var _selected$name;
    return {
      id: selected.id,
      name: (_selected$name = selected.name) !== null && _selected$name !== void 0 ? _selected$name : '',
      phone: selected.phone,
      email: selected.email,
      country_calling_code: selected.country_calling_code,
      cover: selected.cover,
      isWalkIn: isWalkInCustomer(selected)
    };
  }
  if (tempOrder && (tempOrder.customer_id != null || tempOrder.customer_name)) {
    var _tempOrder$customer_i, _tempOrder$customer_n;
    var id = (_tempOrder$customer_i = tempOrder.customer_id) !== null && _tempOrder$customer_i !== void 0 ? _tempOrder$customer_i : '';
    return {
      id: id,
      name: (_tempOrder$customer_n = tempOrder.customer_name) !== null && _tempOrder$customer_n !== void 0 ? _tempOrder$customer_n : '',
      phone: tempOrder.phone,
      email: tempOrder.email,
      country_calling_code: tempOrder.country_calling_code,
      cover: undefined,
      isWalkIn: isWalkInCustomer({
        id: id
      })
    };
  }
  return null;
}