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 _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 _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 { formatFloorRoomCardBookingTimeRange, formatFloorRoomCardGuestDisplayLine, formatFloorRoomCardGuestDisplayLineFromHolder, formatFloorRoomCardNextGuestStripLine, floorRoomCardBookingStartEndMs, getFloorRoomCardPrimaryBooking, isFloorRoomCardBookingInProgress, isFloorRoomCardBookingNotStarted, reservationScheduleMinuteFloorMs, reservationScheduleOccupiedOvertimeThresholdMs, reservationScheduleReservedLateThresholdMs } from "../floorRoomCard/floorRoomCardUtils";
import { mapPisellReservationRowToFloorRoomCardData, resolveFloorRoomCardHolder } from "../floorRoomCard/mapRowToFloorRoomCardData";
/**
 * 合并桌位行 → 大屏资源墙卡片（首版：与平面图/列表展示字段对齐，灯控等可后续接接口）。
 *
 * **整分钟边界**：状态切换按「日程写在 HH:mm 的整分」对齐——例如结束 9:00 时 9:00 整段仍非 overtime，
 * 从 9:01 起 expired；开始 8:00 时 8:00 整段仍 boardingSoon，从 8:01 起 late（见 floorRoomCardUtils 同名工具）。
 *
 * **大屏 Current / Next**：仅按预约起止时间与当前时刻划分，不用接口 `is_next` / `isNext`。
 */
export function mapReservationRowsToVenueWallCards(rows) {
  return rows.map(mapReservationTableRowToVenueWallCard);
}
function formatResourceWallContactLine(row) {
  /**
   * 与 floor map 同源：从 row 构造 RoomCardData 后取 primary booking，
   * 用统一的 holder 展示规则（姓名优先；预留态可展示手机号尾号）。
   */
  var roomTitle = String(row.code || row.main_field || row.id || '').trim();
  var data = mapPisellReservationRowToFloorRoomCardData(row, roomTitle);
  var primary = getFloorRoomCardPrimaryBooking(data);
  var showPhoneOnRow = row.cardStatus === 'booked';
  var primaryLine = primary ? formatFloorRoomCardGuestDisplayLine(primary, showPhoneOnRow).trim() : '';
  if (primaryLine) return primaryLine;

  /**
   * 兜底：主 booking 未带 holder 时，尝试从同资源 bookings 中找第一条可展示的联系人。
   * 仍复用同一套格式化规则，但允许展示脱敏手机号，避免回退成场地名。
   */
  var _iterator = _createForOfIteratorHelper(data.bookings),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var b = _step.value;
      var t = formatFloorRoomCardGuestDisplayLine(b, showPhoneOnRow).trim();
      if (t) return t;
    }

    /** 无联系人可展示：不要回退成场地名，保持为空 */
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return '';
}

/**
 * 与 {@link formatResourceWallContactLine} 一致：先按行态 `showPhone`，再允许脱敏手机号；
 * 若模型上 holder 仍空，再对命中的 floor raw 走同一套 `resolveFloorRoomCardHolder`（与 rawToBooking 同源）。
 */
function formatResourceWallNextBookingGuestLine(row, nextBooking) {
  var showPhoneOnRow = row.cardStatus === 'booked';
  var fromModel = formatFloorRoomCardGuestDisplayLine(nextBooking, showPhoneOnRow).trim() || formatFloorRoomCardGuestDisplayLine(nextBooking, true).trim();
  if (fromModel) return fromModel;
  var raw = resolveFloorRawForNextBooking(row, nextBooking);
  if (raw) {
    var h = resolveFloorRoomCardHolder(raw);
    var fromRaw = formatFloorRoomCardGuestDisplayLineFromHolder(h, showPhoneOnRow).trim() || formatFloorRoomCardGuestDisplayLineFromHolder(h, true).trim();
    if (fromRaw) return fromRaw;
  }
  return formatFloorRoomCardNextGuestStripLine(nextBooking).trim();
}

/** 在 `floorMapSourceBookings` 中定位 Next 对应 raw，供联系人解析与列表同源 */
function resolveFloorRawForNextBooking(row, nextBooking) {
  var _nextBooking$booking_;
  var src = row.floorMapSourceBookings;
  if (!Array.isArray(src) || src.length === 0) return undefined;
  var wantBid = String((_nextBooking$booking_ = nextBooking.booking_id) !== null && _nextBooking$booking_ !== void 0 ? _nextBooking$booking_ : '').trim();
  if (wantBid && !wantBid.startsWith('syn_')) {
    var byId = src.find(function (x) {
      var _ref, _r$booking_id;
      var r = x;
      var id = String((_ref = (_r$booking_id = r.booking_id) !== null && _r$booking_id !== void 0 ? _r$booking_id : r.id) !== null && _ref !== void 0 ? _ref : '').trim();
      return id !== '' && id === wantBid;
    });
    if (byId) return byId;
  }
  var byNext = src.find(function (x) {
    var _r$is_next;
    var r = x;
    var n = (_r$is_next = r.is_next) !== null && _r$is_next !== void 0 ? _r$is_next : r.isNext;
    return n === true || n === 'true' || n === 1 || n === '1';
  });
  return byNext;
}
function sortBookingsByStartAsc(bookings) {
  return _toConsumableArray(bookings).sort(function (a, b) {
    var as = floorRoomCardBookingStartEndMs(a).start;
    var bs = floorRoomCardBookingStartEndMs(b).start;
    return as - bs;
  });
}

/**
 * 大屏专用：按时间段决定 Current / Next，不读 `isNext`。
 * - 恰有一条进行中：展示 Current；若时间轴上还有下一条则同时展示 Next。
 * - 无进行中、前一段已结束且下一段未开始（间隙）：仅展示 Next。
 * - 多条时按开始时间排序后解析。
 */
function resolveVenueWallCurrentNextByTime(bookings, nowMs) {
  if (bookings.length === 0) {
    return {
      mode: 'empty',
      current: null,
      next: null
    };
  }
  var s = sortBookingsByStartAsc(bookings);
  var activeIdx = s.findIndex(function (b) {
    return isFloorRoomCardBookingInProgress(b, nowMs);
  });
  if (activeIdx >= 0) {
    var cur = s[activeIdx];
    var nx = activeIdx + 1 < s.length ? s[activeIdx + 1] : null;
    return {
      mode: nx ? 'both' : 'currentOnly',
      current: cur,
      next: nx
    };
  }
  var upcomingIdx = s.findIndex(function (b) {
    var _floorRoomCardBooking = floorRoomCardBookingStartEndMs(b),
      start = _floorRoomCardBooking.start;
    return Number.isFinite(start) && nowMs < start;
  });
  if (upcomingIdx >= 0) {
    var up = s[upcomingIdx];
    var _floorRoomCardBooking2 = floorRoomCardBookingStartEndMs(up),
      sUp = _floorRoomCardBooking2.start;
    if (upcomingIdx > 0) {
      var prev = s[upcomingIdx - 1];
      var _floorRoomCardBooking3 = floorRoomCardBookingStartEndMs(prev),
        ePrev = _floorRoomCardBooking3.end;
      if (Number.isFinite(ePrev) && nowMs >= ePrev && Number.isFinite(sUp) && nowMs < sUp) {
        return {
          mode: 'nextOnly',
          current: null,
          next: up
        };
      }
    }
    var _nx = upcomingIdx + 1 < s.length ? s[upcomingIdx + 1] : null;
    return {
      mode: _nx ? 'both' : 'single',
      current: up,
      next: _nx
    };
  }
  return {
    mode: 'empty',
    current: null,
    next: null
  };
}
function buildNextListEntry(row, nextBooking, nowMs) {
  var booking = formatResourceWallNextBookingGuestLine(row, nextBooking).trim();
  var time = formatFloorRoomCardBookingTimeRange(nextBooking).trim();
  var _floorRoomCardBooking4 = floorRoomCardBookingStartEndMs(nextBooking),
    start = _floorRoomCardBooking4.start;
  var startInMin = 0;
  if (Number.isFinite(start)) {
    startInMin = Math.max(0, Math.ceil((start - nowMs) / 60000));
  }
  return {
    time: time || '—',
    booking: booking || '—',
    startInMin: startInMin
  };
}
function applyStatusFromPrimaryBooking(primary, nowMs) {
  var status = 'available';
  var remainingMin = undefined;
  var startsInMin = undefined;
  var lateMin = undefined;
  var sessionStartMs = undefined;
  var sessionEndMs = undefined;
  var host = primary.hostBookingStatus;
  if (host === 'reserved') {
    var _floorRoomCardBooking5 = floorRoomCardBookingStartEndMs(primary),
      s = _floorRoomCardBooking5.start;
    if (Number.isFinite(s)) {
      var startMinuteMs = reservationScheduleMinuteFloorMs(s);
      var lateThresholdMs = reservationScheduleReservedLateThresholdMs(s);
      if (nowMs >= lateThresholdMs) {
        status = 'late';
        lateMin = Math.max(0, Math.ceil((nowMs - lateThresholdMs) / 60000));
      } else {
        status = 'boardingSoon';
        startsInMin = Math.max(0, Math.ceil((startMinuteMs - nowMs) / 60000));
      }
    } else {
      status = 'boardingSoon';
    }
  } else if (host === 'occupied') {
    var se = floorRoomCardBookingStartEndMs(primary);
    var s0 = se.start,
      e = se.end;
    if (Number.isFinite(s0)) {
      sessionStartMs = reservationScheduleMinuteFloorMs(s0);
    }
    if (Number.isFinite(e)) {
      var overtimeMs = reservationScheduleOccupiedOvertimeThresholdMs(e);
      sessionEndMs = overtimeMs;
      var remainingNominalMin = Math.ceil((e - nowMs) / 60000);
      remainingMin = Math.max(0, remainingNominalMin);
      var remainingUntilOvertimeMin = Math.ceil((overtimeMs - nowMs) / 60000);
      if (nowMs >= overtimeMs) status = 'expired';else if (remainingUntilOvertimeMin <= 10 && remainingUntilOvertimeMin > 0) status = 'endingSoon';else status = 'inUse';
    } else {
      status = 'inUse';
    }
  }
  return {
    status: status,
    remainingMin: remainingMin,
    startsInMin: startsInMin,
    lateMin: lateMin,
    sessionStartMs: sessionStartMs,
    sessionEndMs: sessionEndMs
  };
}
function mapReservationTableRowToVenueWallCard(row) {
  var _roomData$bookings;
  var cardStatus = row.cardStatus;
  var isAvailable = cardStatus === 'available' || cardStatus === 'maintenance';
  var nowMs = Date.now();
  var roomTitle = String(row.code || row.main_field || row.id || '').trim();
  var roomData = mapPisellReservationRowToFloorRoomCardData(row, roomTitle);
  var bookings = (_roomData$bookings = roomData.bookings) !== null && _roomData$bookings !== void 0 ? _roomData$bookings : [];
  var nextList = undefined;
  var wallUseNextLabelHideNextRow = undefined;
  var currentTime = '';
  var currentBookingDisplay = '';
  var statusPack = {
    status: 'available',
    remainingMin: undefined,
    startsInMin: undefined,
    lateMin: undefined,
    sessionStartMs: undefined,
    sessionEndMs: undefined
  };
  if (bookings.length > 0) {
    var slot = resolveVenueWallCurrentNextByTime(bookings, nowMs);
    if (slot.mode === 'nextOnly' && slot.next) {
      var b = slot.next;
      currentTime = formatFloorRoomCardBookingTimeRange(b).trim();
      currentBookingDisplay = formatResourceWallNextBookingGuestLine(row, b).trim();
      if (!isAvailable) {
        statusPack = applyStatusFromPrimaryBooking(b, nowMs);
      } else {
        statusPack = {
          status: 'available',
          remainingMin: undefined,
          startsInMin: undefined,
          lateMin: undefined,
          sessionStartMs: undefined,
          sessionEndMs: undefined
        };
      }
      nextList = undefined;
      wallUseNextLabelHideNextRow = true;
    } else if (slot.mode === 'empty') {
      nextList = undefined;
      currentTime = '';
      currentBookingDisplay = 'Available to Book';
      statusPack = {
        status: 'available',
        remainingMin: undefined,
        startsInMin: undefined,
        lateMin: undefined,
        sessionStartMs: undefined,
        sessionEndMs: undefined
      };
    } else if (slot.current) {
      var primary = slot.current;
      var currentNotStarted = isFloorRoomCardBookingNotStarted(primary, nowMs);
      currentTime = formatFloorRoomCardBookingTimeRange(primary).trim();
      currentBookingDisplay = formatResourceWallNextBookingGuestLine(row, primary).trim();
      if (!isAvailable) {
        statusPack = applyStatusFromPrimaryBooking(primary, nowMs);
      } else {
        statusPack = {
          status: 'available',
          remainingMin: undefined,
          startsInMin: undefined,
          lateMin: undefined,
          sessionStartMs: undefined,
          sessionEndMs: undefined
        };
      }
      if (slot.next && !currentNotStarted) {
        nextList = [buildNextListEntry(row, slot.next, nowMs)];
      }
      if (currentNotStarted) {
        wallUseNextLabelHideNextRow = true;
      }
    }
  } else {
    var _row$time, _row$timeEnd;
    var _primary = getFloorRoomCardPrimaryBooking(roomData);
    var currentTimeFromPrimary = _primary ? formatFloorRoomCardBookingTimeRange(_primary).trim() : '';
    var start = String((_row$time = row.time) !== null && _row$time !== void 0 ? _row$time : '').trim();
    var end = String((_row$timeEnd = row.timeEnd) !== null && _row$timeEnd !== void 0 ? _row$timeEnd : '').trim();
    var currentTimeFallback = start && end ? "".concat(start.replace(/ .*/, ''), " - ").concat(end.replace(/ .*/, '')) : start || '';
    currentTime = currentTimeFromPrimary || currentTimeFallback;
    if (!isAvailable && _primary) {
      statusPack = applyStatusFromPrimaryBooking(_primary, nowMs);
    }
    currentBookingDisplay = isAvailable ? 'Available to Book' : formatResourceWallContactLine(row);
    nextList = undefined;
  }
  if (!currentTime && bookings.length === 0) {
    var _row$time2, _row$timeEnd2;
    var fbStart = String((_row$time2 = row.time) !== null && _row$time2 !== void 0 ? _row$time2 : '').trim();
    var fbEnd = String((_row$timeEnd2 = row.timeEnd) !== null && _row$timeEnd2 !== void 0 ? _row$timeEnd2 : '').trim();
    currentTime = fbStart && fbEnd ? "".concat(fbStart.replace(/ .*/, ''), " - ").concat(fbEnd.replace(/ .*/, '')) : fbStart || '';
  }
  return _objectSpread({
    resourceId: String(row.id),
    resource: row.code || row.main_field || String(row.id),
    area: row.area,
    status: statusPack.status,
    currentTime: currentTime,
    currentBooking: currentBookingDisplay,
    remainingMin: statusPack.remainingMin,
    startsInMin: statusPack.startsInMin,
    lateMin: statusPack.lateMin,
    sessionStartMs: statusPack.sessionStartMs,
    sessionEndMs: statusPack.sessionEndMs,
    nextList: nextList
  }, wallUseNextLabelHideNextRow ? {
    wallUseNextLabelHideNextRow: true
  } : {});
}