import { isObjectWithContent as S } from "@aplus-frontend/utils";
import { debounce as A } from "lodash-unified";
import { ref as d, watch as M, onMounted as O, onActivated as x, computed as v } from "vue";
import { getUrlQuery as f, setUrlQuery as m } from "../utils/query.mjs";
const _ = (h) => {
  const {
    saveDataSource: p,
    sendToUrl: c,
    tableKey: t,
    extraUrlParams: Q,
    searchFormModel: K,
    urlQueryAdapter: u
  } = h;
  let a, l = !1;
  const n = d({}), y = d(!1), i = (e) => {
    if (!e || Array.isArray(e) || typeof e != "object")
      return {};
    const r = { ...e };
    return delete r.__tk, delete r[t.value], r;
  }, o = d(), s = () => {
    if (o.value)
      return o.value;
    const e = u.value?.resolveOwnerKey?.({
      tableKey: t.value
    });
    return e && (o.value = e), o.value;
  }, g = () => {
    const e = f();
    return u.value?.getQuery?.({
      tableKey: t.value,
      ownerKey: s(),
      defaultQuery: e
    }) ?? e;
  }, b = (e) => {
    const r = u.value;
    if (!r?.setQuery) {
      m(e);
      return;
    }
    const C = f();
    r.setQuery(e, {
      tableKey: t.value,
      ownerKey: s(),
      defaultQuery: C,
      defaultSetQuery: m
    });
  }, w = A(() => {
    try {
      const e = encodeURIComponent(
        JSON.stringify(
          i({
            ...p?.getSearchFormValues?.(),
            ...Q?.value?.() ?? {}
          })
        )
      );
      e !== a && (a = e, l = !0);
    } catch {
      a = "";
    }
    l && (b({ [t.value]: a }), l = !1);
  }, 500), U = () => {
    try {
      const e = g()[t.value] ?? "";
      n.value = e ? i(JSON.parse(decodeURIComponent(e))) : {}, y.value = !0;
    } catch {
      n.value = {};
    }
  };
  return M(
    K,
    () => {
      c?.value && w();
    },
    {
      deep: !0,
      immediate: !0
    }
  ), O(() => {
    c?.value && U();
  }), x(() => {
    s();
  }), {
    mountedData: v(() => n.value),
    isValidMountedData: v(() => S(n.value)),
    isFirstSendToUrl: y
  };
};
export {
  _ as useSendToUrl
};
