import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { buildDateTime } from "../../pisellSalesManagement/hooks/perspectiveUtils.js";
import { extractResourceRecordIds } from "./bookingToReservationTables.js";
import { mergeGridBookingSearchParams } from "./reservationDataUtils.js";
import dayjs from "dayjs";
//#region src/plus/pisellReservation/data/hudDrawerLocalListQuery.ts
/**
* HUD 抽屉内 Monitor 表：筛选/排序仅影响抽屉展示，不调父级 floorDay / grid 请求。
*/
/** 深拷贝筛参（无函数；与 RecordBoard searchParams 结构一致） */
function cloneHudDrawerSearchParams(params) {
	try {
		return JSON.parse(JSON.stringify(params !== null && params !== void 0 ? params : {}));
	} catch (_unused) {
		return _objectSpread2({}, params !== null && params !== void 0 ? params : {});
	}
}
/**
* 抽屉内去掉 Monitor 预约日期快筛；从 `filter.values` 移除对应键，避免本地列表仍按父级日期段收窄。
*/
function stripHudDrawerBookingDateQuickFilter(params) {
	const f = params.filter;
	if (typeof f !== "object" || f === null || Array.isArray(f)) return;
	const fo = f;
	const v = fo.values;
	if (typeof v !== "object" || v === null || Array.isArray(v)) return;
	const values = _objectSpread2({}, v);
	delete values.booking_time_start_between;
	params.filter = _objectSpread2(_objectSpread2({}, fo), {}, { values });
}
/**
* 合并抽屉内 onSearch 增量（与顶栏 Filter 行为对齐：filter.values 深合并）。
*/
function mergeHudDrawerSearchParams(prev, incoming) {
	const next = _objectSpread2(_objectSpread2({}, prev), incoming);
	const prevFilter = typeof prev.filter === "object" && prev.filter !== null ? prev.filter : {};
	if (typeof incoming.filter === "object" && incoming.filter !== null && !Array.isArray(incoming.filter)) {
		const incFilter = incoming.filter;
		const prevV = typeof prevFilter.values === "object" && prevFilter.values !== null && !Array.isArray(prevFilter.values) ? prevFilter.values : {};
		const incV = typeof incFilter.values === "object" && incFilter.values !== null && !Array.isArray(incFilter.values) ? incFilter.values : void 0;
		next.filter = _objectSpread2(_objectSpread2(_objectSpread2({}, prevFilter), incFilter), {}, { values: incV != null ? _objectSpread2(_objectSpread2({}, prevV), incV) : prevV });
	}
	return mergeGridBookingSearchParams(next);
}
function getRowStartMs(row) {
	const sa = row.start_at;
	if (typeof sa === "string" && sa) {
		const d = dayjs(sa);
		if (d.isValid()) return d.valueOf();
	}
	const ds = row.start_date;
	const ts = row.start_time;
	const comb = buildDateTime(ds, ts);
	if (comb) {
		const d = dayjs(comb);
		if (d.isValid()) return d.valueOf();
	}
	return 0;
}
function getRowEndMs(row) {
	const ea = row.end_at;
	if (typeof ea === "string" && ea) {
		const d = dayjs(ea);
		if (d.isValid()) return d.valueOf();
	}
	const de = row.end_date;
	const te = row.end_time;
	const comb = buildDateTime(de, te);
	if (comb) {
		const d = dayjs(comb);
		if (d.isValid()) return d.valueOf();
	}
	return 0;
}
function getRowCreatedMs(row) {
	const c = row.created_at;
	if (typeof c === "string" && c) {
		const d = dayjs(c);
		if (d.isValid()) return d.valueOf();
	}
	return 0;
}
function normalizeRangeBounds(raw) {
	if (!Array.isArray(raw) || raw.length < 2) return null;
	const a = dayjs(raw[0]);
	const b = dayjs(raw[1]);
	if (!a.isValid() || !b.isValid()) return null;
	const t0 = a.valueOf();
	const t1 = b.valueOf();
	return t0 <= t1 ? [t0, t1] : [t1, t0];
}
/** 与 Monitor filter 多选一致：有选项时才收窄 */
function multiSelectMatch(rowVals, selected) {
	if (!Array.isArray(selected) || selected.length === 0) return true;
	const set = new Set(selected.map((x) => String(x)));
	if (Array.isArray(rowVals)) return rowVals.some((x) => set.has(String(x)));
	if (rowVals == null || rowVals === "") return false;
	return set.has(String(rowVals));
}
/** numberRange：`{ min, max }`，null / 空 表示该端不限 */
function numberRangeContains(n, raw) {
	if (raw == null || typeof raw !== "object" || Array.isArray(raw)) return true;
	const o = raw;
	const minN = o.min != null && o.min !== "" ? Number(o.min) : NaN;
	const maxN = o.max != null && o.max !== "" ? Number(o.max) : NaN;
	const hasMin = Number.isFinite(minN);
	const hasMax = Number.isFinite(maxN);
	if (!hasMin && !hasMax) return true;
	if (!Number.isFinite(n)) return false;
	if (hasMin && n < minN) return false;
	if (hasMax && n > maxN) return false;
	return true;
}
function parseAmount(v) {
	if (v == null || v === "") return null;
	if (typeof v === "number" && Number.isFinite(v)) return v;
	const n = Number(String(v).replace(/,/g, "").trim());
	return Number.isFinite(n) ? n : null;
}
/** 与列表请求侧一致：partially_paid 与 unpaid 筛选项对齐 */
function paymentStatusForMatch(row) {
	var _order$payment_status;
	const order = row.order;
	const st = (_order$payment_status = order === null || order === void 0 ? void 0 : order.payment_status) !== null && _order$payment_status !== void 0 ? _order$payment_status : row.payment_status;
	const s = String(st !== null && st !== void 0 ? st : "").trim().toLowerCase();
	if (s === "partially_paid") return "unpaid";
	return s;
}
function rowMatchesKeyword(row, keyword) {
	const k = keyword.trim().toLowerCase();
	if (!k) return true;
	const acc = [];
	const push = (v) => {
		if (v == null) return;
		const s = String(v).toLowerCase().trim();
		if (s) acc.push(s);
	};
	push(row.id);
	push(row.booking_id);
	const order = row.order;
	if (order) {
		push(order.shop_full_order_number);
		push(order.note);
		const cust = order.customer;
		if (cust) {
			push(cust.name);
			push(cust.first_name);
			push(cust.last_name);
			push(cust.company_name);
		}
		const ci = order.contacts_info;
		if (ci) {
			push(ci.first_name);
			push(ci.last_name);
			push(ci.phone);
			push(ci.email);
		}
	}
	push(row.notes);
	return acc.some((p) => p.includes(k));
}
function rowMatchesValues(row, values) {
	const payment = values.order_payment_status;
	if (Array.isArray(payment) && payment.length > 0) {
		const st = paymentStatusForMatch(row);
		const allowed = new Set(payment.map((x) => String(x).toLowerCase()));
		if (st === "" || !allowed.has(st)) return false;
	}
	const appt = values.appointment_status;
	if (Array.isArray(appt) && appt.length > 0) {
		if (!multiSelectMatch(row.appointment_status, appt)) return false;
	}
	const orderStatus = values.order_status;
	if (Array.isArray(orderStatus) && orderStatus.length > 0) {
		var _order$order_status;
		const order = row.order;
		if (!multiSelectMatch((_order$order_status = order === null || order === void 0 ? void 0 : order.order_status) !== null && _order$order_status !== void 0 ? _order$order_status : order === null || order === void 0 ? void 0 : order.status, orderStatus)) return false;
	}
	const salesCh = values.order_sales_channel;
	if (Array.isArray(salesCh) && salesCh.length > 0) {
		const order = row.order;
		if (!multiSelectMatch(order === null || order === void 0 ? void 0 : order.order_sales_channel, salesCh)) return false;
	}
	const payMethod = values.payment_method;
	if (Array.isArray(payMethod) && payMethod.length > 0) {
		var _ref, _order$payment_method;
		const order = row.order;
		if (!multiSelectMatch((_ref = (_order$payment_method = order === null || order === void 0 ? void 0 : order.payment_method) !== null && _order$payment_method !== void 0 ? _order$payment_method : order === null || order === void 0 ? void 0 : order.pay_method) !== null && _ref !== void 0 ? _ref : order === null || order === void 0 ? void 0 : order.payment_methods, payMethod)) return false;
	}
	const custFilter = values.customer_id;
	if (Array.isArray(custFilter) && custFilter.length > 0) {
		var _order$customer_id, _ref2;
		const order = row.order;
		const cid = (_order$customer_id = order === null || order === void 0 ? void 0 : order.customer_id) !== null && _order$customer_id !== void 0 ? _order$customer_id : order === null || order === void 0 || (_ref2 = order.customer) === null || _ref2 === void 0 ? void 0 : _ref2.id;
		if (cid == null || !custFilter.map(String).includes(String(cid))) return false;
	}
	const formIds = values.form_record_ids;
	if (Array.isArray(formIds) && formIds.length > 0) {
		const need = new Set(formIds.map((x) => String(x)));
		if (!extractResourceRecordIds(row).some((id) => need.has(id))) return false;
	}
	const numBetween = values.number_between;
	if (numBetween != null && typeof numBetween === "object") {
		const party = typeof row.number === "number" && Number.isFinite(row.number) ? row.number : Number(row.number);
		if (!numberRangeContains(Number.isFinite(party) ? party : NaN, numBetween)) return false;
	}
	const order = row.order;
	const sum = order === null || order === void 0 ? void 0 : order.summary;
	const amtBetween = values.total_amount_between;
	if (amtBetween != null && typeof amtBetween === "object") {
		var _ref3, _parseAmount, _row$amount;
		const amt = (_ref3 = (_parseAmount = parseAmount(sum === null || sum === void 0 ? void 0 : sum.total_amount)) !== null && _parseAmount !== void 0 ? _parseAmount : parseAmount(order === null || order === void 0 ? void 0 : order.total_amount)) !== null && _ref3 !== void 0 ? _ref3 : parseAmount((_row$amount = row.amount) !== null && _row$amount !== void 0 ? _row$amount : row.total);
		if (amt == null || !numberRangeContains(amt, amtBetween)) return false;
	}
	const createdR = normalizeRangeBounds(values.created_at_between);
	if (createdR) {
		const cm = getRowCreatedMs(row);
		if (cm === 0) return false;
		const [t0, t1] = createdR;
		if (cm < t0 || cm > t1) return false;
	}
	const updatedRaw = row.updated_at;
	const updatedR = normalizeRangeBounds(values.updated_at_between);
	if (updatedR) {
		const u = typeof updatedRaw === "string" && updatedRaw ? dayjs(updatedRaw).valueOf() : 0;
		if (!u) return false;
		const [t0, t1] = updatedR;
		if (u < t0 || u > t1) return false;
	}
	const range = normalizeRangeBounds(values.booking_time_start_between);
	if (range) {
		const [t0, t1] = range;
		const startMs = getRowStartMs(row);
		if (startMs === 0) return false;
		if (startMs < t0 || startMs > t1) return false;
	}
	return true;
}
function applySort(rows, sortKey) {
	if (!sortKey || !String(sortKey).includes(":")) return rows;
	const [field, dir] = String(sortKey).split(":");
	const desc = dir === "desc";
	const list = [...rows];
	const pick = (r) => {
		switch (field) {
			case "start_at":
			case "after_execution_time": return getRowStartMs(r);
			case "end_at": return getRowEndMs(r);
			case "created_at": return getRowCreatedMs(r);
			default: return 0;
		}
	};
	list.sort((a, b) => {
		const da = pick(a);
		const db = pick(b);
		if (da === db) return 0;
		return desc ? db - da : da - db;
	});
	return list;
}
/**
* 在「画布资源子集」行上做 keyword + filter.values 本地过滤 + sort。
* 与 Monitor `getFilterButtonList` 常见项对齐（支付/预约态/订单态/渠道/人数/金额/资源/时间窗等）；未覆盖字段忽略。
*/
function applyHudDrawerLocalListQuery(rows, searchParams) {
	let out = rows;
	const kw = searchParams.keyword;
	if (typeof kw === "string" && kw.trim()) out = out.filter((r) => rowMatchesKeyword(r, kw));
	const filter = searchParams.filter;
	const values = filter && typeof filter === "object" && filter !== null && typeof filter.values === "object" && filter.values !== null && !Array.isArray(filter.values) ? filter.values : {};
	if (Object.keys(values).length > 0) out = out.filter((r) => rowMatchesValues(r, values));
	const sort = searchParams.sort;
	if (typeof sort === "string" && sort) out = applySort(out, sort);
	return out;
}
//#endregion
export { applyHudDrawerLocalListQuery, cloneHudDrawerSearchParams, mergeHudDrawerSearchParams, stripHudDrawerBookingDateQuickFilter };
