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; }
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); }
/**
 * 把 `/order/sales/{id}` 响应（OrderData）解析为 ISalesDetail。
 *
 * - 纯函数：不依赖任何运行时模块/插件，便于单测与 view-model 适配
 * - products 保留 tempOrder / 后端详情原字段，仅做浅拷贝，避免丢失 product_sku 等协议字段
 * - bookings 平铺保留服务端原顺序，同时输出 byProductUid 反查表与 rootBooking
 * - header 收敛"非数组顶层字段"，便于 ticketBooking view-model 直接消费
 *
 * 设计原则参考 `.cursor/rules/data-field-semantics.mdc`：
 * - 字段命名以《统一 Sales 数据协议》为准（OrderData 类型）
 * - root booking 以 `parent_id === 0` 判定，沿用 ticketBooking 现有约定
 *   （`packages/private-materials/src/components/ticketBooking/index.tsx`：
 *    `booking.parent_id === 0 ? 'list' : 'detail'`）
 * - 不在此处发明等价关系；UI 侧（ticketBooking）若需要别的字段，由 view-model 适配层做转换
 */

/** OrderData 中除大数组外的"顶层 header 字段"白名单，按需扩展。 */
var HEADER_KEYS = ['order_id', 'order_number', 'shop_order_number', 'shop_full_order_number', 'type', 'business_code', 'platform', 'sales_channel', 'order_sales_channel', 'vouchers', 'status', 'payment_status', 'shipping_status', 'customer_id', 'customer_name', 'country_calling_code', 'phone', 'email', 'is_price_include_tax', 'tax_title', 'tax_country_code', 'currency_code', 'currency_symbol', 'currency_format', 'is_deposit', 'deposit_amount', 'shop_discount', 'surcharge_fee', 'note', 'schedule_date', 'created_at', 'updated_at', 'metadata', 'total_amount', 'shop_id', 'create_date', 'holder', 'relation_forms', 'contacts', 'contacts_info'];
function pickHeader(raw) {
  var _raw$order_id;
  var header = {
    order_id: (_raw$order_id = raw === null || raw === void 0 ? void 0 : raw.order_id) !== null && _raw$order_id !== void 0 ? _raw$order_id : null
  };
  if (!raw || _typeof(raw) !== 'object') return header;
  var _iterator = _createForOfIteratorHelper(HEADER_KEYS),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _key = _step.value;
      if (raw[_key] !== undefined) header[_key] = raw[_key];
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return header;
}
function pickCustomer(raw) {
  var _raw$customer_id, _raw$customer_name;
  if (!raw || _typeof(raw) !== 'object') return null;
  var explicit = raw.customer;
  if (explicit && _typeof(explicit) === 'object') {
    var _ref, _explicit$id, _ref2, _explicit$name, _explicit$phone, _explicit$email, _explicit$country_cal;
    return _objectSpread({
      id: (_ref = (_explicit$id = explicit.id) !== null && _explicit$id !== void 0 ? _explicit$id : raw.customer_id) !== null && _ref !== void 0 ? _ref : null,
      name: (_ref2 = (_explicit$name = explicit.name) !== null && _explicit$name !== void 0 ? _explicit$name : raw.customer_name) !== null && _ref2 !== void 0 ? _ref2 : '',
      phone: (_explicit$phone = explicit.phone) !== null && _explicit$phone !== void 0 ? _explicit$phone : raw.phone,
      email: (_explicit$email = explicit.email) !== null && _explicit$email !== void 0 ? _explicit$email : raw.email,
      country_calling_code: (_explicit$country_cal = explicit.country_calling_code) !== null && _explicit$country_cal !== void 0 ? _explicit$country_cal : raw.country_calling_code
    }, explicit);
  }
  if (raw.customer_id == null && !raw.customer_name) return null;
  return {
    id: (_raw$customer_id = raw.customer_id) !== null && _raw$customer_id !== void 0 ? _raw$customer_id : null,
    name: (_raw$customer_name = raw.customer_name) !== null && _raw$customer_name !== void 0 ? _raw$customer_name : '',
    phone: raw.phone,
    email: raw.email,
    country_calling_code: raw.country_calling_code
  };
}

/**
 * 判定根 booking。沿用 ticketBooking 现有约定：
 *   `parent_id === 0` 视为根；其余为子（item_type === 'recurring_booking' 也按 parent_id 判定）。
 *   见 `packages/private-materials/src/components/ticketBooking/index.tsx`：
 *   `type: booking.parent_id === 0 ? 'list' : 'detail'`。
 */
function isRootBooking(booking) {
  if (!booking || _typeof(booking) !== 'object') return false;
  var parentId = booking.parent_id;
  if (parentId === 0 || parentId === null || parentId === undefined) return true;
  return false;
}
function indexBookingsByProductUid(bookings) {
  var result = {};
  var _iterator2 = _createForOfIteratorHelper(bookings),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var _b$metadata;
      var b = _step2.value;
      var uid = b && (b.product_uid || ((_b$metadata = b.metadata) === null || _b$metadata === void 0 ? void 0 : _b$metadata.product_uid)) || '';
      if (!uid) continue;
      var _key2 = String(uid);
      if (!result[_key2]) result[_key2] = [];
      result[_key2].push(b);
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return result;
}

/**
 * 将 `/order/sales/{id}` 响应解析为 ISalesDetail。
 *
 * 注意：
 * - 入参允许是 `{ data: OrderData }` 或直接 `OrderData`，自动识别。
 * - products 保留原字段；字段补齐由 OrderModule hydrate 负责。
 * - 不做远程请求；不修改入参；返回新对象。
 */
export function parseSalesResponse(input) {
  var raw = input && _typeof(input) === 'object' && input.data && input.order_id == null ? input.data : input || {};
  var productsRaw = Array.isArray(raw === null || raw === void 0 ? void 0 : raw.products) ? raw.products : [];
  var products = productsRaw.map(function (p, index) {
    var row = _objectSpread({}, p || {});
    var metadata = row.metadata && _typeof(row.metadata) === 'object' ? _objectSpread({}, row.metadata) : {};
    if (!metadata.unique_identification_number) {
      var _row$product_id, _row$product_variant_;
      metadata.unique_identification_number = "sales-product-".concat((_row$product_id = row.product_id) !== null && _row$product_id !== void 0 ? _row$product_id : 'unknown', "-").concat((_row$product_variant_ = row.product_variant_id) !== null && _row$product_variant_ !== void 0 ? _row$product_variant_ : 0, "-").concat(index);
    }
    delete metadata.price_schema_version;
    delete row.identity_key;
    return _objectSpread(_objectSpread({}, row), {}, {
      metadata: metadata
    });
  });
  var bookingsRaw = Array.isArray(raw === null || raw === void 0 ? void 0 : raw.bookings) ? raw.bookings : [];
  var bookings = bookingsRaw.map(function (b) {
    return _objectSpread({}, b || {});
  });
  var rootBooking = bookings.find(isRootBooking) || null;
  var bookingsByProductUid = indexBookingsByProductUid(bookings);
  var payments = Array.isArray(raw === null || raw === void 0 ? void 0 : raw.payments) ? raw.payments.map(function (p) {
    return _objectSpread({}, p || {});
  }) : [];
  var surcharges = Array.isArray(raw === null || raw === void 0 ? void 0 : raw.surcharges) ? raw.surcharges.map(function (s) {
    return _objectSpread({}, s || {});
  }) : [];
  var discount_list = Array.isArray(raw === null || raw === void 0 ? void 0 : raw.discount_list) ? raw.discount_list.map(function (d) {
    return _objectSpread({}, d || {});
  }) : [];
  var summary = raw !== null && raw !== void 0 && raw.summary && _typeof(raw.summary) === 'object' ? _objectSpread({}, raw.summary) : {};
  return {
    header: pickHeader(raw),
    products: products,
    bookings: bookings,
    rootBooking: rootBooking,
    bookingsByProductUid: bookingsByProductUid,
    payments: payments,
    surcharges: surcharges,
    discount_list: discount_list,
    customer: pickCustomer(raw),
    summary: summary,
    raw: raw
  };
}