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); }
import { isWalkInCustomer } from "../selectors";
import { pickIdentity } from "./identity";
import { resolveLocalizedText } from "./resolveLocalizedText";
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];
}
function normalizeBundleForDisplay(bundle) {
  var _bundle$metadata, _ref, _ref2, _ref3, _ref4, _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 = (_ref = (_ref2 = (_ref3 = (_ref4 = (_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 && _ref4 !== void 0 ? _ref4 : bundle === null || bundle === void 0 ? void 0 : bundle.custom_price) !== null && _ref3 !== void 0 ? _ref3 : bundle === null || bundle === void 0 ? void 0 : bundle.price) !== null && _ref2 !== void 0 ? _ref2 : bundle === null || bundle === void 0 ? void 0 : bundle.selling_price) !== null && _ref !== void 0 ? _ref : 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, _ref5, _line$metadata2, _catalog$variants, _ref8, _ref9, _ref10, _detail$product_cover, _ref11, _detail$note, _ref12, _productSummary$durat, _ref13, _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 = (_ref5 = (_line$metadata2 = line.metadata) === null || _line$metadata2 === void 0 ? void 0 : _line$metadata2.origin) !== null && _ref5 !== void 0 ? _ref5 : 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 = Array.isArray(detail === null || detail === void 0 ? void 0 : detail.product_option_item) ? detail.product_option_item : [];
  var catalogBundles = Array.isArray(catalog === null || catalog === void 0 ? void 0 : catalog.bundles) ? catalog.bundles : [];
  var catalogOptions = Array.isArray(catalog === null || catalog === void 0 ? void 0 : catalog.options) ? catalog.options : [];
  var bundleTitles = (line.product_bundle || []).map(function (b) {
    var matchedDetail = detailBundles.find(function (db) {
      return (db === null || db === void 0 ? void 0 : db.bundle_id) === (b === null || b === void 0 ? void 0 : b.bundle_id);
    });
    var matchedCatalog = catalogBundles.find(function (cb) {
      return (cb === null || cb === void 0 ? void 0 : cb.id) === (b === null || b === void 0 ? void 0 : b.bundle_id);
    });
    return resolveFirstLocalizedText(matchedDetail === null || matchedDetail === void 0 ? void 0 : matchedDetail.title, matchedCatalog === null || matchedCatalog === void 0 ? void 0 : matchedCatalog.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 optionTitles = (line.product_option_item || []).map(function (o) {
    var matchedDetail = detailOptions.find(function (d) {
      return (d === null || d === void 0 ? void 0 : d.product_option_item_id) === (o === null || o === void 0 ? void 0 : o.product_option_item_id);
    });
    var matchedCatalog = catalogOptions.find(function (co) {
      return (co === null || co === void 0 ? void 0 : co.id) === (o === null || o === void 0 ? void 0 : o.product_option_item_id);
    });
    return resolveFirstLocalizedText(matchedDetail === null || matchedDetail === void 0 ? void 0 : matchedDetail.title, matchedCatalog === null || matchedCatalog === void 0 ? void 0 : matchedCatalog.title, o === null || o === void 0 ? void 0 : o.title, o === null || o === void 0 ? void 0 : 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 _ref6, _ref7, _strategyMeta$display, _strategyMeta$display2;
    var strategyMeta = promotionInfo.strategyMetadata || {};
    var text = (_ref6 = (_ref7 = (_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 && _ref7 !== void 0 ? _ref7 : strategyMeta.title) !== null && _ref6 !== void 0 ? _ref6 : '';
    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);
  return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, line), {}, {
    product_bundle: (line.product_bundle || []).map(normalizeBundleForDisplay),
    _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: (_ref8 = (_ref9 = (_ref10 = (_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 && _ref10 !== void 0 ? _ref10 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.cover) !== null && _ref9 !== void 0 ? _ref9 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.cover_url) !== null && _ref8 !== void 0 ? _ref8 : '',
    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,
    note: (_ref11 = (_detail$note = detail === null || detail === void 0 ? void 0 : detail.note) !== null && _detail$note !== void 0 ? _detail$note : line.note) !== null && _ref11 !== void 0 ? _ref11 : '',
    duration: (_ref12 = (_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 && _ref12 !== void 0 ? _ref12 : lineOrigin === null || lineOrigin === void 0 ? void 0 : lineOrigin.duration,
    product_resource: (_ref13 = (_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 && _ref13 !== void 0 ? _ref13 : 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;
}