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 _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 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 { isWalkIn } from "../../../components/booking/utils";
import { getIsSubjectRequire, isNormalProductByDurationSchedule } from "../../../components/booking/info/service2/utils";
import { getMergedBookingSources } from "./mergeBookingsForDisplay";

/** 未分配预约主体的购物车行（用于提交前弹窗） */

/** 弹窗快照行：打开时冻结，分配后仍展示 */

/** 弹窗展示行（快照 + 实时 enriched 视图） */

function hasHolderAssigned(cacheItem) {
  var _cacheItem$_extend;
  var holderId = cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.holder_id;
  if (Array.isArray(holderId)) return holderId.length > 0;
  return holderId !== undefined && holderId !== null && holderId !== '';
}

/**
 * Holder 确认弹窗按真实预约行展示；命中合并展示行时要回到对应 source，避免第一张卡显示 xN。
 *
 * @example
 * resolveSingleBookingFromMergedLine(mergedBooking, 'uid-1');
 */
function resolveSingleBookingFromMergedLine(booking, productUid) {
  var sources = getMergedBookingSources(booking);
  if (sources.length <= 1) return booking;
  var source = sources.find(function (item) {
    var _item$product, _item$booking;
    var sourceProductUid = (_item$product = item.product) === null || _item$product === void 0 || (_item$product = _item$product.metadata) === null || _item$product === void 0 ? void 0 : _item$product.unique_identification_number;
    var sourceBookingUid = (_item$booking = item.booking) === null || _item$booking === void 0 ? void 0 : _item$booking.product_uid;
    return String(sourceProductUid !== null && sourceProductUid !== void 0 ? sourceProductUid : '') === productUid || String(sourceBookingUid !== null && sourceBookingUid !== void 0 ? sourceBookingUid : '') === productUid;
  });
  if (!source) return booking;
  return _objectSpread(_objectSpread({}, source.booking), {}, {
    _extend: _objectSpread(_objectSpread({}, source.booking._extend || {}), {}, {
      product: source.product
    })
  });
}

/**
 * 从合并后的购物车展示行里反查真实预约 source，保证每个 uid 都拿到同一套 enriched 展示字段。
 *
 * @example
 * resolveSingleBookingFromMergedCartBookings(cartBookings, 'uid-2');
 */
function resolveSingleBookingFromMergedCartBookings(cartBookings, productUid) {
  var _iterator = _createForOfIteratorHelper(cartBookings),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var booking = _step.value;
      var sources = getMergedBookingSources(booking);
      if (sources.length <= 1) continue;
      var source = sources.find(function (item) {
        var _item$product2, _item$booking2;
        var sourceProductUid = (_item$product2 = item.product) === null || _item$product2 === void 0 || (_item$product2 = _item$product2.metadata) === null || _item$product2 === void 0 ? void 0 : _item$product2.unique_identification_number;
        var sourceBookingUid = (_item$booking2 = item.booking) === null || _item$booking2 === void 0 ? void 0 : _item$booking2.product_uid;
        return String(sourceProductUid !== null && sourceProductUid !== void 0 ? sourceProductUid : '') === productUid || String(sourceBookingUid !== null && sourceBookingUid !== void 0 ? sourceBookingUid : '') === productUid;
      });
      if (!source) continue;
      return _objectSpread(_objectSpread({}, source.booking), {}, {
        _extend: _objectSpread(_objectSpread({}, source.booking._extend || {}), {}, {
          product: source.product
        })
      });
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return null;
}

/**
 * 按 groupId 去重未分配行，与 booking `confirmHolderModal` 计数规则一致。
 *
 * @example
 * const lines = dedupeUnassignedHolderLines(rawLines);
 * calculateUnassignedHolderCount(lines); // => 未分配主体数量
 */
export function dedupeUnassignedHolderLines(lines) {
  var result = [];
  lines.forEach(function (line) {
    var _line$cacheItem;
    var groupId = (_line$cacheItem = line.cacheItem) === null || _line$cacheItem === void 0 || (_line$cacheItem = _line$cacheItem._extend) === null || _line$cacheItem === void 0 ? void 0 : _line$cacheItem.groupId;
    if (groupId) {
      if (!result.some(function (item) {
        var _item$cacheItem;
        return ((_item$cacheItem = item.cacheItem) === null || _item$cacheItem === void 0 || (_item$cacheItem = _item$cacheItem._extend) === null || _item$cacheItem === void 0 ? void 0 : _item$cacheItem.groupId) === groupId;
      })) {
        result.push(line);
      }
      return;
    }
    result.push(line);
  });
  return result;
}

/**
 * 统计未分配预约主体数量（按 quantity 累加）。
 *
 * @example
 * calculateUnassignedHolderCount(lines); // 1 个商品 quantity=2 => 2
 */
export function calculateUnassignedHolderCount(lines) {
  return dedupeUnassignedHolderLines(lines).reduce(function (sum, line) {
    var _line$cacheItem2;
    return sum + (((_line$cacheItem2 = line.cacheItem) === null || _line$cacheItem2 === void 0 || (_line$cacheItem2 = _line$cacheItem2._extend) === null || _line$cacheItem2 === void 0 ? void 0 : _line$cacheItem2.quantity) || 1);
  }, 0);
}

/**
 * 从 BookingTicket 购物车收集「需分配 holder 且尚未分配」的预约行。
 *
 * @example
 * const lines = collectUnassignedHolderLines(bookingTicket);
 */
export function collectUnassignedHolderLines(bookingTicket) {
  var _bookingTicket$getPro, _bookingTicket$getPro2;
  if (!bookingTicket || typeof bookingTicket.getCart !== 'function') {
    return [];
  }
  if (typeof bookingTicket.buildCacheItemFromOrderLine !== 'function') {
    return [];
  }
  var buildCacheItemFromOrderLine = bookingTicket.buildCacheItemFromOrderLine;
  var cart = bookingTicket.getCart();
  var catalog = (_bookingTicket$getPro = (_bookingTicket$getPro2 = bookingTicket.getProductCatalog) === null || _bookingTicket$getPro2 === void 0 || (_bookingTicket$getPro2 = _bookingTicket$getPro2.call(bookingTicket)) === null || _bookingTicket$getPro2 === void 0 ? void 0 : _bookingTicket$getPro2.products) !== null && _bookingTicket$getPro !== void 0 ? _bookingTicket$getPro : [];
  var rawLines = [];
  (cart.bookings || []).forEach(function (bookingView) {
    var _bookingView$_extend, _catalog$find;
    var orderLine = (_bookingView$_extend = bookingView._extend) === null || _bookingView$_extend === void 0 ? void 0 : _bookingView$_extend.product;
    if (!orderLine) {
      return;
    }
    var sourceProduct = (_catalog$find = catalog.find(function (p) {
      return String(p.id) === String(orderLine.product_id);
    })) !== null && _catalog$find !== void 0 ? _catalog$find : null;
    var cacheItem = buildCacheItemFromOrderLine({
      product: orderLine,
      booking: bookingView,
      sourceProduct: sourceProduct
    });
    if (isNormalProductByDurationSchedule(cacheItem)) {
      return;
    }
    if (hasHolderAssigned(cacheItem)) {
      return;
    }
    rawLines.push({
      cacheItem: cacheItem,
      booking: bookingView,
      orderLine: orderLine
    });
  });
  return dedupeUnassignedHolderLines(rawLines);
}

/**
 * 将未分配行映射为购物车 enriched booking 视图，保证弹窗卡片与 SaleDetail 一致。
 *
 * @example
 * resolveEnrichedBookingForLine(line, cart.bookings);
 */
export function resolveEnrichedBookingForLine(line, cartBookings) {
  var _line$orderLine$metad, _line$booking;
  var uid = (_line$orderLine$metad = line.orderLine.metadata) === null || _line$orderLine$metad === void 0 ? void 0 : _line$orderLine$metad.unique_identification_number;
  if (uid != null && uid !== '') {
    var matched = cartBookings.find(function (booking) {
      return String(booking.product_uid) === String(uid);
    });
    if (matched) return resolveSingleBookingFromMergedLine(matched, String(uid));
    var mergedSource = resolveSingleBookingFromMergedCartBookings(cartBookings, String(uid));
    if (mergedSource) return mergedSource;
  }
  var bookingId = (_line$booking = line.booking) === null || _line$booking === void 0 ? void 0 : _line$booking.booking_id;
  if (bookingId) {
    var _matched = cartBookings.find(function (booking) {
      return booking.booking_id === bookingId;
    });
    if (_matched && uid != null && uid !== '') {
      return resolveSingleBookingFromMergedLine(_matched, String(uid));
    }
    if (_matched) return _matched;
  }
  return line.booking;
}

/**
 * 从当前未分配行生成弹窗快照 key（与 dedupe 规则一致）。
 *
 * @example
 * buildHolderConfirmSnapshotKeys(collectUnassignedHolderLines(bookingTicket));
 */
export function buildHolderConfirmSnapshotKeys(lines) {
  var keys = [];
  dedupeUnassignedHolderLines(lines).forEach(function (line) {
    var _line$orderLine$metad2, _line$cacheItem3;
    var productUid = (_line$orderLine$metad2 = line.orderLine.metadata) === null || _line$orderLine$metad2 === void 0 ? void 0 : _line$orderLine$metad2.unique_identification_number;
    if (productUid === undefined || productUid === null || productUid === '') {
      return;
    }
    var key = {
      productUid: String(productUid)
    };
    if ((_line$cacheItem3 = line.cacheItem) !== null && _line$cacheItem3 !== void 0 && (_line$cacheItem3 = _line$cacheItem3._extend) !== null && _line$cacheItem3 !== void 0 && _line$cacheItem3.groupId) {
      key.groupId = line.cacheItem._extend.groupId;
    }
    keys.push(key);
  });
  return keys;
}

/**
 * 按 product_uid 从 OS 购物车反查一行（含已分配 holder）。
 */
export function resolveLineByProductUid(bookingTicket, productUid) {
  var _bookingTicket$getPro3, _bookingTicket$getPro4, _bookingView$_extend2, _catalog$find2;
  if (typeof bookingTicket.getCart !== 'function') return null;
  if (typeof bookingTicket.buildCacheItemFromOrderLine !== 'function') return null;
  var buildCacheItemFromOrderLine = bookingTicket.buildCacheItemFromOrderLine;
  var cart = bookingTicket.getCart();
  var catalog = (_bookingTicket$getPro3 = (_bookingTicket$getPro4 = bookingTicket.getProductCatalog) === null || _bookingTicket$getPro4 === void 0 || (_bookingTicket$getPro4 = _bookingTicket$getPro4.call(bookingTicket)) === null || _bookingTicket$getPro4 === void 0 ? void 0 : _bookingTicket$getPro4.products) !== null && _bookingTicket$getPro3 !== void 0 ? _bookingTicket$getPro3 : [];
  var bookingView = (cart.bookings || []).find(function (booking) {
    return String(booking.product_uid) === String(productUid);
  });
  var orderLine = bookingView === null || bookingView === void 0 || (_bookingView$_extend2 = bookingView._extend) === null || _bookingView$_extend2 === void 0 ? void 0 : _bookingView$_extend2.product;
  if (!bookingView || !orderLine) return null;
  var sourceProduct = (_catalog$find2 = catalog.find(function (p) {
    return String(p.id) === String(orderLine.product_id);
  })) !== null && _catalog$find2 !== void 0 ? _catalog$find2 : null;
  return {
    cacheItem: buildCacheItemFromOrderLine({
      product: orderLine,
      booking: bookingView,
      sourceProduct: sourceProduct
    }),
    booking: bookingView,
    orderLine: orderLine
  };
}

/**
 * 按打开时的快照渲染弹窗列表：卡片不随分配消失，数据随 cart 刷新。
 *
 * @example
 * buildHolderConfirmDisplayLines({ bookingTicket, snapshotLineKeys, cartBookings });
 */
export function buildHolderConfirmDisplayLines(input) {
  var bookingTicket = input.bookingTicket,
    snapshotLineKeys = input.snapshotLineKeys,
    cartBookings = input.cartBookings;
  var unassignedUidSet = new Set(collectUnassignedHolderLines(bookingTicket).map(function (line) {
    var _line$orderLine$metad3, _line$orderLine$metad4;
    return String((_line$orderLine$metad3 = (_line$orderLine$metad4 = line.orderLine.metadata) === null || _line$orderLine$metad4 === void 0 ? void 0 : _line$orderLine$metad4.unique_identification_number) !== null && _line$orderLine$metad3 !== void 0 ? _line$orderLine$metad3 : '');
  }));
  return snapshotLineKeys.map(function (key) {
    var baseLine = resolveLineByProductUid(bookingTicket, key.productUid);
    if (!baseLine) return null;
    return _objectSpread(_objectSpread({}, baseLine), {}, {
      displayBooking: resolveEnrichedBookingForLine(baseLine, cartBookings),
      isAssigned: !unassignedUidSet.has(key.productUid)
    });
  }).filter(function (line) {
    return line != null;
  });
}

/**
 * 保存 / 结账前是否应弹出「预约主体未分配」确认弹窗（与 ticketBooking Footer 一致）。
 *
 * @example
 * shouldPromptHolderBeforeSubmit({ customerId: 12, bookingConfig, bookingTicket });
 */
export function shouldPromptHolderBeforeSubmit(input) {
  var _input$customerId;
  var hasBookingTicket = Boolean(input.bookingTicket);
  var isWalkInCustomer = isWalkIn((_input$customerId = input.customerId) !== null && _input$customerId !== void 0 ? _input$customerId : undefined);
  var isSubjectRequire = getIsSubjectRequire({
    bookingConfig: input.bookingConfig
  });
  var unassignedCount = input.bookingTicket ? collectUnassignedHolderLines(input.bookingTicket).length : 0;
  var shouldPrompt = hasBookingTicket && !isWalkInCustomer && isSubjectRequire && unassignedCount > 0;
  return shouldPrompt;
}