import { customerBrief, extractResourceRecordIds, isMonitorScheduleBookingSkipped } from "./bookingToReservationTables.js";
import { sceneElementsToBoundRecordIdStrings } from "../floorMap/floorMapBoundRecordIds.js";
import dayjs from "dayjs";
//#region src/plus/pisellReservation/data/calendarAdapter.ts
/**
* 画布日历：sceneElements 顺序资源行 + floorDayBooking 列表 → RecordBoard 日历受控数据。
*/
function parseBookingStart(b) {
	const raw = b.start_at || (b.start_date && b.start_time ? `${b.start_date} ${b.start_time}` : "");
	if (!raw) return null;
	const d = dayjs(raw);
	return d.isValid() ? d : null;
}
function parseBookingEnd(b) {
	const raw = b.end_at || (b.end_date && b.end_time ? `${b.end_date} ${b.end_time}` : "");
	if (!raw) return null;
	const d = dayjs(raw);
	return d.isValid() ? d : null;
}
function calendarDisplayEnd(b, start) {
	var _ref, _ref2, _b$status;
	const explicit = parseBookingEnd(b);
	if (explicit) return explicit;
	const st = String((_ref = (_ref2 = (_b$status = b.status) !== null && _b$status !== void 0 ? _b$status : b.booking_status) !== null && _ref2 !== void 0 ? _ref2 : b.order_status) !== null && _ref !== void 0 ? _ref : "").trim().toLowerCase();
	if (st === "occupied" || st === "locked") return start.endOf("day");
	return start.add(2, "hour");
}
function isAggregateParentShell(booking) {
	const meta = booking.metadata;
	if ((meta === null || meta === void 0 ? void 0 : meta.multiple_resource_flag) !== 1) return false;
	const uid = booking.product_uid;
	if (uid != null && String(uid) !== "") return false;
	const res = booking.resources;
	return !Array.isArray(res) || res.length === 0;
}
function statusToCalendarTag(b) {
	var _ref3, _ref4, _b$status2;
	const st = String((_ref3 = (_ref4 = (_b$status2 = b.status) !== null && _b$status2 !== void 0 ? _b$status2 : b.booking_status) !== null && _ref4 !== void 0 ? _ref4 : b.order_status) !== null && _ref3 !== void 0 ? _ref3 : "").trim().toLowerCase();
	if (st === "locked") return "block";
	if (st === "occupied") return "checked_in";
	if (st === "reserved") {
		var _b$reserved_status;
		if (String((_b$reserved_status = b.reserved_status) !== null && _b$reserved_status !== void 0 ? _b$reserved_status : "") === "late") return "late";
		return "new";
	}
}
function fractionHourOf(d, dayStart) {
	return d.diff(dayStart, "minute", true) / 60;
}
/** 日历浮点小时 → dayjs（与 RecordBoard `dayAndHourToDayjs` 一致） */
function dayjsFromCalendarHour(dateStr, hourFloat) {
	const h = Math.floor(hourFloat);
	const m = Math.round((hourFloat - h) * 60);
	const mm = Math.min(59, Math.max(0, m));
	return dayjs(`${dateStr} ${String(h).padStart(2, "0")}:${String(mm).padStart(2, "0")}`, "YYYY-MM-DD HH:mm");
}
/** 与 {@link sceneElementsToBoundRecordIdStrings} 同序：画布已绑定资源 id（string），与预约 `relation_id` 对齐 */
function orderedCanvasResourceRecordIdStrings(sceneElements, gridDataSourceKey) {
	return sceneElementsToBoundRecordIdStrings(sceneElements, gridDataSourceKey);
}
function buildCalendarResourcesFromMergedTables(options) {
	const { orderedResourceIds, tables } = options;
	const byId = new Map(tables.map((r) => [String(r.id), r]));
	return orderedResourceIds.map((id) => {
		const row = byId.get(id);
		return {
			id,
			name: (row === null || row === void 0 ? void 0 : row.code) || (row === null || row === void 0 ? void 0 : row.main_field) || id,
			groupType: row === null || row === void 0 ? void 0 : row.area,
			form_id: id
		};
	});
}
/**
* 在合并后的 `tables` 中查找与宿主 raw booking 对应的行（用于详情弹窗）。
*/
function findMergedTableRowForBookingRaw(raw, tables) {
	var _ref5, _ref6, _raw$booking_id;
	const bid = String((_ref5 = (_ref6 = (_raw$booking_id = raw.booking_id) !== null && _raw$booking_id !== void 0 ? _raw$booking_id : raw.booking_uid) !== null && _ref6 !== void 0 ? _ref6 : raw.id) !== null && _ref5 !== void 0 ? _ref5 : "").trim();
	if (!bid) return void 0;
	for (const row of tables) {
		const list = row.floorMapSourceBookings;
		if (!Array.isArray(list)) continue;
		if (list.some((bk) => {
			var _r$id, _r$booking_id, _r$booking_uid;
			const r = bk;
			const id = String((_r$id = r.id) !== null && _r$id !== void 0 ? _r$id : "").trim();
			const bookingId = String((_r$booking_id = r.booking_id) !== null && _r$booking_id !== void 0 ? _r$booking_id : "").trim();
			const bookingUid = String((_r$booking_uid = r.booking_uid) !== null && _r$booking_uid !== void 0 ? _r$booking_uid : "").trim();
			return id === bid || bookingId === bid || bookingUid === bid;
		})) return row;
	}
}
/**
* 在已匹配到的 `tableRow.floorMapSourceBookings` 中取出与 `raw` 同一条预约的那条数据（引用随合并刷新）。
* 供详情弹窗在收到实时推送、合并 tables 后同步更新内容。
*/
function extractFloorMapSourceBookingForRow(raw, row) {
	var _ref7, _ref8, _raw$booking_id2;
	const bid = String((_ref7 = (_ref8 = (_raw$booking_id2 = raw.booking_id) !== null && _raw$booking_id2 !== void 0 ? _raw$booking_id2 : raw.booking_uid) !== null && _ref8 !== void 0 ? _ref8 : raw.id) !== null && _ref7 !== void 0 ? _ref7 : "").trim();
	if (!bid) return void 0;
	const list = row.floorMapSourceBookings;
	if (!Array.isArray(list)) return void 0;
	for (const bk of list) {
		var _r$id2, _r$booking_id2, _r$booking_uid2;
		if (!bk || typeof bk !== "object") continue;
		const r = bk;
		const id = String((_r$id2 = r.id) !== null && _r$id2 !== void 0 ? _r$id2 : "").trim();
		const bookingId = String((_r$booking_id2 = r.booking_id) !== null && _r$booking_id2 !== void 0 ? _r$booking_id2 : "").trim();
		const bookingUid = String((_r$booking_uid2 = r.booking_uid) !== null && _r$booking_uid2 !== void 0 ? _r$booking_uid2 : "").trim();
		if (id === bid || bookingId === bid || bookingUid === bid) return r;
	}
}
/**
* 将 GET booking 列表（与 floorDayBookingData 一致）映射为日历条；仅画布已绑定资源。
*/
function mapFloorDayBookingsToCalendarItems(options) {
	const { bookings, canvasResourceIdSet } = options;
	if (!Array.isArray(bookings)) return [];
	/** 集合为空时不再按画布过滤（与顶栏「tables 回退列 id」等策略一致，避免交集被误杀） */
	const filterByCanvas = canvasResourceIdSet.size > 0;
	const out = [];
	let seq = 0;
	for (const raw of bookings) {
		var _ref9, _b$relation_form_name, _ref10, _b$phone, _ref11, _b$booking_id, _ref12, _ref13, _b$status3;
		if (!raw || typeof raw !== "object") continue;
		const b = raw;
		if (isMonitorScheduleBookingSkipped(b)) continue;
		if (isAggregateParentShell(b)) continue;
		const rids = extractResourceRecordIds(b).filter((id) => filterByCanvas ? canvasResourceIdSet.has(id) : Boolean(id));
		if (rids.length === 0) continue;
		const start = parseBookingStart(b);
		if (!start) continue;
		const end = calendarDisplayEnd(b, start);
		const name = customerBrief(b) || String((_ref9 = (_b$relation_form_name = b.relation_form_name) !== null && _b$relation_form_name !== void 0 ? _b$relation_form_name : b.booking_id) !== null && _ref9 !== void 0 ? _ref9 : "Booking");
		const phoneRaw = (_ref10 = (_b$phone = b.phone) !== null && _b$phone !== void 0 ? _b$phone : b.mobile) !== null && _ref10 !== void 0 ? _ref10 : b.customer_phone;
		const phone = typeof phoneRaw === "string" ? phoneRaw : void 0;
		const statusTag = statusToCalendarTag(b);
		const baseId = String((_ref11 = (_b$booking_id = b.booking_id) !== null && _b$booking_id !== void 0 ? _b$booking_id : b.id) !== null && _ref11 !== void 0 ? _ref11 : `bk_${seq++}`);
		const kind = String((_ref12 = (_ref13 = (_b$status3 = b.status) !== null && _b$status3 !== void 0 ? _b$status3 : b.booking_status) !== null && _ref13 !== void 0 ? _ref13 : b.order_status) !== null && _ref12 !== void 0 ? _ref12 : "").trim().toLowerCase() === "locked" ? "block" : "booking";
		for (const courtId of rids) {
			let dayCursor = start.startOf("day");
			const lastDay = end.startOf("day");
			while (!dayCursor.isAfter(lastDay)) {
				const dayStart = dayCursor.startOf("day");
				const dayEnd = dayCursor.endOf("day");
				const segStart = start.isAfter(dayStart) ? start : dayStart;
				const segEnd = end.isBefore(dayEnd) ? end : dayEnd;
				if (!segEnd.isAfter(segStart)) {
					dayCursor = dayCursor.add(1, "day");
					continue;
				}
				const startHour = fractionHourOf(segStart, dayStart);
				const endHour = fractionHourOf(segEnd, dayStart);
				const dateStr = dayStart.format("YYYY-MM-DD");
				out.push({
					id: `${baseId}_${courtId}_${dateStr}`,
					courtId,
					date: dateStr,
					startHour,
					endHour,
					name,
					kind,
					phone,
					statusTag,
					raw: b
				});
				dayCursor = dayCursor.add(1, "day");
			}
		}
	}
	return out;
}
//#endregion
export { buildCalendarResourcesFromMergedTables, dayjsFromCalendarHour, extractFloorMapSourceBookingForRow, findMergedTableRowForBookingRaw, mapFloorDayBookingsToCalendarItems, orderedCanvasResourceRecordIdStrings };
