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