import { isFunction as v } from "lodash-unified";
import { ref as d, watch as h, onMounted as g } from "vue";
const q = (t) => {
  let i = 0;
  const r = d(t.options || []), l = d(!1);
  h(
    () => t.options,
    (e) => {
      r.value = e;
    },
    {
      deep: !0
    }
  );
  function c(e, u) {
    if (!e?.length)
      return;
    const a = t.fieldNames?.value || "value";
    for (const n of e) {
      if (n[a] === u[a])
        return n;
      if (n.children?.length) {
        const f = c(n.children, u);
        if (f)
          return f;
      }
    }
  }
  async function o(e, u = !1) {
    if (!v(t.request))
      return;
    e?.length || (l.value = !0), i += 1;
    const a = i;
    try {
      u && (r.value = []);
      const n = await t.request(e, t.params);
      if (a !== i)
        return;
      if (e?.length) {
        const f = e[e.length - 1], s = c(r.value, f);
        s && (s.children = n);
      } else
        r.value = n;
    } finally {
      l.value = !1;
    }
  }
  return g(() => {
    t.lazy || o();
  }), h(
    () => t.params,
    () => {
      o();
    },
    {
      deep: !0
    }
  ), {
    options: r,
    request: o,
    loading: l
  };
};
export {
  q as useOptions
};
