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