import dayjs from "dayjs";
//#region src/plus/pisellReservation/floorRoomCard/floorRoomCardUtils.ts
function normalizeHmsForDayjs(time) {
	const parts = time.trim().split(":").map((p) => p.trim());
	if (parts.length >= 2) return `${String(parts[0]).padStart(2, "0")}:${String(parts[1]).padStart(2, "0")}:${parts[2] != null ? String(parts[2]).padStart(2, "0") : "00"}`;
	return "00:00:00";
}
function bookingStartEndMs(startDate, startTime, endDate, endTime) {
	return {
		start: dayjs(`${startDate}T${normalizeHmsForDayjs(startTime)}`).valueOf(),
		end: dayjs(`${endDate}T${normalizeHmsForDayjs(endTime)}`).valueOf()
	};
}
/** 预约时段内进度 0–100（与 demo getProgressPercent 一致，使用真实时间） */
function getFloorRoomCardProgressPercent(startDate, startTime, endDate, endTime, nowMs = Date.now()) {
	const { start, end } = bookingStartEndMs(startDate, startTime, endDate, endTime);
	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），否则按起止时间与当前时刻推算。
*/
function resolveFloorRoomCardProgressPercent(booking, nowMs = Date.now()) {
	const 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」等（图元迟到/超时展示） */
function formatFloorRoomCardDurationMinutes(totalMin) {
	if (totalMin <= 0) return "0m";
	const h = Math.floor(totalMin / 60);
	const m = totalMin % 60;
	if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`;
	return `${m}m`;
}
/** 距开始时刻的倒计时分钟（不含文案前缀）；仅本地起止时间推算 */
function getFloorRoomCardArrivalMinutes(room, nowMs = Date.now()) {
	const b = room.bookings[0];
	if (!b || room.status !== "reserved") return null;
	const { start } = bookingStartEndMs(b.start_date, b.start_time, b.end_date, b.end_time);
	if (!Number.isFinite(start)) return null;
	const diffMin = Math.floor((start - nowMs) / 6e4);
	if (diffMin < 0) return null;
	return diffMin;
}
/**
* 预留态「还有 n 分钟」：优先宿主 `remainingReserveTime`（分钟，>0），否则 {@link getFloorRoomCardArrivalMinutes}
*/
function resolveFloorRoomCardReservedCountdownMinutes(room, nowMs = Date.now()) {
	const b = room.bookings[0];
	if (!b || room.status !== "reserved") return null;
	const r = b.remainingReserveTime;
	if (r != null && Number.isFinite(r)) {
		const n = Math.max(0, Math.round(r));
		if (n > 0) return n;
	}
	return getFloorRoomCardArrivalMinutes(room, nowMs);
}
/**
* 多预约列表中单条：与 {@link resolveFloorRoomCardReservedCountdownMinutes} 一致，但针对当前行 booking。
*/
function resolveFloorRoomCardReservedCountdownMinutesForBooking(booking, nowMs = Date.now()) {
	const r = booking.remainingReserveTime;
	if (r != null && Number.isFinite(r)) {
		const n = Math.max(0, Math.round(r));
		if (n > 0) return n;
	}
	const { start } = bookingStartEndMs(booking.start_date, booking.start_time, booking.end_date, booking.end_time);
	if (!Number.isFinite(start)) return null;
	const diffMin = Math.floor((start - nowMs) / 6e4);
	if (diffMin < 0) return null;
	return diffMin;
}
/**
* 紧凑多预约行：仅当该条 booking 有宿主 `lateTime`（分钟）时为 late，否则 not_arrived（不按本地时刻推算迟到）。
*/
function getFloorRoomCardReservedRowBodyType(booking, _nowMs = Date.now()) {
	if (booking.lateTime != null && Number.isFinite(booking.lateTime) && booking.lateTime > 0) return "late";
	return "not_arrived";
}
/** 当前时刻是否落在预约时段内 [start, end)（进行中） */
function isFloorRoomCardBookingInProgress(booking, nowMs = Date.now()) {
	const { start, end } = bookingStartEndMs(booking.start_date, booking.start_time, booking.end_date, booking.end_time);
	if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return false;
	return nowMs >= start && nowMs < end;
}
/** 当前时刻是否在预约开始之前（未开始） */
function isFloorRoomCardBookingNotStarted(booking, nowMs = Date.now()) {
	const { start } = bookingStartEndMs(booking.start_date, booking.start_time, booking.end_date, booking.end_time);
	if (!Number.isFinite(start)) return false;
	return nowMs < start;
}
/**
* 第一条预约进行中且其后仍有未开始的时段：返回第一条「未开始」预约，用于 Next 行。
* 不依赖 cardType（不必 late/timeout）。
*/
function getFloorRoomCardNextNotStartedBooking(data, nowMs = Date.now()) {
	const list = data.bookings;
	if (list.length < 2) return null;
	if (!isFloorRoomCardBookingInProgress(list[0], nowMs)) return null;
	for (let i = 1; i < list.length; i++) if (isFloorRoomCardBookingNotStarted(list[i], nowMs)) return list[i];
	return null;
}
function sortFloorRoomCardBookingsByStart(list) {
	return [...list].sort((a, b) => {
		const { start: as } = bookingStartEndMs(a.start_date, a.start_time, a.end_date, a.end_time);
		const { start: bs } = bookingStartEndMs(b.start_date, b.start_time, b.end_date, b.end_time);
		return as - bs;
	});
}
/**
* 多条预约里恰好一条 `hostBookingStatus === 'occupied'` 时：把该条排到首位，便于标准占用卡用 bookings[0] 展示。
* 多条同时为 occupied 或未标记 host 时不改顺序。
*/
function reorderBookingsForSingleOccupiedPrimary(list) {
	if (list.length <= 1) return list;
	if (list.filter((b) => b.hostBookingStatus === "occupied").length !== 1) return list;
	const sorted = sortFloorRoomCardBookingsByStart(list);
	const occIdx = sorted.findIndex((b) => b.hostBookingStatus === "occupied");
	if (occIdx < 0) return list;
	const primary = sorted[occIdx];
	/** 当前占用之后的时段在前，便于 bookings[1] 与「下一条」一致 */
	const after = sorted.slice(occIdx + 1);
	const before = sorted.slice(0, occIdx);
	return [
		primary,
		...after,
		...before
	];
}
/**
* 多条预约且仅一条为 occupied：按开始时间排序后，取占用段之后的下一条（用于 Next 行）。
*/
function getFloorRoomCardNextAfterSingleOccupiedBooking(data) {
	const list = data.bookings;
	if (list.length < 2) return null;
	if (list.filter((b) => b.hostBookingStatus === "occupied").length !== 1) return null;
	const sorted = sortFloorRoomCardBookingsByStart(list);
	const i = sorted.findIndex((b) => b.hostBookingStatus === "occupied");
	if (i < 0 || i >= sorted.length - 1) return null;
	return sorted[i + 1];
}
/**
* 多条均为预留（无 occupied）：`bookings` 已按开始时间排好，主卡为 [0]，Next 为紧邻的下一条。
*/
function getFloorRoomCardNextAfterPrimaryReserved(data) {
	var _data$bookings$;
	if (data.status !== "reserved" || data.bookings.length < 2) return null;
	if (data.bookings.some((b) => b.hostBookingStatus === "occupied")) return null;
	return (_data$bookings$ = data.bookings[1]) !== null && _data$bookings$ !== void 0 ? _data$bookings$ : null;
}
/**
* 接口标记 `isNext` 的预约：按开始时间取第一条，供 Next 行展示。
*/
function getFloorRoomCardExplicitNextBooking(data) {
	var _sortFloorRoomCardBoo;
	const marked = data.bookings.filter((b) => b.isNext === true);
	if (marked.length === 0) return null;
	return (_sortFloorRoomCardBoo = sortFloorRoomCardBookingsByStart(marked)[0]) !== null && _sortFloorRoomCardBoo !== void 0 ? _sortFloorRoomCardBoo : null;
}
/**
* 主区域展示用：第一条非 `isNext`；若全部为 next 则回退首条。
*/
function getFloorRoomCardPrimaryBooking(data) {
	const non = data.bookings.find((b) => b.isNext !== true);
	return non !== null && non !== void 0 ? non : data.bookings[0];
}
/**
* 多条预约且均为预留态（host 为 reserved 或未标）：按开始时间排序，主卡只展示最近一档，其余走 Next。
*/
function reorderBookingsAllReservedChronological(list) {
	if (list.length <= 1) return list;
	if (list.some((b) => b.hostBookingStatus === "occupied")) return list;
	if (!list.every((b) => b.hostBookingStatus == null || b.hostBookingStatus === "reserved")) return list;
	return sortFloorRoomCardBookingsByStart(list);
}
/** 与 demo getCardType 一致 */
function getFloorRoomCardType(room) {
	if (room.status === "locked") return "locked";
	if (room.status === "empty") return "empty";
	const n = room.bookings.length;
	const occCount = room.bookings.filter((b) => b.hostBookingStatus === "occupied").length;
	if (n > 1) {
		/**
		* 多条、房间仍为预留且无任何占用段：默认多预约列表卡。
		* 例外：恰好 2 条且 1 条主展示 + 1 条带 `isNext` 时与「单条 + Next」一致，走标准卡（非 rc--multi）。
		*/
		if (room.status === "reserved" && occCount === 0) {
			const sorted = reorderBookingsAllReservedChronological([...room.bookings]);
			const mainNonNext = sorted.filter((b) => b.isNext !== true);
			const nextMarked = sorted.filter((b) => b.isNext === true);
			if (!(sorted.length === 2 && mainNonNext.length === 1 && nextMarked.length === 1)) return "multi_reserved";
		}
		const withHost = room.bookings.filter((b) => b.hostBookingStatus != null);
		if (withHost.length > 0) {
			if (occCount >= 2) return "multi_occupied";
			if (occCount === 1 && room.status === "occupied") {
				const s = room.sub_status;
				if (s === "payed" || s === "payment_required" || s === "timeout") return s;
				return "payed";
			}
			if (withHost.every((b) => b.hostBookingStatus === "reserved")) {
				const s = room.sub_status;
				if (s === "not_arrived" || s === "late") return s;
				return "not_arrived";
			}
		}
		if (room.status === "occupied") {
			const s = room.sub_status;
			if (s === "payed" || s === "payment_required" || s === "timeout") return s;
			return "payed";
		}
		if (room.status === "reserved") {
			const s = room.sub_status;
			if (s === "not_arrived" || s === "late") return s;
			return "not_arrived";
		}
	}
	if (room.status === "occupied") {
		const s = room.sub_status;
		if (s === "payed" || s === "payment_required" || s === "timeout") return s;
		return "payed";
	}
	if (room.status === "reserved") {
		const s = room.sub_status;
		if (s === "not_arrived" || s === "late") return s;
		return "not_arrived";
	}
	return "empty";
}
/**
* 平面图 RoomCard 联系人手机号展示：与 {@link ReservationFloorRoomCard} ContactInfo 一致。
*/
function maskPisellReservationPhoneTail(phone) {
	return phone.length >= 4 ? `***${phone.slice(-4)}` : null;
}
/**
* 房间标题：优先数据行 `main_field` 展示名（` ## ` 前为主名称），其次 `code`，最后图元编辑名。
* 与平面图 `reservationCards` 绑定桌位卡一致。
*/
function displayRoomTitleFromRow(row, sceneElementName) {
	var _row$code;
	const rawMain = row.main_field;
	if (typeof rawMain === "string" && rawMain.trim()) {
		var _rawMain$split$;
		const first = (_rawMain$split$ = rawMain.split(" ## ")[0]) === null || _rawMain$split$ === void 0 ? void 0 : _rawMain$split$.trim();
		if (first) return first;
	}
	const c = (_row$code = row.code) === null || _row$code === void 0 ? void 0 : _row$code.trim();
	if (c) return c;
	const n = sceneElementName === null || sceneElementName === void 0 ? void 0 : sceneElementName.trim();
	if (n) return n;
	return "";
}
//#endregion
export { displayRoomTitleFromRow, formatFloorRoomCardDurationMinutes, getFloorRoomCardExplicitNextBooking, getFloorRoomCardNextAfterPrimaryReserved, getFloorRoomCardNextAfterSingleOccupiedBooking, getFloorRoomCardNextNotStartedBooking, getFloorRoomCardPrimaryBooking, getFloorRoomCardReservedRowBodyType, getFloorRoomCardType, maskPisellReservationPhoneTail, reorderBookingsAllReservedChronological, reorderBookingsForSingleOccupiedPrimary, resolveFloorRoomCardProgressPercent, resolveFloorRoomCardReservedCountdownMinutes, resolveFloorRoomCardReservedCountdownMinutesForBooking };
