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 _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 _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 _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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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; }
/**
 * 将 GET /shop/schedule/booking 列表项转为平面图/卡片用的 {@link PisellReservationTableRow}。
 * 按资源 form_record（event_resources.relation_id）聚合；无资源时退化为按预约 id 一行。
 */
import dayjs from 'dayjs';
import { resolveFloorRoomCardHolder } from "../floorRoomCard/mapRowToFloorRoomCardData";
/**
 * 仅 `status: reserved | occupied | locked` 参与合并；`empty` 与未知项不写入预约行（桌位保持空闲底行）。
 */
function isSkippedBooking(record) {
  var _record$status;
  var s = String((_record$status = record.status) !== null && _record$status !== void 0 ? _record$status : '');
  return s !== 'reserved' && s !== 'occupied' && s !== 'locked';
}

/**
 * 从 event_resources / resources 节点收集 relation_id（与平面图 dataBinding.recordId 对齐）
 */
function collectRelationIdsFromNode(node, ids) {
  if (!node) return;
  var rid = node.relation_id;
  if (typeof rid === 'number' && rid > 0) ids.add(String(Math.trunc(rid)));else if (typeof rid === 'string' && rid !== '' && rid !== '0') ids.add(rid);
  var kids = node.children;
  if (Array.isArray(kids)) {
    for (var _i = 0, _arr = kids; _i < _arr.length; _i++) {
      var ch = _arr[_i];
      collectRelationIdsFromNode(ch, ids);
    }
  }
}

/**
 * 预约项上所有资源 form_record id（GET schedule/booking 多为 `resources`，旧结构为 `event_resources`）。
 * 多资源时同一预约会写入多个 id，合并阶段每张桌只拿命中本桌 id 的分组。
 */
export function extractResourceRecordIds(booking) {
  var ids = new Set();
  var er = booking.event_resources;
  if (Array.isArray(er)) {
    for (var _i2 = 0, _arr2 = er; _i2 < _arr2.length; _i2++) {
      var block = _arr2[_i2];
      collectRelationIdsFromNode(block, ids);
    }
  }
  var res = booking.resources;
  if (Array.isArray(res)) {
    for (var _i3 = 0, _arr3 = res; _i3 < _arr3.length; _i3++) {
      var _block = _arr3[_i3];
      collectRelationIdsFromNode(_block, ids);
    }
  }
  return _toConsumableArray(ids);
}

/**
 * 按画布已绑定资源 id 过滤 Monitor 用的 booking 列表行（与 {@link extractResourceRecordIds} 对齐）。
 * `resourceIds` 为空时返回空数组。
 */
export function filterBookingsByResourceIds(bookings, resourceIds) {
  if (!Array.isArray(bookings) || resourceIds.size === 0) {
    return [];
  }
  return bookings.filter(function (b) {
    var ids = extractResourceRecordIds(b);
    return ids.some(function (id) {
      return resourceIds.has(id);
    });
  });
}

/** 多资源单的父级壳行（无 resources / 无 product_uid），不参与按桌聚合，避免错误 orphan id */
function isAggregateParentShell(booking) {
  var meta = booking.metadata;
  if ((meta === null || meta === void 0 ? void 0 : meta.multiple_resource_flag) !== 1) return false;
  var uid = booking.product_uid;
  if (uid != null && String(uid) !== '') return false;
  var res = booking.resources;
  return !Array.isArray(res) || res.length === 0;
}
function resourceDisplayCode(booking) {
  var _meta$resource_name, _booking$id;
  var name = booking.relation_form_name;
  if (name) return name;
  var er0 = Array.isArray(booking.event_resources) ? booking.event_resources[0] : undefined;
  var res0 = Array.isArray(booking.resources) ? booking.resources[0] : undefined;
  var head = er0 !== null && er0 !== void 0 ? er0 : res0;
  var meta = head === null || head === void 0 ? void 0 : head.metadata;
  var rn = (_meta$resource_name = meta === null || meta === void 0 ? void 0 : meta.resource_name) !== null && _meta$resource_name !== void 0 ? _meta$resource_name : meta === null || meta === void 0 ? void 0 : meta.form_name;
  if (typeof rn === 'string' && rn) return rn;
  var bid = booking.booking_id;
  if (bid != null && bid !== '') return String(bid);
  return String((_booking$id = booking.id) !== null && _booking$id !== void 0 ? _booking$id : '');
}

/**
 * 预约项联系人简称（与图元 / 详情弹窗 / {@link resolveFloorRoomCardHolder} 一致，仅取展示用姓名）。
 */
export function customerBrief(record) {
  var _h$name;
  var h = resolveFloorRoomCardHolder(record);
  var n = h === null || h === void 0 || (_h$name = h.name) === null || _h$name === void 0 ? void 0 : _h$name.trim();
  return n || '';
}

/** 单条预约上的日历日，用于平面图卡片进度与合成字段 */
export function bookingReferenceDay(booking) {
  var at = booking.start_at;
  if (at && dayjs(at).isValid()) return dayjs(at).format('YYYY-MM-DD');
  var sd = booking.start_date;
  if (typeof sd === 'string' && /^\d{4}-\d{2}-\d{2}/.test(sd)) return sd.slice(0, 10);
  return undefined;
}
function formatBookingTime(record) {
  var raw = record.start_at || (record.start_date && record.start_time ? "".concat(record.start_date, " ").concat(record.start_time) : null);
  if (!raw) return '';
  var d = dayjs(raw);
  return d.isValid() ? d.format('HH:mm') : '';
}

/** 宿主 booking.status：empty / 缺省 → 空闲；reserved / occupied / locked → 对应卡片大类 */
export function hostBookingStatusToCardStatus(record) {
  var _record$status2;
  var s = String((_record$status2 = record.status) !== null && _record$status2 !== void 0 ? _record$status2 : '');
  if (s === 'occupied') return 'occupied';
  if (s === 'reserved') return 'booked';
  if (s === 'locked') return 'maintenance';
  return 'available';
}
function hostReservedStatusFromBooking(booking) {
  var _booking$reserved_sta;
  if (String(booking.status) !== 'reserved') return undefined;
  var rs = String((_booking$reserved_sta = booking.reserved_status) !== null && _booking$reserved_sta !== void 0 ? _booking$reserved_sta : '');
  if (rs === 'late') return 'late';
  if (rs === 'not_arrived') return 'not_arrived';
  return undefined;
}
function hostIsTimeoutFromBooking(booking) {
  if (String(booking.status) !== 'occupied') return undefined;
  return booking.isTimeout === true ? true : undefined;
}

/** 从单条宿主 booking 摘 `reserved_status` / `isTimeout` 信号，供行合并与图元映射 */
export function hostBookingUiPatchFromRecord(booking) {
  var hostReservedStatus = hostReservedStatusFromBooking(booking);
  var hostIsTimeout = hostIsTimeoutFromBooking(booking);
  var out = {};
  if (hostReservedStatus != null) out.hostReservedStatus = hostReservedStatus;
  if (hostIsTimeout === true) out.hostIsTimeout = true;
  return out;
}

/**
 * 无 `bookings[]` 命中时，用资源壳上的 `status` / `reserved_status` / `isTimeout` 覆盖底行（嵌套 OS 列表等）。
 */
export function applyHostResourceShellToBaseRow(base, shell) {
  var _shell$status;
  var st = String((_shell$status = shell.status) !== null && _shell$status !== void 0 ? _shell$status : '');
  if (st === 'locked') {
    return _objectSpread(_objectSpread({}, base), {}, {
      cardStatus: 'maintenance'
    });
  }
  if (st === 'empty') {
    return _objectSpread(_objectSpread({}, base), {}, {
      cardStatus: 'available',
      hostReservedStatus: undefined,
      hostIsTimeout: undefined
    });
  }
  if (st === 'occupied') {
    return _objectSpread(_objectSpread({}, base), {}, {
      cardStatus: 'occupied',
      hostIsTimeout: shell.isTimeout === true ? true : undefined,
      hostReservedStatus: undefined
    });
  }
  if (st === 'reserved') {
    return _objectSpread(_objectSpread({}, base), {}, {
      cardStatus: 'booked',
      hostIsTimeout: undefined
    }, hostBookingUiPatchFromRecord(shell));
  }
  return base;
}
function singleBookingToRow(rowId, booking, codeOverride) {
  var code = codeOverride !== null && codeOverride !== void 0 ? codeOverride : resourceDisplayCode(booking);
  return _objectSpread(_objectSpread({
    id: rowId,
    code: code,
    cardStatus: hostBookingStatusToCardStatus(booking)
  }, hostBookingUiPatchFromRecord(booking)), {}, {
    guestName: customerBrief(booking) || undefined,
    time: formatBookingTime(booking) || undefined,
    floorMapSourceBookings: [booking],
    floorMapReferenceDay: bookingReferenceDay(booking),
    partySize: function () {
      var n = booking.number;
      if (typeof n === 'number' && Number.isFinite(n)) return n;
      if (n != null && n !== '') {
        var v = Number(n);
        return Number.isFinite(v) ? v : undefined;
      }
      return undefined;
    }()
  });
}
function mergeResourceGroup(recordId, group) {
  var named = group.find(function (g) {
    return g.relation_form_name;
  });
  var code = named !== null && named !== void 0 && named.relation_form_name ? String(named.relation_form_name) : resourceDisplayCode(group[0]);
  var sorted = _toConsumableArray(group).sort(function (a, b) {
    return dayjs(a.start_at || "".concat(a.start_date || '', " ").concat(a.start_time || '').trim()).valueOf() - dayjs(b.start_at || "".concat(b.start_date || '', " ").concat(b.start_time || '').trim()).valueOf();
  });
  if (sorted.length === 1) {
    return singleBookingToRow(recordId, sorted[0], code);
  }
  var hasLocked = sorted.some(function (b) {
    return String(b.status) === 'locked';
  });
  var hasOccupied = sorted.some(function (b) {
    return String(b.status) === 'occupied';
  });
  var cardStatus = hasLocked ? 'maintenance' : hasOccupied ? 'occupied' : 'booked';
  var uiPatch = {};
  if (cardStatus === 'occupied') {
    var ob = sorted.find(function (b) {
      return String(b.status) === 'occupied';
    });
    if (ob && hostIsTimeoutFromBooking(ob)) uiPatch.hostIsTimeout = true;
  }
  if (cardStatus === 'booked') {
    var rb = sorted.find(function (b) {
      return String(b.status) === 'reserved';
    });
    var rs = rb ? hostReservedStatusFromBooking(rb) : undefined;
    if (rs != null) uiPatch.hostReservedStatus = rs;
  }
  return _objectSpread(_objectSpread({
    id: recordId,
    code: code || recordId,
    cardStatus: cardStatus
  }, cardStatus === 'maintenance' ? {
    hostReservedStatus: undefined,
    hostIsTimeout: undefined
  } : uiPatch), {}, {
    floorMapSourceBookings: sorted,
    floorMapReferenceDay: bookingReferenceDay(sorted[0]),
    slots: sorted.map(function (b) {
      return {
        name: customerBrief(b) || '',
        time: formatBookingTime(b) || '-'
      };
    })
  });
}

/**
 * 宿主已按桌聚合的 `bookings`（如同一张 resource 下的多条预约）→ 单行 {@link PisellReservationTableRow}，
 * 与 {@link mergeResourceRowsWithBookingRows} 的资源底行合并即可得到平面图 tables 项。
 */
export function mergeBookingsForResourceRecord(recordId, bookings) {
  if (!Array.isArray(bookings)) return null;
  var active = bookings.filter(function (b) {
    if (!b || _typeof(b) !== 'object') return false;
    var rec = b;
    if (isSkippedBooking(rec)) return false;
    if (isAggregateParentShell(rec)) return false;
    return true;
  });
  if (active.length === 0) return null;
  return mergeResourceGroup(recordId, active);
}

/**
 * 由预约列表构造桌位数据源（整列表，与当前表格页数据一致）。
 */
export function bookingListToReservationTableRows(bookings) {
  if (!Array.isArray(bookings) || bookings.length === 0) return [];
  var active = bookings.filter(function (b) {
    if (!b || _typeof(b) !== 'object') return false;
    var rec = b;
    if (isSkippedBooking(rec)) return false;
    if (isAggregateParentShell(rec)) return false;
    return true;
  });
  var byResource = new Map();
  var orphans = [];
  var _iterator = _createForOfIteratorHelper(active),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _b = _step.value;
      var rids = extractResourceRecordIds(_b);
      if (rids.length > 0) {
        var _iterator3 = _createForOfIteratorHelper(rids),
          _step3;
        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var _byResource$get;
            var rid = _step3.value;
            var g = (_byResource$get = byResource.get(rid)) !== null && _byResource$get !== void 0 ? _byResource$get : [];
            g.push(_b);
            byResource.set(rid, g);
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
      } else {
        orphans.push(_b);
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  var rows = [];
  var _iterator2 = _createForOfIteratorHelper(byResource),
    _step2;
  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var _step2$value = _slicedToArray(_step2.value, 2),
        _rid = _step2$value[0],
        group = _step2$value[1];
      rows.push(mergeResourceGroup(_rid, group));
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  for (var _i4 = 0, _orphans = orphans; _i4 < _orphans.length; _i4++) {
    var b = _orphans[_i4];
    var id = b.id != null ? String(b.id) : "booking_".concat(rows.length);
    rows.push(singleBookingToRow(id, b));
  }
  return rows;
}