import H from "../../@babel/runtime/helpers/esm/slicedToArray.mjs";
import V from "../../@babel/runtime/helpers/esm/objectSpread2.mjs";
import j from "../../@babel/runtime/helpers/esm/objectWithoutProperties.mjs";
import P from "../../@babel/runtime/helpers/esm/toConsumableArray.mjs";
import x from "../../@babel/runtime/helpers/esm/typeof.mjs";
import K from "../../@babel/runtime/helpers/esm/createClass.mjs";
import z from "../../@babel/runtime/helpers/esm/classCallCheck.mjs";
import a from "../../@babel/runtime/helpers/esm/defineProperty.mjs";
import E, { merge as L } from "../../rc-util/es/utils/set.mjs";
import { warningOnce as U } from "../../rc-util/es/warning.mjs";
import * as _ from "react";
import { HOOK_MARK as B } from "./FieldContext.mjs";
import { allPromiseFinish as $ } from "./utils/asyncUtil.mjs";
import { defaultValidateMessages as q } from "./utils/messages.mjs";
import N from "./utils/NameMap.mjs";
import { getNamePath as g, cloneByNamePathList as D, containsNamePath as M, matchNamePath as G } from "./utils/valueUtil.mjs";
import W from "../../rc-util/es/utils/get.mjs";
var J = ["name"], Q = /* @__PURE__ */ K(function k(y) {
  var e = this;
  z(this, k), a(this, "formHooked", !1), a(this, "forceRootUpdate", void 0), a(this, "subscribable", !0), a(this, "store", {}), a(this, "fieldEntities", []), a(this, "initialValues", {}), a(this, "callbacks", {}), a(this, "validateMessages", null), a(this, "preserve", null), a(this, "lastValidatePromise", null), a(this, "getForm", function() {
    return {
      getFieldValue: e.getFieldValue,
      getFieldsValue: e.getFieldsValue,
      getFieldError: e.getFieldError,
      getFieldWarning: e.getFieldWarning,
      getFieldsError: e.getFieldsError,
      isFieldsTouched: e.isFieldsTouched,
      isFieldTouched: e.isFieldTouched,
      isFieldValidating: e.isFieldValidating,
      isFieldsValidating: e.isFieldsValidating,
      resetFields: e.resetFields,
      setFields: e.setFields,
      setFieldValue: e.setFieldValue,
      setFieldsValue: e.setFieldsValue,
      validateFields: e.validateFields,
      submit: e.submit,
      _init: !0,
      getInternalHooks: e.getInternalHooks
    };
  }), a(this, "getInternalHooks", function(t) {
    return t === B ? (e.formHooked = !0, {
      dispatch: e.dispatch,
      initEntityValue: e.initEntityValue,
      registerField: e.registerField,
      useSubscribe: e.useSubscribe,
      setInitialValues: e.setInitialValues,
      destroyForm: e.destroyForm,
      setCallbacks: e.setCallbacks,
      setValidateMessages: e.setValidateMessages,
      getFields: e.getFields,
      setPreserve: e.setPreserve,
      getInitialValue: e.getInitialValue,
      registerWatch: e.registerWatch
    }) : (U(!1, "`getInternalHooks` is internal usage. Should not call directly."), null);
  }), a(this, "useSubscribe", function(t) {
    e.subscribable = t;
  }), a(this, "prevWithoutPreserves", null), a(this, "setInitialValues", function(t, i) {
    if (e.initialValues = t || {}, i) {
      var r, n = L(t, e.store);
      (r = e.prevWithoutPreserves) === null || r === void 0 || r.map(function(l) {
        var s = l.key;
        n = E(n, s, W(t, s));
      }), e.prevWithoutPreserves = null, e.updateStore(n);
    }
  }), a(this, "destroyForm", function() {
    var t = new N();
    e.getFieldEntities(!0).forEach(function(i) {
      e.isMergedPreserve(i.isPreserve()) || t.set(i.getNamePath(), !0);
    }), e.prevWithoutPreserves = t;
  }), a(this, "getInitialValue", function(t) {
    var i = W(e.initialValues, t);
    return t.length ? L(i) : i;
  }), a(this, "setCallbacks", function(t) {
    e.callbacks = t;
  }), a(this, "setValidateMessages", function(t) {
    e.validateMessages = t;
  }), a(this, "setPreserve", function(t) {
    e.preserve = t;
  }), a(this, "watchList", []), a(this, "registerWatch", function(t) {
    return e.watchList.push(t), function() {
      e.watchList = e.watchList.filter(function(i) {
        return i !== t;
      });
    };
  }), a(this, "notifyWatch", function() {
    var t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
    if (e.watchList.length) {
      var i = e.getFieldsValue(), r = e.getFieldsValue(!0);
      e.watchList.forEach(function(n) {
        n(i, r, t);
      });
    }
  }), a(this, "timeoutId", null), a(this, "warningUnhooked", function() {
    process.env.NODE_ENV !== "production" && !e.timeoutId && typeof window < "u" && (e.timeoutId = setTimeout(function() {
      e.timeoutId = null, e.formHooked || U(!1, "Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?");
    }));
  }), a(this, "updateStore", function(t) {
    e.store = t;
  }), a(this, "getFieldEntities", function() {
    var t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : !1;
    return t ? e.fieldEntities.filter(function(i) {
      return i.getNamePath().length;
    }) : e.fieldEntities;
  }), a(this, "getFieldsMap", function() {
    var t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : !1, i = new N();
    return e.getFieldEntities(t).forEach(function(r) {
      var n = r.getNamePath();
      i.set(n, r);
    }), i;
  }), a(this, "getFieldEntitiesForNamePathList", function(t) {
    if (!t)
      return e.getFieldEntities(!0);
    var i = e.getFieldsMap(!0);
    return t.map(function(r) {
      var n = g(r);
      return i.get(n) || {
        INVALIDATE_NAME_PATH: g(r)
      };
    });
  }), a(this, "getFieldsValue", function(t, i) {
    e.warningUnhooked();
    var r, n, l;
    if (t === !0 || Array.isArray(t) ? (r = t, n = i) : t && x(t) === "object" && (l = t.strict, n = t.filter), r === !0 && !n)
      return e.store;
    var s = e.getFieldEntitiesForNamePathList(Array.isArray(r) ? r : null), o = [];
    return s.forEach(function(u) {
      var d, f, F = "INVALIDATE_NAME_PATH" in u ? u.INVALIDATE_NAME_PATH : u.getNamePath();
      if (l) {
        var m, h;
        if ((m = (h = u).isList) !== null && m !== void 0 && m.call(h))
          return;
      } else if (!r && (d = (f = u).isListField) !== null && d !== void 0 && d.call(f))
        return;
      if (!n)
        o.push(F);
      else {
        var v = "getMeta" in u ? u.getMeta() : null;
        n(v) && o.push(F);
      }
    }), D(e.store, o.map(g));
  }), a(this, "getFieldValue", function(t) {
    e.warningUnhooked();
    var i = g(t);
    return W(e.store, i);
  }), a(this, "getFieldsError", function(t) {
    e.warningUnhooked();
    var i = e.getFieldEntitiesForNamePathList(t);
    return i.map(function(r, n) {
      return r && !("INVALIDATE_NAME_PATH" in r) ? {
        name: r.getNamePath(),
        errors: r.getErrors(),
        warnings: r.getWarnings()
      } : {
        name: g(t[n]),
        errors: [],
        warnings: []
      };
    });
  }), a(this, "getFieldError", function(t) {
    e.warningUnhooked();
    var i = g(t), r = e.getFieldsError([i])[0];
    return r.errors;
  }), a(this, "getFieldWarning", function(t) {
    e.warningUnhooked();
    var i = g(t), r = e.getFieldsError([i])[0];
    return r.warnings;
  }), a(this, "isFieldsTouched", function() {
    e.warningUnhooked();
    for (var t = arguments.length, i = new Array(t), r = 0; r < t; r++)
      i[r] = arguments[r];
    var n = i[0], l = i[1], s, o = !1;
    i.length === 0 ? s = null : i.length === 1 ? Array.isArray(n) ? (s = n.map(g), o = !1) : (s = null, o = n) : (s = n.map(g), o = l);
    var u = e.getFieldEntities(!0), d = function(v) {
      return v.isFieldTouched();
    };
    if (!s)
      return o ? u.every(d) : u.some(d);
    var f = new N();
    s.forEach(function(h) {
      f.set(h, []);
    }), u.forEach(function(h) {
      var v = h.getNamePath();
      s.forEach(function(I) {
        I.every(function(c, p) {
          return v[p] === c;
        }) && f.update(I, function(c) {
          return [].concat(P(c), [h]);
        });
      });
    });
    var F = function(v) {
      return v.some(d);
    }, m = f.map(function(h) {
      var v = h.value;
      return v;
    });
    return o ? m.every(F) : m.some(F);
  }), a(this, "isFieldTouched", function(t) {
    return e.warningUnhooked(), e.isFieldsTouched([t]);
  }), a(this, "isFieldsValidating", function(t) {
    e.warningUnhooked();
    var i = e.getFieldEntities();
    if (!t)
      return i.some(function(n) {
        return n.isFieldValidating();
      });
    var r = t.map(g);
    return i.some(function(n) {
      var l = n.getNamePath();
      return M(r, l) && n.isFieldValidating();
    });
  }), a(this, "isFieldValidating", function(t) {
    return e.warningUnhooked(), e.isFieldsValidating([t]);
  }), a(this, "resetWithFieldInitialValue", function() {
    var t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, i = new N(), r = e.getFieldEntities(!0);
    r.forEach(function(s) {
      var o = s.props.initialValue, u = s.getNamePath();
      if (o !== void 0) {
        var d = i.get(u) || /* @__PURE__ */ new Set();
        d.add({
          entity: s,
          value: o
        }), i.set(u, d);
      }
    });
    var n = function(o) {
      o.forEach(function(u) {
        var d = u.props.initialValue;
        if (d !== void 0) {
          var f = u.getNamePath(), F = e.getInitialValue(f);
          if (F !== void 0)
            U(!1, "Form already set 'initialValues' with path '".concat(f.join("."), "'. Field can not overwrite it."));
          else {
            var m = i.get(f);
            if (m && m.size > 1)
              U(!1, "Multiple Field with path '".concat(f.join("."), "' set 'initialValue'. Can not decide which one to pick."));
            else if (m) {
              var h = e.getFieldValue(f), v = u.isListField();
              !v && (!t.skipExist || h === void 0) && e.updateStore(E(e.store, f, P(m)[0].value));
            }
          }
        }
      });
    }, l;
    t.entities ? l = t.entities : t.namePathList ? (l = [], t.namePathList.forEach(function(s) {
      var o = i.get(s);
      if (o) {
        var u;
        (u = l).push.apply(u, P(P(o).map(function(d) {
          return d.entity;
        })));
      }
    })) : l = r, n(l);
  }), a(this, "resetFields", function(t) {
    e.warningUnhooked();
    var i = e.store;
    if (!t) {
      e.updateStore(L(e.initialValues)), e.resetWithFieldInitialValue(), e.notifyObservers(i, null, {
        type: "reset"
      }), e.notifyWatch();
      return;
    }
    var r = t.map(g);
    r.forEach(function(n) {
      var l = e.getInitialValue(n);
      e.updateStore(E(e.store, n, l));
    }), e.resetWithFieldInitialValue({
      namePathList: r
    }), e.notifyObservers(i, r, {
      type: "reset"
    }), e.notifyWatch(r);
  }), a(this, "setFields", function(t) {
    e.warningUnhooked();
    var i = e.store, r = [];
    t.forEach(function(n) {
      var l = n.name, s = j(n, J), o = g(l);
      r.push(o), "value" in s && e.updateStore(E(e.store, o, s.value)), e.notifyObservers(i, [o], {
        type: "setField",
        data: n
      });
    }), e.notifyWatch(r);
  }), a(this, "getFields", function() {
    var t = e.getFieldEntities(!0), i = t.map(function(r) {
      var n = r.getNamePath(), l = r.getMeta(), s = V(V({}, l), {}, {
        name: n,
        value: e.getFieldValue(n)
      });
      return Object.defineProperty(s, "originRCField", {
        value: !0
      }), s;
    });
    return i;
  }), a(this, "initEntityValue", function(t) {
    var i = t.props.initialValue;
    if (i !== void 0) {
      var r = t.getNamePath(), n = W(e.store, r);
      n === void 0 && e.updateStore(E(e.store, r, i));
    }
  }), a(this, "isMergedPreserve", function(t) {
    var i = t !== void 0 ? t : e.preserve;
    return i ?? !0;
  }), a(this, "registerField", function(t) {
    e.fieldEntities.push(t);
    var i = t.getNamePath();
    if (e.notifyWatch([i]), t.props.initialValue !== void 0) {
      var r = e.store;
      e.resetWithFieldInitialValue({
        entities: [t],
        skipExist: !0
      }), e.notifyObservers(r, [t.getNamePath()], {
        type: "valueUpdate",
        source: "internal"
      });
    }
    return function(n, l) {
      var s = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : [];
      if (e.fieldEntities = e.fieldEntities.filter(function(d) {
        return d !== t;
      }), !e.isMergedPreserve(l) && (!n || s.length > 1)) {
        var o = n ? void 0 : e.getInitialValue(i);
        if (i.length && e.getFieldValue(i) !== o && e.fieldEntities.every(function(d) {
          return (
            // Only reset when no namePath exist
            !G(d.getNamePath(), i)
          );
        })) {
          var u = e.store;
          e.updateStore(E(u, i, o, !0)), e.notifyObservers(u, [i], {
            type: "remove"
          }), e.triggerDependenciesUpdate(u, i);
        }
      }
      e.notifyWatch([i]);
    };
  }), a(this, "dispatch", function(t) {
    switch (t.type) {
      case "updateValue": {
        var i = t.namePath, r = t.value;
        e.updateValue(i, r);
        break;
      }
      case "validateField": {
        var n = t.namePath, l = t.triggerName;
        e.validateFields([n], {
          triggerName: l
        });
        break;
      }
    }
  }), a(this, "notifyObservers", function(t, i, r) {
    if (e.subscribable) {
      var n = V(V({}, r), {}, {
        store: e.getFieldsValue(!0)
      });
      e.getFieldEntities().forEach(function(l) {
        var s = l.onStoreChange;
        s(t, i, n);
      });
    } else
      e.forceRootUpdate();
  }), a(this, "triggerDependenciesUpdate", function(t, i) {
    var r = e.getDependencyChildrenFields(i);
    return r.length && e.validateFields(r), e.notifyObservers(t, r, {
      type: "dependenciesUpdate",
      relatedFields: [i].concat(P(r))
    }), r;
  }), a(this, "updateValue", function(t, i) {
    var r = g(t), n = e.store;
    e.updateStore(E(e.store, r, i)), e.notifyObservers(n, [r], {
      type: "valueUpdate",
      source: "internal"
    }), e.notifyWatch([r]);
    var l = e.triggerDependenciesUpdate(n, r), s = e.callbacks.onValuesChange;
    if (s) {
      var o = D(e.store, [r]);
      s(o, e.getFieldsValue());
    }
    e.triggerOnFieldsChange([r].concat(P(l)));
  }), a(this, "setFieldsValue", function(t) {
    e.warningUnhooked();
    var i = e.store;
    if (t) {
      var r = L(e.store, t);
      e.updateStore(r);
    }
    e.notifyObservers(i, null, {
      type: "valueUpdate",
      source: "external"
    }), e.notifyWatch();
  }), a(this, "setFieldValue", function(t, i) {
    e.setFields([{
      name: t,
      value: i
    }]);
  }), a(this, "getDependencyChildrenFields", function(t) {
    var i = /* @__PURE__ */ new Set(), r = [], n = new N();
    e.getFieldEntities().forEach(function(s) {
      var o = s.props.dependencies;
      (o || []).forEach(function(u) {
        var d = g(u);
        n.update(d, function() {
          var f = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : /* @__PURE__ */ new Set();
          return f.add(s), f;
        });
      });
    });
    var l = function s(o) {
      var u = n.get(o) || /* @__PURE__ */ new Set();
      u.forEach(function(d) {
        if (!i.has(d)) {
          i.add(d);
          var f = d.getNamePath();
          d.isFieldDirty() && f.length && (r.push(f), s(f));
        }
      });
    };
    return l(t), r;
  }), a(this, "triggerOnFieldsChange", function(t, i) {
    var r = e.callbacks.onFieldsChange;
    if (r) {
      var n = e.getFields();
      if (i) {
        var l = new N();
        i.forEach(function(o) {
          var u = o.name, d = o.errors;
          l.set(u, d);
        }), n.forEach(function(o) {
          o.errors = l.get(o.name) || o.errors;
        });
      }
      var s = n.filter(function(o) {
        var u = o.name;
        return M(t, u);
      });
      s.length && r(s, n);
    }
  }), a(this, "validateFields", function(t, i) {
    e.warningUnhooked();
    var r, n;
    Array.isArray(t) || typeof t == "string" || typeof i == "string" ? (r = t, n = i) : n = t;
    var l = !!r, s = l ? r.map(g) : [], o = [], u = String(Date.now()), d = /* @__PURE__ */ new Set(), f = n || {}, F = f.recursive, m = f.dirty;
    e.getFieldEntities(!0).forEach(function(c) {
      if (l || s.push(c.getNamePath()), !(!c.props.rules || !c.props.rules.length) && !(m && !c.isFieldDirty())) {
        var p = c.getNamePath();
        if (d.add(p.join(u)), !l || M(s, p, F)) {
          var w = c.validateRules(V({
            validateMessages: V(V({}, q), e.validateMessages)
          }, n));
          o.push(w.then(function() {
            return {
              name: p,
              errors: [],
              warnings: []
            };
          }).catch(function(S) {
            var T, b = [], A = [];
            return (T = S.forEach) === null || T === void 0 || T.call(S, function(C) {
              var R = C.rule.warningOnly, O = C.errors;
              R ? A.push.apply(A, P(O)) : b.push.apply(b, P(O));
            }), b.length ? Promise.reject({
              name: p,
              errors: b,
              warnings: A
            }) : {
              name: p,
              errors: b,
              warnings: A
            };
          }));
        }
      }
    });
    var h = $(o);
    e.lastValidatePromise = h, h.catch(function(c) {
      return c;
    }).then(function(c) {
      var p = c.map(function(w) {
        var S = w.name;
        return S;
      });
      e.notifyObservers(e.store, p, {
        type: "validateFinish"
      }), e.triggerOnFieldsChange(p, c);
    });
    var v = h.then(function() {
      return e.lastValidatePromise === h ? Promise.resolve(e.getFieldsValue(s)) : Promise.reject([]);
    }).catch(function(c) {
      var p = c.filter(function(w) {
        return w && w.errors.length;
      });
      return Promise.reject({
        values: e.getFieldsValue(s),
        errorFields: p,
        outOfDate: e.lastValidatePromise !== h
      });
    });
    v.catch(function(c) {
      return c;
    });
    var I = s.filter(function(c) {
      return d.has(c.join(u));
    });
    return e.triggerOnFieldsChange(I), v;
  }), a(this, "submit", function() {
    e.warningUnhooked(), e.validateFields().then(function(t) {
      var i = e.callbacks.onFinish;
      if (i)
        try {
          i(t);
        } catch (r) {
          console.error(r);
        }
    }).catch(function(t) {
      var i = e.callbacks.onFinishFailed;
      i && i(t);
    });
  }), this.forceRootUpdate = y;
});
function he(k) {
  var y = _.useRef(), e = _.useState({}), t = H(e, 2), i = t[1];
  if (!y.current)
    if (k)
      y.current = k;
    else {
      var r = function() {
        i({});
      }, n = new Q(r);
      y.current = n.getForm();
    }
  return [y.current];
}
export {
  Q as FormStore,
  he as default
};
