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; }
import dayjs from 'dayjs';
function normalizeHmsForDayjs(time) {
  var t = time.trim();
  var parts = t.split(':').map(function (p) {
    return p.trim();
  });
  if (parts.length >= 2) {
    var h = String(parts[0]).padStart(2, '0');
    var m = String(parts[1]).padStart(2, '0');
    var s = parts[2] != null ? String(parts[2]).padStart(2, '0') : '00';
    return "".concat(h, ":").concat(m, ":").concat(s);
  }
  return '00:00:00';
}
function bookingStartEndMs(startDate, startTime, endDate, endTime) {
  var s = dayjs("".concat(startDate, "T").concat(normalizeHmsForDayjs(startTime))).valueOf();
  var e = dayjs("".concat(endDate, "T").concat(normalizeHmsForDayjs(endTime))).valueOf();
  return {
    start: s,
    end: e
  };
}

/** 预约时段内进度 0–100（与 demo getProgressPercent 一致，使用真实时间） */
export function getFloorRoomCardProgressPercent(startDate, startTime, endDate, endTime) {
  var nowMs = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : Date.now();
  var _bookingStartEndMs = bookingStartEndMs(startDate, startTime, endDate, endTime),
    start = _bookingStartEndMs.start,
    end = _bookingStartEndMs.end;
  if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return 0;
  if (nowMs <= start) return 0;
  if (nowMs >= end) return 100;
  return Math.round((nowMs - start) / (end - start) * 100);
}

/**
 * 进度条百分比：优先宿主 `progressPercent`（0–100），否则按起止时间与当前时刻推算。
 */
export function resolveFloorRoomCardProgressPercent(booking) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var p = booking.progressPercent;
  if (p != null && Number.isFinite(p)) {
    return Math.min(100, Math.max(0, Math.round(p)));
  }
  return getFloorRoomCardProgressPercent(booking.start_date, booking.start_time, booking.end_date, booking.end_time, nowMs);
}

/** 将分钟数格式化为「10m」「1h 5m」等（图元迟到/超时展示） */
export function formatFloorRoomCardDurationMinutes(totalMin) {
  if (totalMin <= 0) return '0m';
  var h = Math.floor(totalMin / 60);
  var m = totalMin % 60;
  if (h > 0) return m > 0 ? "".concat(h, "h ").concat(m, "m") : "".concat(h, "h");
  return "".concat(m, "m");
}

/** 已超过结束时刻的加时时长文案 */
export function getFloorRoomCardOvertime(endDate, endTime) {
  var nowMs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Date.now();
  var _bookingStartEndMs2 = bookingStartEndMs(endDate, endTime, endDate, endTime),
    end = _bookingStartEndMs2.end;
  if (!Number.isFinite(end)) return null;
  var diffMin = Math.floor((nowMs - end) / 60000);
  if (diffMin <= 0) return null;
  return formatFloorRoomCardDurationMinutes(diffMin);
}

/** 已逾开始时刻的「迟到」时长 */
export function getFloorRoomCardLateTime(startDate, startTime) {
  var nowMs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Date.now();
  var _bookingStartEndMs3 = bookingStartEndMs(startDate, startTime, startDate, startTime),
    start = _bookingStartEndMs3.start;
  if (!Number.isFinite(start)) return null;
  var diffMin = Math.floor((nowMs - start) / 60000);
  if (diffMin <= 0) return null;
  return formatFloorRoomCardDurationMinutes(diffMin);
}

/** 距开始时刻的倒计时分钟（不含文案前缀）；仅本地起止时间推算 */
export function getFloorRoomCardArrivalMinutes(room) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var b = room.bookings[0];
  if (!b || room.status !== 'reserved') return null;
  var _bookingStartEndMs4 = bookingStartEndMs(b.start_date, b.start_time, b.end_date, b.end_time),
    start = _bookingStartEndMs4.start;
  if (!Number.isFinite(start)) return null;
  var diffMin = Math.floor((start - nowMs) / 60000);
  if (diffMin < 0) return null;
  return diffMin;
}

/**
 * 预留态「还有 n 分钟」：优先宿主 `remainingReserveTime`（分钟，>0），否则 {@link getFloorRoomCardArrivalMinutes}
 */
export function resolveFloorRoomCardReservedCountdownMinutes(room) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var b = room.bookings[0];
  if (!b || room.status !== 'reserved') return null;
  var r = b.remainingReserveTime;
  if (r != null && Number.isFinite(r)) {
    var n = Math.max(0, Math.round(r));
    if (n > 0) return n;
  }
  return getFloorRoomCardArrivalMinutes(room, nowMs);
}

/**
 * 多预约列表中单条：与 {@link resolveFloorRoomCardReservedCountdownMinutes} 一致，但针对当前行 booking。
 */
export function resolveFloorRoomCardReservedCountdownMinutesForBooking(booking) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var r = booking.remainingReserveTime;
  if (r != null && Number.isFinite(r)) {
    var n = Math.max(0, Math.round(r));
    if (n > 0) return n;
  }
  var _bookingStartEndMs5 = bookingStartEndMs(booking.start_date, booking.start_time, booking.end_date, booking.end_time),
    start = _bookingStartEndMs5.start;
  if (!Number.isFinite(start)) return null;
  var diffMin = Math.floor((start - nowMs) / 60000);
  if (diffMin < 0) return null;
  return diffMin;
}

/**
 * 紧凑多预约行：仅当该条 booking 有宿主 `lateTime`（分钟）时为 late，否则 not_arrived（不按本地时刻推算迟到）。
 */
export function getFloorRoomCardReservedRowBodyType(booking) {
  var _nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  if (booking.lateTime != null && Number.isFinite(booking.lateTime) && booking.lateTime > 0) {
    return 'late';
  }
  return 'not_arrived';
}
/** 当前时刻是否落在预约时段内 [start, end)（进行中） */
export function isFloorRoomCardBookingInProgress(booking) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var _bookingStartEndMs6 = bookingStartEndMs(booking.start_date, booking.start_time, booking.end_date, booking.end_time),
    start = _bookingStartEndMs6.start,
    end = _bookingStartEndMs6.end;
  if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return false;
  return nowMs >= start && nowMs < end;
}

/** 当前时刻是否在预约开始之前（未开始） */
export function isFloorRoomCardBookingNotStarted(booking) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var _bookingStartEndMs7 = bookingStartEndMs(booking.start_date, booking.start_time, booking.end_date, booking.end_time),
    start = _bookingStartEndMs7.start;
  if (!Number.isFinite(start)) return false;
  return nowMs < start;
}

/**
 * 第一条预约进行中且其后仍有未开始的时段：返回第一条「未开始」预约，用于 Next 行。
 * 不依赖 cardType（不必 late/timeout）。
 */
export function getFloorRoomCardNextNotStartedBooking(data) {
  var nowMs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
  var list = data.bookings;
  if (list.length < 2) return null;
  if (!isFloorRoomCardBookingInProgress(list[0], nowMs)) return null;
  for (var i = 1; i < list.length; i++) {
    if (isFloorRoomCardBookingNotStarted(list[i], nowMs)) return list[i];
  }
  return null;
}
function sortFloorRoomCardBookingsByStart(list) {
  return _toConsumableArray(list).sort(function (a, b) {
    var _bookingStartEndMs8 = bookingStartEndMs(a.start_date, a.start_time, a.end_date, a.end_time),
      as = _bookingStartEndMs8.start;
    var _bookingStartEndMs9 = bookingStartEndMs(b.start_date, b.start_time, b.end_date, b.end_time),
      bs = _bookingStartEndMs9.start;
    return as - bs;
  });
}

/**
 * 多条预约里恰好一条 `hostBookingStatus === 'occupied'` 时：把该条排到首位，便于标准占用卡用 bookings[0] 展示。
 * 多条同时为 occupied 或未标记 host 时不改顺序。
 */
export function reorderBookingsForSingleOccupiedPrimary(list) {
  if (list.length <= 1) return list;
  var occ = list.filter(function (b) {
    return b.hostBookingStatus === 'occupied';
  });
  if (occ.length !== 1) return list;
  var sorted = sortFloorRoomCardBookingsByStart(list);
  var occIdx = sorted.findIndex(function (b) {
    return b.hostBookingStatus === 'occupied';
  });
  if (occIdx < 0) return list;
  var primary = sorted[occIdx];
  /** 当前占用之后的时段在前，便于 bookings[1] 与「下一条」一致 */
  var after = sorted.slice(occIdx + 1);
  var before = sorted.slice(0, occIdx);
  return [primary].concat(_toConsumableArray(after), _toConsumableArray(before));
}

/**
 * 多条预约且仅一条为 occupied：按开始时间排序后，取占用段之后的下一条（用于 Next 行）。
 */
export function getFloorRoomCardNextAfterSingleOccupiedBooking(data) {
  var list = data.bookings;
  if (list.length < 2) return null;
  if (list.filter(function (b) {
    return b.hostBookingStatus === 'occupied';
  }).length !== 1) {
    return null;
  }
  var sorted = sortFloorRoomCardBookingsByStart(list);
  var i = sorted.findIndex(function (b) {
    return b.hostBookingStatus === 'occupied';
  });
  if (i < 0 || i >= sorted.length - 1) return null;
  return sorted[i + 1];
}

/**
 * 多条均为预留（无 occupied）：`bookings` 已按开始时间排好，主卡为 [0]，Next 为紧邻的下一条。
 */
export function getFloorRoomCardNextAfterPrimaryReserved(data) {
  var _data$bookings$;
  if (data.status !== 'reserved' || data.bookings.length < 2) return null;
  if (data.bookings.some(function (b) {
    return b.hostBookingStatus === 'occupied';
  })) {
    return null;
  }
  return (_data$bookings$ = data.bookings[1]) !== null && _data$bookings$ !== void 0 ? _data$bookings$ : null;
}

/**
 * 接口标记 `isNext` 的预约：按开始时间取第一条，供 Next 行展示。
 */
export function getFloorRoomCardExplicitNextBooking(data) {
  var _sortFloorRoomCardBoo;
  var marked = data.bookings.filter(function (b) {
    return b.isNext === true;
  });
  if (marked.length === 0) return null;
  return (_sortFloorRoomCardBoo = sortFloorRoomCardBookingsByStart(marked)[0]) !== null && _sortFloorRoomCardBoo !== void 0 ? _sortFloorRoomCardBoo : null;
}

/**
 * 主区域展示用：第一条非 `isNext`；若全部为 next 则回退首条。
 */
export function getFloorRoomCardPrimaryBooking(data) {
  var non = data.bookings.find(function (b) {
    return b.isNext !== true;
  });
  return non !== null && non !== void 0 ? non : data.bookings[0];
}

/**
 * 多条预约且均为预留态（host 为 reserved 或未标）：按开始时间排序，主卡只展示最近一档，其余走 Next。
 */
export function reorderBookingsAllReservedChronological(list) {
  if (list.length <= 1) return list;
  if (list.some(function (b) {
    return b.hostBookingStatus === 'occupied';
  })) return list;
  if (!list.every(function (b) {
    return b.hostBookingStatus == null || b.hostBookingStatus === 'reserved';
  })) {
    return list;
  }
  return sortFloorRoomCardBookingsByStart(list);
}

/** 与 demo getCardType 一致 */
export function getFloorRoomCardType(room) {
  if (room.status === 'locked') return 'locked';
  if (room.status === 'empty') return 'empty';
  var n = room.bookings.length;
  var occCount = room.bookings.filter(function (b) {
    return b.hostBookingStatus === 'occupied';
  }).length;
  if (n > 1) {
    /**
     * 多条、房间仍为预留且无任何占用段：默认多预约列表卡。
     * 例外：恰好 2 条且 1 条主展示 + 1 条带 `isNext` 时与「单条 + Next」一致，走标准卡（非 rc--multi）。
     */
    if (room.status === 'reserved' && occCount === 0) {
      var sorted = reorderBookingsAllReservedChronological(_toConsumableArray(room.bookings));
      var mainNonNext = sorted.filter(function (b) {
        return b.isNext !== true;
      });
      var nextMarked = sorted.filter(function (b) {
        return b.isNext === true;
      });
      var isSingleMainWithExplicitNext = sorted.length === 2 && mainNonNext.length === 1 && nextMarked.length === 1;
      if (!isSingleMainWithExplicitNext) {
        return 'multi_reserved';
      }
    }
    var withHost = room.bookings.filter(function (b) {
      return b.hostBookingStatus != null;
    });
    if (withHost.length > 0) {
      if (occCount >= 2) {
        return 'multi_occupied';
      }
      if (occCount === 1 && room.status === 'occupied') {
        var s = room.sub_status;
        if (s === 'payed' || s === 'payment_required' || s === 'timeout') return s;
        return 'payed';
      }
      if (withHost.every(function (b) {
        return b.hostBookingStatus === 'reserved';
      })) {
        var _s = room.sub_status;
        if (_s === 'not_arrived' || _s === 'late') return _s;
        return 'not_arrived';
      }
    }
    if (room.status === 'occupied') {
      var _s2 = room.sub_status;
      if (_s2 === 'payed' || _s2 === 'payment_required' || _s2 === 'timeout') return _s2;
      return 'payed';
    }
    if (room.status === 'reserved') {
      var _s3 = room.sub_status;
      if (_s3 === 'not_arrived' || _s3 === 'late') return _s3;
      return 'not_arrived';
    }
  }
  if (room.status === 'occupied') {
    var _s4 = room.sub_status;
    if (_s4 === 'payed' || _s4 === 'payment_required' || _s4 === 'timeout') return _s4;
    return 'payed';
  }
  if (room.status === 'reserved') {
    var _s5 = room.sub_status;
    if (_s5 === 'not_arrived' || _s5 === 'late') return _s5;
    return 'not_arrived';
  }
  return 'empty';
}

/**
 * 平面图 RoomCard 联系人手机号展示：与 {@link ReservationFloorRoomCard} ContactInfo 一致。
 */
export function maskPisellReservationPhoneTail(phone) {
  return phone.length >= 4 ? "***".concat(phone.slice(-4)) : null;
}

/**
 * 房间标题：优先数据行 `main_field` 展示名（` ## ` 前为主名称），其次 `code`，最后图元编辑名。
 * 与平面图 `reservationCards` 绑定桌位卡一致。
 */
export function displayRoomTitleFromRow(row, sceneElementName) {
  var _row$code;
  var rawMain = row.main_field;
  if (typeof rawMain === 'string' && rawMain.trim()) {
    var _rawMain$split$;
    var first = (_rawMain$split$ = rawMain.split(' ## ')[0]) === null || _rawMain$split$ === void 0 ? void 0 : _rawMain$split$.trim();
    if (first) return first;
  }
  var c = (_row$code = row.code) === null || _row$code === void 0 ? void 0 : _row$code.trim();
  if (c) return c;
  var n = sceneElementName === null || sceneElementName === void 0 ? void 0 : sceneElementName.trim();
  if (n) return n;
  return '';
}

/**
 * 展示用名称：`main_field` 按 ` ## ` 分段且有两段及以上时取**第二段**（常见「内部码 ## 展示名」），
 * 否则取第一段；再无则回退 {@link displayRoomTitleFromRow}。
 */
export function displayRoomShowNameFromRow(row, sceneElementName) {
  var rawMain = row.main_field;
  if (typeof rawMain === 'string' && rawMain.trim()) {
    var parts = rawMain.split(' ## ').map(function (p) {
      return p.trim();
    }).filter(function (p) {
      return p.length > 0;
    });
    if (parts.length >= 2) return parts[1];
    if (parts.length === 1) return parts[0];
  }
  return displayRoomTitleFromRow(row, sceneElementName);
}