import { HighlightText as e } from "../text/index.js";
import { t } from "./ui.module-BisoTevy.js";
import { useCallback as n, useEffect as r, useMemo as i, useRef as a, useState as o } from "react";
import { cn as s, logError as c } from "@ryuzaki13/react-foundation-lib/utils";
import { asRecord as l, isRecord as u, isSafe as d } from "@ryuzaki13/react-foundation-lib/validators";
import { reportTransportError as f } from "@ryuzaki13/react-foundation-lib/error-report";
import { formatDateAsODataDatetime as p, parseDate as m, truncateText as h } from "@ryuzaki13/react-foundation-lib/formatters";
import { queryOptions as g, useQuery as _, useQueryClient as v } from "@tanstack/react-query";
import { persistedQueryMeta as y } from "@ryuzaki13/react-foundation-lib/query-client";
import { buildEntityOperationPath as b, buildEntityPath as x, buildFunctionImportPath as S, buildODataFilter as C, buildODataOrder as w, odataParseValueByMetadata as T, parseServiceMetadata as ee } from "@ryuzaki13/react-foundation-lib/odata-service";
import "@ryuzaki13/react-foundation-lib/string-comparison";
import { buildSeparatedArrays as te, useODataCollectionStore as E } from "@ryuzaki13/react-foundation-lib/odata";
import { createTableColumnVisibilityFromODataMetadata as ne, createTableColumnsFromODataMetadata as re, enrichTableColumnsWithODataFormatting as ie, resolveStableColumnId as ae } from "@ryuzaki13/react-foundation-lib/table";
import "@ryuzaki13/react-foundation-lib/notifications";
import { jsx as D, jsxs as oe } from "react/jsx-runtime";
//#region node_modules/@ryuzaki13/react-foundation-api/dist/chunks/fetch-CPEFkAcU.js
var O = {};
function k() {
	return O;
}
function se(e) {
	return e.split(";")[0] ?? e;
}
function A(e, t) {
	let n = O.devDp0Service;
	return (__DEV__ || __PREVIEW__) && n && se(e) === se(n) ? "odataDp0" : t ?? "odata";
}
function ce() {
	return O.resolveSapClient?.() ?? null;
}
var le = "/sap/opu/odata/sap", ue = __DEV__ || __PREVIEW__ ? "/sap-dp0/opu/odata/sap" : "/sap/opu/odata/sap", de = __DEV__ || __PREVIEW__ ? "/sap-dp0/opu/odata/UI2" : "/sap/opu/odata/UI2", fe = __BASE_APP_CONFIG_URL__, j = Object.freeze({
	"": "",
	odata: le,
	odataDp0: ue,
	odataUi2: de,
	config: fe
});
function M(e) {
	return typeof e == "string" ? e : typeof Request < "u" && e instanceof Request ? e.url : e.toString();
}
function N(e) {
	let t = e.split("?")[0]?.split("#")[0] ?? "";
	return t ? t.startsWith("/") ? t : `/${t}` : "/";
}
var pe = 40, me = 1e3;
function he(e) {
	try {
		let t = typeof window < "u" ? window.location.origin : "http://localhost", n = new URL(e, t);
		return `${n.origin === t ? "" : n.origin}${n.pathname}`;
	} catch {
		return N(e);
	}
}
function ge(e) {
	if (!(typeof DOMParser > "u")) try {
		return new DOMParser().parseFromString(e, "text/html");
	} catch {
		return;
	}
}
function _e(e, t) {
	return t?.querySelector("title")?.textContent || /<title[^>]*>([\s\S]*?)<\/title>/i.exec(e)?.[1];
}
function ve(e, t) {
	let n = t?.querySelectorAll("form").length;
	return n === void 0 ? Array.from(e.matchAll(/<form\b/gi)).length : n;
}
function ye(e, t) {
	let n = t ? Array.from(t.querySelectorAll("input[name],textarea[name],select[name]")).map((e) => e.name).filter(Boolean) : Array.from(e.matchAll(/\bname\s*=\s*["']([^"']+)["']/gi)).map((e) => e[1]).filter((e) => !!e);
	return Array.from(new Set(n)).slice(0, pe);
}
function be(e, t) {
	return h(t?.body?.textContent ?? e.replace(/<script\b[\s\S]*?<\/script>/gi, " ").replace(/<style\b[\s\S]*?<\/style>/gi, " ").replace(/<[^>]+>/g, " "), me);
}
function xe(e) {
	let t = ge(e);
	return {
		length: e.length,
		title: h(_e(e, t), 200),
		formCount: ve(e, t),
		inputNames: ye(e, t),
		textPreview: be(e, t)
	};
}
function Se(e, t, n, r, i) {
	let a = i ? M(i.input) : void 0, o = a?.startsWith("http") ? a : a ? `${j[i?.baseUrlType ?? ""]}${a}` : void 0;
	f(e, {
		source: t,
		requestUrl: o ? he(o) : void 0,
		responseUrl: n.url ? he(n.url) : void 0,
		method: i?.init.method?.toUpperCase() ?? "GET",
		baseUrlType: i?.baseUrlType,
		sapClient: i?.sapClient,
		status: n.status,
		statusText: n.statusText,
		contentType: n.headers.get("Content-Type") || void 0,
		redirected: n.redirected,
		responseType: n.type,
		html: xe(r)
	});
}
var P = null, Ce = 0;
function we(e) {
	if (typeof window > "u") return e;
	try {
		let t = new RegExp(__ORIGIN_REG_EXP__, "i"), n = new URL(e, window.location.origin), r = t.test(n.origin), i = n.origin === __SSO_ORIGIN__;
		return r || i || n.origin === window.location.origin ? `${n.pathname}${n.search}${n.hash}` : n.toString();
	} catch {
		return e;
	}
}
function F(e) {
	return e ? typeof e.inputs.SAMLRequest == "string" || typeof e.inputs.SAMLResponse == "string" : !1;
}
function Te() {
	let e = `${__APP_ID__}-sso-iframe-${++Ce}`, t = document.createElement("iframe");
	return t.name = e, t.style.display = "none", t;
}
function Ee(e, t) {
	return new Promise((n) => {
		let r = null, i = () => {
			r !== null && window.clearTimeout(r), r = window.setTimeout(() => {
				t(), n(!0);
			}, 400);
		};
		e.addEventListener("load", i), e.addEventListener("error", i);
	});
}
function De(e, t) {
	let n = document.createElement("form");
	n.method = e.method === "GET" ? "GET" : "POST", n.action = we(e.action), n.target = t, n.style.display = "none";
	for (let [t, r] of Object.entries(e.inputs)) {
		let e = document.createElement("input");
		e.type = "hidden", e.name = t, e.value = r, n.appendChild(e);
	}
	return n;
}
function Oe() {
	return typeof document > "u" ? null : document.body ?? document.documentElement;
}
function ke(e) {
	let t = Oe();
	if (!t) return Promise.resolve(!1);
	let n = Te(), r = De(e, n.name), i = Ee(n, () => {
		n.remove(), r.remove();
	});
	return t.appendChild(n), t.appendChild(r), r.submit(), i;
}
function Ae(e) {
	let t = Oe();
	if (!t) return Promise.resolve(!1);
	let n = Te(), r = Ee(n, () => {
		n.remove();
	});
	return t.appendChild(n), n.src = we(e), r;
}
function je({ form: e, recoveryUrl: t } = {}) {
	return P || (typeof window > "u" ? !1 : (P = (async () => F(e) ? ke(e) : t ? Ae(t) : !1)().finally(() => {
		P = null;
	}), P));
}
var I = class e extends Error {
	form;
	recoveryUrl;
	recoverable;
	constructor(t, n, r, i = {}) {
		super(t), this.form = n, this.recoveryUrl = r, this.recoverable = i.recoverable ?? !0, Object.setPrototypeOf(this, e.prototype);
	}
}, L = /* @__PURE__ */ new Map(), R = /* @__PURE__ */ new Map(), z = null, B = null;
function V(e, t) {
	if (t !== "") return !0;
	let n = N(M(e));
	return n.startsWith("/sap/") || n.startsWith("/sap-dp0/");
}
function H(e, t) {
	return __DEV__ || __PREVIEW__ ? V(e, t) ? t === "odataDp0" || t === "" && N(M(e)).startsWith("/sap-dp0/") ? "300" : `${__SAP_CLIENT__}` : null : ce();
}
function Me(e) {
	return new I("Не удалось автоматически восстановить SSO-сессию. Перезагрузите страницу и выполните вход заново.", e.form, e.recoveryUrl, { recoverable: !1 });
}
function U(e) {
	let t = Me(e);
	return typeof window < "u" && (B = t), t;
}
async function Ne() {
	let e = z;
	if (e && await e.catch(() => {}), B) throw B;
}
async function W(e, t) {
	if (B) throw B;
	let n;
	if (!z) {
		if (z = (async () => {
			if (!await Promise.resolve(je({
				form: e.form,
				recoveryUrl: e.recoveryUrl
			})).catch(() => !1)) throw U(e);
			try {
				n = { value: await t() }, B = null;
			} catch (e) {
				throw e instanceof I ? U(e) : e;
			}
		})().finally(() => {
			z = null;
		}), await z, !n) throw B ?? Me(e);
		return n.value;
	}
	await Ne();
	try {
		return await t();
	} catch (e) {
		throw e instanceof I ? U(e) : e;
	}
}
function Pe(e, t, n) {
	if (t === "config") return {
		cacheKey: `${__APP_ID__}:${n ?? ""}`,
		fetchUrl: "/Statistics"
	};
	let [r] = N(M(e)).split("/").filter(Boolean);
	if (!r) throw Error("Не удалось определить сервис для получения CSRF-токена");
	return {
		cacheKey: `${t}:${n ?? ""}:${r}`,
		fetchUrl: `/${r}/`
	};
}
async function Fe(e, t, n) {
	let r = Pe(e, t, n), i = L.get(r.cacheKey);
	if (i) return i;
	let a = R.get(r.cacheKey);
	if (a) return a;
	let o = new Headers({ "x-csrf-token": "Fetch" });
	o.set("sap-language", "ru"), o.set("sap-contextid-accept", "header"), o.set("Accept-Language", "ru"), n && o.set("sap-client", n);
	let s = (t && j[t]) ?? "", c = fetch(s + r.fetchUrl, {
		method: "GET",
		headers: o,
		credentials: "include",
		redirect: "manual"
	}).then(async (e) => {
		if (Ge(e)) throw new I("Требуется повторная аутентификация", void 0, s + r.fetchUrl);
		if (!e.ok) throw Error("Не удалось получить CSRF-токен");
		let t = e.headers.get("x-csrf-token");
		if (!t) {
			let t = (e.headers.get("Content-Type") || "").toLowerCase(), n = await e.text();
			if (Ie(t, n)) {
				let e = K(n);
				if (F(e)) throw new I("Требуется повторная аутентификация", e, s + r.fetchUrl);
			}
			throw Error("CSRF-токен отсутствует в ответе");
		}
		return L.set(r.cacheKey, t), R.delete(r.cacheKey), t;
	}).catch((e) => {
		throw R.delete(r.cacheKey), e;
	});
	return R.set(r.cacheKey, c), c;
}
function G(e, t) {
	let n = t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
	return RegExp(`${n}\\s*=\\s*["']([^"']*)["']`, "i").exec(e)?.[1];
}
function K(e) {
	try {
		if (typeof DOMParser < "u") {
			let t = new DOMParser().parseFromString(e, "text/html").querySelector("form");
			if (t) {
				let e = t.getAttribute("action") || (typeof window < "u" ? window.location.href : ""), n = (t.getAttribute("method") || "GET").toUpperCase(), r = {};
				return t.querySelectorAll("input[name]").forEach((e) => {
					r[e.name] = e.value ?? "";
				}), {
					action: e,
					method: n,
					inputs: r
				};
			}
		}
	} catch {}
	let t = /<form\b([^>]*)>([\s\S]*?)<\/form>/i.exec(e);
	if (!t) return;
	let [, n = "", r = ""] = t, i = G(n, "action") || (typeof window < "u" ? window.location.href : ""), a = (G(n, "method") || "GET").toUpperCase(), o = {};
	for (let e of r.matchAll(/<input\b([^>]*)>/gi)) {
		let t = e[1] ?? "", n = G(t, "name");
		n && (o[n] = G(t, "value") ?? "");
	}
	return {
		action: i,
		method: a,
		inputs: o
	};
}
function Ie(e, t) {
	return e.includes("text/html") || /<html/i.test(t) || /<form/i.test(t);
}
function Le(e) {
	if (!u(e)) return e;
	let t = { ...e };
	return delete t.__metadata, t;
}
function Re(e) {
	if (u(e) && u(e.d) && Array.isArray(e.d.results)) {
		let t;
		return e.d.__count && (t = Number(e.d.__count)), {
			data: e.d.results.map(Le),
			totalCount: t
		};
	}
	return u(e) && e.d !== void 0 ? { data: Le(e.d) } : { data: e };
}
var ze = Object.freeze({ __noContent: !0 });
function Be(e) {
	return !!e && typeof e == "object" && "__noContent" in e;
}
async function Ve(e, t) {
	if (e.status === 204 || e.status === 205) return { data: ze };
	let n = (e.headers.get("Content-Type") || "").toLowerCase();
	if (n.includes("application/json") || n.includes("application/odata+json")) return Re(await e.json());
	let r = await e.text();
	if (Ie(n, r)) {
		let n = K(r);
		if (F(n)) throw new I("Требуется повторная аутентификация", n);
		let i = /* @__PURE__ */ Error("Unexpected HTML response from OData endpoint");
		throw Se(i, "fetch.parseResponse", e, r, t), i;
	}
	try {
		return Re(JSON.parse(r));
	} catch (e) {
		throw c(e), Error("Unsupported response content type and body is not JSON");
	}
}
function He(e) {
	if (typeof e != "string") return null;
	let t = e.trim();
	return t.length ? t : null;
}
function q(e, t) {
	let n = He(t);
	!n || e.includes(n) || e.push(n);
}
function Ue(e) {
	let t = [], n = e.error;
	typeof n == "string" && q(t, n);
	let r = l(n);
	return r && (q(t, r.code), q(t, l(r.message)?.value ?? r.message)), q(t, e.details), q(t, e.message), t;
}
async function We(e, t) {
	let n = (e.headers.get("Content-Type") || "").toLowerCase();
	try {
		if (n.includes("application/json") || n.includes("application/odata+json")) {
			let t = Ue(await e.json());
			if (t.length) return Error(t.join(" | "));
		} else {
			let r = He(await e.text());
			if (r) {
				if (Ie(n, r)) {
					let n = K(r);
					if (F(n)) return new I("Требуется повторная аутентификация", n);
					let i = /* @__PURE__ */ Error("Unexpected HTML response from OData endpoint");
					return Se(i, "fetch.buildHttpError", e, r, t), i;
				}
				return Error(r);
			}
		}
	} catch {}
	return /* @__PURE__ */ Error(`HTTP error: ${e.status} ${e.statusText}`);
}
function Ge(e) {
	return e.type === "opaqueredirect";
}
async function Ke(e, t = {}, n = "odata") {
	let r = t.method?.toUpperCase() || "GET", i = new Headers(t.headers), a = !["GET", "HEAD"].includes(r), o = d(t.body), s = V(e, n), c = H(e, n);
	if (i.set("sap-language", "ru"), s && (i.set("sap-language", "ru"), i.set("sap-contextid-accept", "header")), c && i.set("sap-client", c), a && s) {
		let t = await Fe(e, n, c);
		i.set("x-csrf-token", t);
	}
	i.has("Accept") || i.set("Accept", "application/json"), o && a && !i.has("Content-Type") && i.set("Content-Type", "application/json");
	let l = (n && j[n]) ?? "", u = typeof e == "string" ? e : e.toString(), f = await fetch(l + u, {
		...t,
		headers: i,
		credentials: "include",
		redirect: s ? "manual" : t.redirect
	});
	if (s && Ge(f)) throw new I("Требуется повторная аутентификация", void 0, l + u);
	if ((f.status === 401 || f.status === 403) && a && s && !t.retried) {
		let r = Pe(e, n, c);
		L.delete(r.cacheKey), R.delete(r.cacheKey);
		let a = await Fe(e, n, c), o = new Headers(i);
		if (o.set("x-csrf-token", a), f = await fetch(l + u, {
			...t,
			headers: o,
			credentials: "include",
			redirect: "manual",
			retried: !0
		}), Ge(f)) throw new I("Требуется повторная аутентификация", void 0, l + u);
	}
	return f;
}
async function qe(e, t, n, r, i) {
	if (!e.ok) throw e.status === 0 ? Error("Ошибка сети или CORS. Проверьте подключение и настройки сервера.") : await We(e, {
		input: t,
		init: n,
		baseUrlType: r,
		sapClient: i
	});
	return e;
}
async function Je(e, t = {}, n = "odata") {
	let r = H(e, n);
	return qe(await Ke(e, t, n), e, t, n, r);
}
async function Ye(e, t = {}, n = "odata") {
	let r = V(e, n), i = H(e, n), a = () => Je(e, {
		...t,
		ssoRetried: !0
	}, n);
	r && await Ne();
	let o;
	try {
		o = await Ke(e, t, n);
	} catch (e) {
		if (r && e instanceof I && e.recoverable && !t.ssoRetried) o = await W(e, a);
		else throw e;
	}
	try {
		return await qe(o, e, t, n, i);
	} catch (o) {
		if (r && o instanceof I && o.recoverable && !t.ssoRetried) return qe(await W(o, a), e, t, n, i);
		throw o;
	}
}
async function Xe(e, t = {}, n = "odata") {
	let r = new Headers(t.headers);
	r.set("DataServiceVersion", "2.0"), r.set("MaxDataServiceVersion", "2.0");
	let i = {
		...t,
		headers: r
	}, a = {
		input: e,
		init: t,
		baseUrlType: n,
		sapClient: H(e, n)
	};
	try {
		return await Ve(await Ye(e, i, n), a);
	} catch (r) {
		if (V(e, n) && r instanceof I && r.recoverable && !t.ssoRetried) return W(r, async () => {
			let t = {
				...i,
				ssoRetried: !0
			};
			return Ve(await Je(e, t, n), {
				input: e,
				init: t,
				baseUrlType: n,
				sapClient: H(e, n)
			});
		});
		throw r;
	}
}
function Ze(e, t) {
	let n = t.init || {}, r = t.baseUrl, i = t.transform;
	if (t.swCache) {
		let e = new Headers(n.headers);
		e.set("x-sw-cache", t.swCache), n.headers = e;
	}
	return async (t) => {
		!n.signal && t?.signal && (n.signal = t.signal);
		let a = await Ye(e, n, r);
		if (typeof i != "function") throw Error("fetchQueryFn requires a transformation function!");
		return await i(a);
	};
}
//#endregion
//#region node_modules/@ryuzaki13/react-foundation-api/dist/chunks/odataFetchFn-D8PGKDZM.js
var J = ["odata"];
function Qe(e, t, n) {
	n === void 0 || n === "" || e.set(t, String(n));
}
function $e(e, t = {}, n = {}) {
	let [r, i = ""] = e.split("?"), a = new URLSearchParams(i);
	if (t.expression) {
		let e = C(t.expression);
		e && a.set("$filter", e);
	}
	t.sorts && a.set("$orderby", w(t.sorts)), t.select && a.set("$select", t.select.join(",")), t.expand && a.set("$expand", t.expand.join(",")), Qe(a, "$top", t.top), Qe(a, "$skip", t.skip), Qe(a, "$inlinecount", t.inlinecount);
	let o = r.replace(/\/+$/, ""), s = a.toString(), c = s ? `${o}?${s}` : o, l = n;
	if (t.swCache) {
		let e = new Headers(n.headers);
		e.set("x-sw-cache", t.swCache), l = {
			...n,
			headers: e
		};
	}
	return {
		path: c,
		fullUrl: `${j[t.baseUrl ?? "odata"]}${c}`,
		baseUrl: t.baseUrl,
		init: l,
		queryString: s
	};
}
async function Y(e, t = {}, n = {}) {
	let r = $e(e, t, n);
	return Xe(r.path, r.init, t.baseUrl);
}
var et = __APP_BUILD_ID__, tt = 1e3 * 60 * 60 * 24;
function nt(e) {
	if (e) return Array.isArray(e) ? e[0] : e;
}
var rt = ({ service: e }) => [
	...J,
	"metadata-version",
	{
		service: e,
		buildId: et
	}
];
function it(e) {
	return {
		service: e,
		changedAt: null,
		version: null
	};
}
function at(e) {
	return async ({ signal: t }) => {
		let n = k().metadataVersion;
		if (!n) return it(e.service);
		let r = m(nt((await Y(`/${n.service}/${n.target}('${se(e.service)}')`, { baseUrl: A(n.service, n.baseUrl) }, { signal: t })).data)?.lastChanged);
		return {
			service: e.service,
			changedAt: r,
			version: r ? p(r) : null
		};
	};
}
var ot = (e) => g({
	queryKey: rt(e),
	queryFn: at(e),
	meta: y,
	enabled: !!(e.service && k().metadataVersion),
	staleTime: e.staleTime ?? tt,
	gcTime: Infinity
});
function st(e, t) {
	return e.invalidateQueries({ predicate: (e) => {
		let [n, r, i] = e.queryKey;
		return n !== J[0] || r !== "metadata" || !i || typeof i != "object" ? !1 : "service" in i && i.service === t;
	} });
}
function ct(e, t) {
	return e?.data === void 0 || !t.changedAt ? !1 : t.changedAt.getTime() > e.dataUpdatedAt;
}
function lt(e) {
	return Ze(`/${e.service}/$metadata`, {
		baseUrl: A(e.service, e.baseUrl),
		init: { headers: {
			Accept: "*/*",
			"Content-Type": "application/xml"
		} },
		transform: async (t) => {
			try {
				return ee(await t.text());
			} catch (t) {
				throw Error(`Сервис ${e.service} содержит необработанную ошибку: ${String(t)}`);
			}
		}
	});
}
var X = (e) => g({
	queryKey: [
		...J,
		"metadata",
		e
	],
	queryFn: lt(e),
	meta: y,
	enabled: !!e.service,
	staleTime: Infinity,
	gcTime: Infinity
});
async function ut(e, t, n) {
	if (!t.service) return;
	let r = X(t).queryKey;
	ct(e.getQueryState(r), n) && await st(e, t.service);
}
function dt(e) {
	let t = v(), n = i(() => ({
		service: e.service,
		baseUrl: e.baseUrl
	}), [e.baseUrl, e.service]), a = _(ot(i(() => ({ service: e.service }), [e.service]))), o = _(X(n));
	return r(() => {
		!e.service || !a.isSuccess || ut(t, n, a.data);
	}, [
		n,
		o.dataUpdatedAt,
		e.service,
		t,
		a.data,
		a.isSuccess
	]), o;
}
async function ft(e, t) {
	let n = { service: e.service };
	try {
		await ut(t, e, await t.fetchQuery(ot(n)));
	} catch {}
}
async function pt(e, t) {
	if (e.service) return await t.fetchQuery(X(e)), await ft(e, t), t.fetchQuery(X(e));
}
function Z(e) {
	return "returnType" in e;
}
function mt(e, t) {
	let n = e?.entities[t], r = e?.functionImports[t];
	if (n && r) throw Error(`Найден конфликт metadata: '${t}' существует и как Entity, и как FunctionImport`);
	if (n) return n;
	if (r) return r;
	throw Error(`OData target '${t}' не был загружен`);
}
function ht(e, t, n) {
	if (Z(e)) {
		if (t !== "fi") throw Error(`OData operation '${t}' несовместима с FunctionImport '${e.name}'. Для FunctionImport используйте method: 'fi'.`);
		return;
	}
	if (t === "fi") throw Error(`OData operation 'fi' несовместима с Entity '${n.target}'. Для Entity используйте один из методов: 'create', 'update', 'delete', 'read', 'query', 'fm'.`);
	if (t === "read" && e.result) throw Error(`OData operation '${t}' несовместима с parameterized query entity '${n.target}'. Для target с result='${e.result}' используйте method: 'query'.`);
}
function gt(e, t) {
	if (t === "create") return "POST";
	if (t === "update") return "PUT";
	if (t === "delete") return "DELETE";
	if (t === "read" || t === "query") return "GET";
	if (Z(e)) {
		if (!e.httpMethod) throw Error(`FunctionImport '${e.name}' не содержит httpMethod в metadata, поэтому operation 'fi' выполнить нельзя.`);
		return e.httpMethod;
	}
	throw Error(`OData operation '${t}' не поддерживается для target '${"title" in e ? e.title : "unknown"}'.`);
}
function _t(e, t) {
	if (e && (t === "create" || t === "update")) return JSON.stringify(e);
}
function vt(e, t, n, r) {
	if (Z(e)) return S(e, t, n);
	if (r === "fi") throw Error(`OData operation 'fi' несовместима с Entity '${t.target}'.`);
	return b(e, t, n, r);
}
function yt(e, t) {
	if (!Z(e)) return e.columns;
	if (e.resultEntity) return t.entities[e.resultEntity]?.columns;
}
function bt(e) {
	let t = [];
	for (let n = 0; n < e.length; n += 1) {
		let r = e[n];
		t.push({
			id: r.id,
			type: r.type,
			abapBooleanLike: r.abapBooleanLike
		});
	}
	return t;
}
function xt(e, t) {
	let n;
	for (let r = 0; r < t.length; r += 1) {
		let i = t[r];
		if (!Object.prototype.hasOwnProperty.call(e, i.id)) continue;
		let a = e[i.id], o = T(i, a);
		o !== a && (n ||= { ...e }, n[i.id] = o);
	}
	return n ?? e;
}
function St(e, t, n) {
	let r = yt(t, n);
	if (!r?.length) return e;
	let i = bt(r);
	if (Array.isArray(e)) {
		let t;
		for (let n = 0; n < e.length; n += 1) {
			let r = e[n];
			if (!u(r)) continue;
			let a = xt(r, i);
			a !== r && (t ||= e.slice(), t[n] = a);
		}
		return t ?? e;
	}
	return u(e) ? xt(e, i) : e;
}
function Ct(...e) {
	let [t, n] = e, { odata: r, options: i = {}, init: a = {}, autoParse: o, swCache: s } = n, c = "params" in n ? n.params ?? {} : {};
	return async ({ client: e, signal: l }) => {
		let u = A(r.service, i.baseUrl), d = await pt({
			service: r.service,
			baseUrl: u
		}, e);
		if (!d) throw Error(`Не удалось загрузить metadata OData-сервиса '${r.service}'`);
		let f = mt(d, r.target);
		ht(f, t, r);
		let p = "body" in n ? _t(n.body, t) : void 0, m = gt(f, t);
		__DEV__ && t === "query" && !("result" in f) && Object.keys(c).length > 0 && console.warn(`OData query для plain entity "${r.service}/${r.target}" получил params, но они будут проигнорированы. Для чтения сущности по ключу используйте odataReadFn.`);
		let h = vt(f, r, c, t), g = s ? {
			...i,
			baseUrl: u,
			swCache: s
		} : {
			...i,
			baseUrl: u
		}, _ = {
			...a,
			method: m,
			body: p,
			signal: l
		};
		if (t === "query") {
			let e = await Y(h, g, _);
			if (Be(e)) throw Error("OData query не должен возвращать 204 No Content");
			let t = o ? St(e.data, f, d) : e.data;
			return {
				data: n.transform ? n.transform(t, f) : t,
				totalCount: e.totalCount
			};
		}
		let v = await Y(h, g, _);
		if (Be(v)) return { data: v.data };
		let y = o ? St(v.data, f, d) : v.data;
		return {
			data: n.transform ? n.transform(y, f) : y,
			totalCount: v.totalCount
		};
	};
}
function wt(e) {
	return Ct("query", e);
}
//#endregion
//#region node_modules/@ryuzaki13/react-foundation-api/dist/odata/index.js
var Tt = () => [...J, "collection"], Q = ({ service: e, target: t, limitedKeys: n, serverFilter: r }) => [...Tt(), {
	service: e,
	target: t,
	limitedKeys: n,
	serverFilter: r
}];
function Et(e) {
	let t = [];
	for (let [n, r] of e.entries()) {
		let e = `${r.odata.service}.${r.odata.target}`;
		for (let [i, [a, o]] of Object.entries(r.segments).entries()) t.push({
			id: a,
			serviceKey: e,
			serviceIndex: n,
			segmentIndex: i,
			odata: r.odata,
			segment: o,
			model: {
				...r.model,
				codeKey: a
			},
			panelVisibility: o.panelVisibility ?? "user"
		});
	}
	return t;
}
function Dt(e, t, n) {
	let r = /* @__PURE__ */ new Map();
	for (let [e, n] of Object.entries(t)) r.set(e, new Map(n.map((e, t) => [e.codeKey, t])));
	let i = [...e].map((e, t) => ({
		item: e,
		index: t
	})).sort((e, t) => {
		if (e.item.serviceIndex !== t.item.serviceIndex) return e.item.serviceIndex - t.item.serviceIndex;
		let n = r.get(e.item.serviceKey), i = n?.get(e.item.id), a = n?.get(t.item.id);
		return i !== void 0 && a !== void 0 ? i - a : i === void 0 ? a === void 0 ? e.item.segmentIndex === t.item.segmentIndex ? e.index - t.index : e.item.segmentIndex - t.item.segmentIndex : 1 : -1;
	});
	if (!n?.length) return i.map(({ item: e }) => e);
	let a = new Set(i.map(({ item: e }) => e.id)), o = [...new Set(n)].filter((e) => a.has(e));
	if (o.length === 0) return i.map(({ item: e }) => e);
	let s = new Map(o.map((e, t) => [e, t]));
	return [...i].sort((e, t) => {
		let n = s.get(e.item.id), r = s.get(t.item.id);
		return n !== void 0 && r !== void 0 ? n - r : n === void 0 ? r === void 0 ? e.index - t.index : 1 : -1;
	}).map(({ item: e }) => e);
}
async function Ot(e) {
	let { url: t, query: n, signal: r } = e;
	try {
		let e = await Y(t, n, { signal: r });
		if (Be(e)) throw Error("отсутствует тело ответа");
		return { items: e.data.map(({ ID: e, CNT: t, __metadata: n, __Parameters: r, ...i }) => i) };
	} catch (e) {
		return c("Ошибка загрузки справочника:", e), { items: [] };
	}
}
var kt = __APP_BUILD_ID__, At = 1e3 * 60 * 60 * 4, jt = 1e3 * 60 * 60 * 24 * 7, Mt = "ttl=forever;name=ref", Nt = "bust=forever;name=ref", Pt = "ttl=4h;name=ref-updates", Ft = () => [
	...J,
	"collection-updates",
	{ buildId: kt }
];
function It(e) {
	return {
		...e,
		lastChangedAt: m(e.lastChanged)
	};
}
function Lt(e, t) {
	let n = e.map(It);
	return {
		items: n,
		byEntityName: n.reduce((e, t) => (t.entityName && (e[t.entityName] = t), e), {}),
		fetchedAt: t,
		coverageStartedAt: t - jt
	};
}
function Rt() {
	return async ({ signal: e }) => {
		let t = Date.now(), n = k().collectionUpdates;
		return n ? Lt((await Y(`/${n.service}/${n.target}`, {
			baseUrl: A(n.service, n.baseUrl),
			swCache: Pt
		}, { signal: e })).data, Math.max(t, Date.now())) : Lt([], t);
	};
}
var zt = (e = {}) => g({
	queryKey: Ft(),
	queryFn: Rt(),
	meta: y,
	enabled: !!k().collectionUpdates,
	staleTime: e.staleTime ?? At,
	gcTime: Infinity
});
function Bt(e = {}) {
	return _(zt(e));
}
function Vt(e) {
	let { data: t, dataUpdatedAt: n = 0, isLoading: r, isError: i } = dt({ service: e.service }), a = t?.entities[e.target];
	if (!r && !a && t?.functionImports[e.target]) throw Error(`OData target '${e.target}' является FunctionImport и не может использоваться как сущность`);
	if (i) throw Error(`Ошибка загрузки метаданных сервиса ${e.service}`);
	return {
		metadata: a,
		metadataUpdatedAt: n,
		isLoading: r
	};
}
var $ = "Использование actions недопустимо до окончания загрузки metadata";
function Ht(e) {
	let { metadata: t, metadataUpdatedAt: n, isLoading: r } = Vt(e);
	return {
		config: e,
		metadata: t,
		metadataUpdatedAt: n,
		isLoading: r,
		actions: i(() => ({
			getEntityPath: (n = {}) => {
				if (!t) throw Error($);
				return x(t, e, n);
			},
			getKeys: () => {
				if (!t) throw Error($);
				return t.columns?.map((e) => e.id);
			},
			getKeyPairs: () => {
				if (!t) throw Error($);
				return t.columns?.filter((e) => e.semanticType === "code" && e.linkedColumnId).map((e) => ({
					codeKey: e.id,
					textKey: e.linkedColumnId
				}));
			},
			getKeyPairsMap: () => {
				if (!t) throw Error($);
				let e = {};
				for (let n of t.columns ?? []) n.semanticType === "code" && n.linkedColumnId && (e[n.id] = n.linkedColumnId);
				return e;
			}
		}), [e, t])
	};
}
function Ut(e, t) {
	if (!t) return e;
	let n = e.trim().toLowerCase();
	return n === "off" || n.startsWith("bust=") ? e : n.startsWith("ttl=") ? e.replace(/^\s*ttl=/i, "bust=") : Nt;
}
function Wt(e) {
	return typeof e == "number" && Number.isFinite(e) && e > 0;
}
function Gt(e, t) {
	let n = t?.cacheUpdatedAt ?? 0, r = e.update?.lastChangedAt?.getTime();
	return !!(Wt(r) && (!t || !n || r > n) || Wt(e.metadataUpdatedAt) && (!t || !n || e.metadataUpdatedAt > n) || Wt(e.updatesCoverageStartedAt) && (!t || !n || n < e.updatesCoverageStartedAt));
}
function Kt(e) {
	let { service: t, target: n, limitedKeys: a, excludeEmpty: o, sortByCode: s, serverFilter: c, clientFilter: l, swCache: u = Mt } = e, d = v(), { actions: f, metadata: p, metadataUpdatedAt: m, isLoading: h } = Ht(e), g = Bt(), b = i(() => Q({
		service: t,
		target: n,
		limitedKeys: a,
		serverFilter: c
	}), [
		t,
		n,
		a,
		c
	]), x = d.getQueryData(b), S = g.data?.byEntityName[n], C = Gt({
		update: S,
		metadataUpdatedAt: m,
		updatesCoverageStartedAt: g.data?.coverageStartedAt
	}, x), w = Ut(u, C), T = g.isError || g.isSuccess && !g.isFetching;
	return r(() => {
		!x || !C || d.invalidateQueries({ queryKey: b });
	}, [
		x,
		d,
		b,
		C
	]), _({
		queryKey: b,
		queryFn: async ({ signal: e }) => {
			let r = Date.now(), i = a ? [...a] : f.getKeys(), u = f.getKeyPairs(), d = f.getKeyPairsMap();
			if (a) for (let e of a) {
				let t = d[e];
				t && !i.includes(t) && i.push(t);
			}
			let { items: p } = await Ot({
				url: `/${t}/${n}`,
				query: {
					select: i,
					expression: c,
					swCache: w
				},
				signal: e
			}), h = p;
			l && (h = p.filter(l));
			let g = te(h, u, o, s), _ = u.map((e) => ({
				codeKey: e.codeKey,
				count: g[e.codeKey].length
			})).sort((e, t) => e.count - t.count);
			return {
				items: h,
				keyPairs: u,
				keyPairsMap: d,
				separated: g,
				chain: _,
				count: h.length,
				cacheUpdatedAt: Math.max(r, Date.now(), S?.lastChangedAt?.getTime() ?? 0, m)
			};
		},
		enabled: !!(!h && p && t && n && T),
		meta: y,
		staleTime: 1e3 * 60 * 60 * 2,
		gcTime: 1e3 * 60 * 60 * 1
	});
}
function qt({ odata: e, model: t, pageSize: r = 50 }) {
	let { codeKey: s, maxVisibleItems: c } = t, { data: l, isLoading: u, isError: d, refetch: f } = Kt(e), p = l?.keyPairsMap[s] ?? "", m = v(), [h, g] = o(), _ = a(/* @__PURE__ */ new Map()), { itemsMap: y, separatedItems: b, orderedKeys: x } = i(() => {
		let e = /* @__PURE__ */ new Map(), t = [], n = [];
		if (l && l.separated[s]) {
			n = l.separated[s];
			for (let r of n) {
				let n = r[s];
				n && (e.set(n, r), t.push(n));
			}
		}
		return {
			itemsMap: e,
			separatedItems: n,
			orderedKeys: t
		};
	}, [l, s]), S = n((e) => {
		let t = l?.separated[s];
		if (!t) return /* @__PURE__ */ new Map();
		let n = /* @__PURE__ */ new Map();
		for (let r of t) {
			let t = r[e]?.toLowerCase();
			if (t) for (let e = 1; e <= Math.min(5, t.length); e++) {
				let i = t.substring(0, e);
				n.has(i) || n.set(i, /* @__PURE__ */ new Set()), n.get(i).add(r[s]);
			}
		}
		return n;
	}, [l, s]), C = n((e) => {
		g(() => {
			if (e?.length) return new Set(e.map((e) => e[s]));
		});
	}, [s]), w = n((e, t) => {
		if (!x.length) return [];
		let n = c, r = /* @__PURE__ */ new Set(), i = [];
		if (t?.length) for (let e = 0; e < t.length; e++) r.add(t[e][s]);
		let a = 0, o = h && h.size > 0;
		for (let t of x) {
			if (a >= n) break;
			let c = y.get(t);
			if (!c || r.size > 0 && r.has(t)) continue;
			let l = c[s];
			o && !h.has(l) || e && !e(l, c[p]) || (i.push(c), a++);
		}
		return i;
	}, [
		x,
		c,
		s,
		y,
		h,
		p
	]), T = n((e) => {
		let t = l?.separated[s] || [], n = e * r, i = n + r;
		return t.slice(n, i);
	}, [
		l,
		r,
		s
	]), ee = n((e, t) => {
		if (!l) return [];
		let n = new Set(t);
		return l.items.filter((t) => n.has(t[e]));
	}, [l]), te = n((e, t, n = 200) => {
		_.current.has(e) && clearTimeout(_.current.get(e));
		let r = setTimeout(t, n);
		_.current.set(e, r);
	}, []), E = n(() => {
		for (let e of _.current.values()) clearTimeout(e);
		_.current.clear();
	}, []);
	return i(() => () => {
		E();
	}, [E]), {
		data: l,
		isLoading: u,
		isError: d,
		codeKey: s,
		textKey: p,
		getItems: w,
		findSourceItemsByKeys: ee,
		setFilteredItems: C,
		getPage: T,
		buildSearchIndex: S,
		debounce: te,
		itemsMap: y,
		separatedItems: b,
		orderedKeys: x,
		refetch: f,
		invalidate: () => m.invalidateQueries({ queryKey: Q(e) }),
		totalCount: l?.separated[s]?.length || 0,
		pageSize: r
	};
}
function Jt(e) {
	let t = v(), [n, a] = o({}), s = i(() => e.map((e) => Q(e)), [e]);
	return r(() => {
		function n() {
			let n = {};
			for (let r of e) {
				let e = Q(r), i = t.getQueryData(e);
				i?.chain && (n[`${r.service}.${r.target}`] = i.chain);
			}
			a((e) => Object.keys(e).length === Object.keys(n).length && Object.entries(n).every(([t, n]) => e[t] === n) ? e : n);
		}
		return n(), t.getQueryCache().subscribe((e) => {
			if (e?.query) {
				let t = e.query;
				s.some((e) => JSON.stringify(e) === JSON.stringify(t.queryKey)) && n();
			}
		});
	}, [
		e,
		t,
		s
	]), n;
}
function Yt(e) {
	let [t] = o(() => {
		let t = E.getState(), { codeKey: n, maxVisibleItems: r = t.defaultMaxVisibleItems, minSearchCodeLength: i = t.defaultMinSearchCodeLength, minSearchTextLength: a = t.defaultMinSearchTextLength, searchDebounceDelay: o = t.defaultSearchDebounceDelay } = e;
		return {
			codeKey: n,
			maxVisibleItems: r,
			minSearchCodeLength: i,
			minSearchTextLength: a,
			searchDebounceDelay: o
		};
	});
	return t;
}
function Xt(e, t) {
	let n = {}, r = (e) => {
		for (let i of e) {
			if ("columns" in i && Array.isArray(i.columns) && i.columns.length > 0) {
				r(i.columns);
				continue;
			}
			let e = ae(i);
			!e || !(e in t) || (n[e] = t[e]);
		}
	};
	return r(e), n;
}
function Zt(e) {
	let { metadata: t, isLoading: n } = Vt(e);
	return {
		columns: i(() => t ? e.mode === "build" ? re(t.columns, {
			resolveHeader: e.resolveHeader,
			resolveFormatting: e.resolveFormatting
		}) : ie(e.columns, t.columns) : e.mode === "build" ? [] : [...e.columns], [e, t]),
		defaultColumnVisibility: i(() => {
			if (!t) return;
			if (e.mode === "build") return ne(t.columns, { resolveVisible: e.resolveVisible });
			let n = ne(t.columns);
			return Xt(e.columns, n);
		}, [e, t]),
		metadata: t,
		isLoading: n
	};
}
//#endregion
//#region src/select/SelectOptionContent.tsx
function Qt({ label: n, code: r, highlight: i }) {
	return /* @__PURE__ */ oe("div", {
		className: t.uiOptionBase,
		children: [/* @__PURE__ */ D("div", {
			className: s(t.uiOptionText, "flexEllipsis"),
			children: /* @__PURE__ */ D(e, {
				text: n,
				highlight: i
			})
		}), r && /* @__PURE__ */ D("div", {
			className: t.uiOptionCode,
			children: /* @__PURE__ */ D(e, {
				text: r,
				highlight: i
			})
		})]
	});
}
//#endregion
export { Dt as a, wt as c, Et as i, Zt as n, Yt as o, Jt as r, qt as s, Qt as t };

//# sourceMappingURL=SelectOptionContent-lfEtHXfO.js.map