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

//# sourceMappingURL=index.js.map