import { t as e } from "../chunks/ui.module-DHVTOqZ0.js";
import { n as t } from "../chunks/button-BsvHGWPc.js";
import { c as n, g as r, h as i } from "../chunks/misc-aGQBhywJ.js";
import { o as a } from "../chunks/flex-C7njxZ74.js";
import { r as o } from "../chunks/grid-dI94AAbi.js";
import { a as s, i as c, n as l, r as u } from "../chunks/modal-DLRYn-Lr.js";
import { n as d, t as f } from "../chunks/badge-DMM8cOHd.js";
import { d as p, f as m } from "../chunks/input-CCdBtl-C.js";
import { t as h } from "../chunks/input-search-Ca8iqeK2.js";
import { n as g } from "../chunks/multi-select-Bs1GU5MD.js";
import { t as _ } from "../chunks/table-DOwANXnt.js";
import { useCallback as v, useMemo as y, useState as b } from "react";
import { odataQueryFn as x, useODataTableColumns as S } from "@ryuzaki13/react-foundation-api/odata";
import { createFilterContains as C, createFilterEqual as w, unwrapODataQueryResult as T } from "@ryuzaki13/react-foundation-lib/odata-service";
import { useInfiniteQuery as E, useQuery as D } from "@tanstack/react-query";
import { cn as O, stableStringify as k } from "@ryuzaki13/react-foundation-lib/utils";
import { Fragment as A, jsx as j, jsxs as M } from "react/jsx-runtime";
import { ChevronRightIcon as N, XIcon as P } from "lucide-react";
//#region src/advanced-search/lib/searchParts.ts
function F(e) {
	let t = e.trim();
	return t ? t.split("*").map((e) => e.trim()).filter((e) => e.length) : [];
}
function I(e, t, n) {
	let r = t.map((e) => e.toLowerCase());
	return e.filter((e) => {
		for (let t of n) {
			let n = String(e[t] || "").toLowerCase(), i = 0, a = !0;
			for (let e of r) {
				let t = n.indexOf(e, i);
				if (t === -1) {
					a = !1;
					break;
				}
				i = t + e.length;
			}
			if (a) return !0;
		}
		return !1;
	});
}
//#endregion
//#region src/advanced-search/model/useAdvancedSearch.ts
var L = 50;
function R(e) {
	let [t, n] = b(""), [r, i] = b(() => Object.keys(e.segments ?? {}).reduce((e, t) => (e[t] = [], e), {})), a = F(t), o = a.length > 1, s = o ? 5e3 : L, c = E({
		queryKey: [
			"search",
			e.odata.service,
			e.odata.target,
			r,
			t
		],
		queryFn: async ({ pageParam: t = 0, signal: n, client: i }) => {
			let c = e.columns.map((e) => e.key), l = await x({
				odata: {
					service: e.odata.service,
					target: e.odata.target
				},
				options: {
					top: s,
					skip: t,
					select: c,
					expression: {
						and: !0,
						filters: [{ filters: a ? e.searchKeys.map((e) => ({ filters: a.map((t) => C(e, t)) })) : [] }, {
							and: !0,
							filters: Object.keys(r).map((e) => w(e, r[e]))
						}]
					},
					sorts: [{ key: e.leadingKey }]
				}
			})({
				signal: n,
				client: i
			});
			return o ? I(l.data, a, e.searchKeys) : l.data;
		},
		getNextPageParam: (e, t) => {
			if (!(e.length < s)) return t.length * s;
		},
		initialPageParam: 0
	}), l = v((e) => {
		n(e);
	}, []), u = v(() => {
		n("");
	}, []);
	return {
		query: c,
		items: y(() => c.data?.pages.flatMap((e) => e) ?? [], [c.data?.pages]),
		searchTerm: t,
		setSearch: l,
		clearSearch: u,
		filters: r,
		setFilters: i
	};
}
//#endregion
//#region src/advanced-search/model/useAdvancedSearchInitialSelected.ts
function z(e, t = []) {
	let n = D({
		queryKey: [
			"searchSelected",
			e.odata.service,
			e.odata.target,
			t
		],
		queryFn: async ({ client: n, signal: r }) => {
			if (t.length === 0) return {
				data: [],
				totalCount: void 0
			};
			let i = e.columns.map((e) => e.key);
			return await x({
				odata: {
					service: e.odata.service,
					target: e.odata.target
				},
				options: {
					select: i,
					expression: { filters: t.map((t) => w(e.leadingKey, t)) }
				}
			})({
				client: n,
				signal: r
			});
		},
		enabled: t.length > 0
	});
	return T(n);
}
//#endregion
//#region src/advanced-search/model/useAdvancedSearchSelection.ts
function B(e, t) {
	let n = /* @__PURE__ */ new Map();
	for (let r of e) n.set(String(r[t]), r);
	return Array.from(n.values());
}
function V(e, t = []) {
	let [n, r] = b(() => B(t, e.leadingKey)), i = v((t, n) => {
		if (t.length !== n.length) return !1;
		let r = new Set(n.map((t) => String(t[e.leadingKey])));
		return t.every((t) => r.has(String(t[e.leadingKey])));
	}, [e.leadingKey]), a = v((t) => {
		r((n) => {
			let r = B(t, e.leadingKey);
			return i(n, r) ? n : r;
		});
	}, [i, e.leadingKey]);
	return {
		selectedItems: n,
		select: v((t) => {
			r((n) => n.some((n) => n[e.leadingKey] === t[e.leadingKey]) ? n : [...n, t]);
		}, [e.leadingKey]),
		deselect: v((t) => {
			r((n) => n.filter((n) => n[e.leadingKey] !== t));
		}, [e.leadingKey]),
		replaceSelection: a,
		clearSelection: v(() => {
			r([]);
		}, []),
		isSelected: v((t) => n.some((n) => n[e.leadingKey] === t), [e.leadingKey, n])
	};
}
//#endregion
//#region src/advanced-search/ui/AdvancedSearchModalSession.tsx
function H({ onClose: e, onItemsSelect: r, title: i, config: p, initialSelectedItems: m }) {
	let b = y(() => p.columns.map((e) => ({
		id: e.key,
		accessorKey: e.key,
		header: e.label,
		meta: { width: e.width || "auto" }
	})), [p.columns]), { columns: x, isLoading: C } = S({
		service: p.odata.service,
		target: p.odata.target,
		mode: "enrich",
		columns: b
	}), { query: w, items: T, searchTerm: E, setSearch: D, clearSearch: O, filters: k, setFilters: A } = R(p), { selectedItems: N, deselect: P, replaceSelection: F } = V(p, m), I = v((e) => String(e[p.leadingKey]), [p.leadingKey]), L = y(() => N.map((e) => String(e[p.leadingKey])), [N, p.leadingKey]), z = y(() => new Set(T.map((e) => String(e[p.leadingKey]))), [T, p.leadingKey]), B = v(() => {
		w.hasNextPage && !w.isFetchingNextPage && w.fetchNextPage();
	}, [w]), H = v((e) => {
		let t = new Set(e.map((e) => String(e[p.leadingKey]))), n = N.filter((e) => !z.has(String(e[p.leadingKey]))), r = T.filter((e) => t.has(String(e[p.leadingKey])));
		F([...n, ...r]);
	}, [
		p.leadingKey,
		T,
		F,
		N,
		z
	]), U = v((e) => {
		P(String(e[p.leadingKey]));
	}, [p.leadingKey, P]), W = v(() => {
		r(N), e();
	}, [
		N,
		r,
		e
	]), G = y(() => {
		if ("segments" in p && p.segments) {
			let e = Object.keys(p.segments);
			if (e.length) return {
				odata: {
					...p.odata,
					limitedKeys: e
				},
				segments: p.segments,
				model: p.model
			};
		}
	}, [p]);
	return /* @__PURE__ */ M(l, {
		isOpen: !0,
		onClose: e,
		title: i || p.title,
		size: "lg",
		height: "min(50em, 80dvh)",
		children: [
			/* @__PURE__ */ j(s, { children: /* @__PURE__ */ M(a, {
				gap: "sm",
				children: [G && /* @__PURE__ */ j(g, {
					odata: G.odata,
					segments: G.segments,
					model: G.model,
					values: k,
					onChange: A
				}), /* @__PURE__ */ j(h, {
					size: "md",
					placeholder: p.searchLabel ?? "Введите поисковый запрос",
					value: E,
					onChange: D,
					onClear: O,
					className: "flexGrow"
				})]
			}) }),
			/* @__PURE__ */ j(u, { children: /* @__PURE__ */ M(o, {
				gap: "md",
				templateRows: "1fr auto",
				className: "h100",
				children: [/* @__PURE__ */ j(_, {
					columns: x,
					data: T,
					selectionMode: "multi",
					selectedRowIds: L,
					getRowId: I,
					isLoading: w.isLoading || C,
					isFetching: w.isFetching,
					onRowSelectionChange: H,
					onReachEnd: B,
					className: "w100"
				}), /* @__PURE__ */ j("div", {
					className: "marginBlockMd border",
					children: /* @__PURE__ */ j(n, {
						className: "paddingSm",
						height: "6em",
						children: /* @__PURE__ */ j(f, { children: N.map((e) => /* @__PURE__ */ j(d, {
							size: "md",
							tone: "info",
							appearance: "outline",
							onRemove: () => U(e),
							children: p.leadingText && e[p.leadingText] || e[p.leadingKey]
						}, e[p.leadingKey])) })
					})
				})]
			}) }),
			/* @__PURE__ */ M(c, { children: [/* @__PURE__ */ j(t, {
				onClick: e,
				children: "Отмена"
			}), /* @__PURE__ */ j(t, {
				variant: "successOutline",
				onClick: W,
				children: "Выбрать"
			})] })
		]
	});
}
//#endregion
//#region src/advanced-search/ui/AdvancedSearchModal.tsx
function U(e, t) {
	return k({
		leadingKey: String(e.leadingKey),
		service: e.odata.service,
		target: e.odata.target,
		selectedIds: t.map((t) => String(t[e.leadingKey])).sort()
	});
}
function W({ onClose: e, onItemsSelect: n, initialSelection: a, title: o, config: s }) {
	return a.status === "ready" ? /* @__PURE__ */ j(H, {
		title: o,
		config: s,
		onClose: e,
		onItemsSelect: n,
		initialSelectedItems: a.items
	}, U(s, a.items)) : /* @__PURE__ */ M(l, {
		isOpen: !0,
		onClose: e,
		title: o || s.title,
		size: "lg",
		height: "min(50em, 80dvh)",
		children: [/* @__PURE__ */ j(u, { children: a.status === "loading" ? /* @__PURE__ */ j(i, { text: "Загружаем выбранные элементы..." }) : /* @__PURE__ */ j(r, {
			color: "error",
			children: "Не удалось загрузить выбранные элементы"
		}) }), /* @__PURE__ */ j(c, { children: /* @__PURE__ */ j(t, {
			onClick: e,
			children: "Закрыть"
		}) })]
	});
}
//#endregion
//#region src/advanced-search/ui/AdvancedSearchSelectUI.tsx
var G = ({ label: t, description: n, disabled: r, size: i, placeholder: o = "Выбрать", token: s, onOpen: c, onClear: l }) => {
	let { controlId: u, labelId: d, descriptionId: f } = p({
		hasLabel: t != null,
		hasDescription: !!n
	}), h = !!s;
	return /* @__PURE__ */ M("div", {
		"aria-disabled": r || void 0,
		className: O(e.uiElement, e.uiSizable, i && e[i]),
		children: [
			t && /* @__PURE__ */ j("label", {
				id: d,
				htmlFor: u,
				className: e.uiLabel,
				children: t
			}),
			n && /* @__PURE__ */ j("p", {
				id: f,
				className: e.uiDescription,
				children: n
			}),
			/* @__PURE__ */ M("div", {
				className: e.uiInputContainer,
				children: [/* @__PURE__ */ j("div", {
					className: e.uiInputWithToggle,
					children: !h && /* @__PURE__ */ j(a, {
						align: "center",
						className: "h100",
						children: /* @__PURE__ */ j("div", {
							className: e.uiPlaceholder,
							children: o
						})
					})
				}), /* @__PURE__ */ j("div", {
					className: m.controlEndAdornment,
					children: /* @__PURE__ */ M("div", {
						className: e.uiToggleButtonContainer,
						children: [
							/* @__PURE__ */ j("div", {
								className: "flexEllipsis",
								style: { maxWidth: "100%" },
								children: s
							}),
							/* @__PURE__ */ j("button", {
								type: "button",
								disabled: !s,
								className: e.uiClearButton,
								onClick: l,
								"aria-label": "Очистить все",
								children: /* @__PURE__ */ j(P, {})
							}),
							/* @__PURE__ */ j("div", { className: e.uiButtonSeparator }),
							/* @__PURE__ */ j("button", {
								type: "button",
								onClick: c,
								className: e.uiToggleButton,
								children: /* @__PURE__ */ j(N, { className: e.uiToggleIcon })
							})
						]
					})
				})]
			})
		]
	});
}, K = [];
function q({ value: e = [], onChange: t, title: n, config: r, ...i }) {
	let [a, o] = b(!1), s = z(r, e), c = s.data, l = e.length === 0 ? {
		status: "ready",
		items: K
	} : c === void 0 ? s.isError ? { status: "error" } : { status: "loading" } : {
		status: "ready",
		items: c
	}, u = v(() => o(!0), []), d = v(() => o(!1), []), f = v(() => t([]), [t]), p = v((e) => t(e.map((e) => String(e[r.leadingKey]))), [r.leadingKey, t]), m = v((e) => {
		if (e?.length) return e.length > 1 ? `Выбрано ${e.length} элем.` : `${r.leadingText && e[0][r.leadingText] || e[0][r.leadingKey]}`;
	}, [r.leadingKey, r.leadingText]);
	return /* @__PURE__ */ M(A, { children: [/* @__PURE__ */ j(G, {
		...i,
		token: m(c),
		onOpen: u,
		onClear: f
	}), a && /* @__PURE__ */ j(W, {
		title: n,
		config: r,
		onClose: d,
		onItemsSelect: p,
		initialSelection: l
	})] });
}
//#endregion
export { q as AdvancedSearchSelect, R as useAdvancedSearch, z as useAdvancedSearchInitialSelected, V as useAdvancedSearchSelection };

//# sourceMappingURL=index.js.map