"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const types = require("../../../utils/types.js");
const objects = require("../../../utils/objects.js");
const style = require("../../../utils/dom/style.js");
const index = require("../../../hooks/use-namespace/index.js");
const index$1 = require("../../../hooks/use-id/index.js");
const constants = require("./constants.js");
const useFormCommonProps = require("./hooks/use-form-common-props.js");
const formItem = require("./form-item.js");
const formLabelWrap = require("./form-label-wrap.js");
const Vue = require("vue");
const index$3 = require("../../../../../async-validator/dist-web/index.js");
const index$2 = require("../../../../node_modules/@vueuse/shared/index.js");
const shared_esmBundler = require("../../../../../@vue/shared/dist/shared.esm-bundler.js");
const castArray = require("../../../../../lodash-es/castArray.js");
const cloneDeep = require("../../../../../lodash-es/cloneDeep.js");
const _hoisted_1 = ["role", "aria-labelledby"];
var form_item_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ Vue.defineComponent({
  name: "ElFormItem",
  __name: "form-item",
  props: formItem.formItemProps,
  setup(__props, { expose: __expose }) {
    const props = __props;
    const slots = Vue.useSlots();
    const formContext = Vue.inject(constants.formContextKey, void 0);
    const parentFormItemContext = Vue.inject(constants.formItemContextKey, void 0);
    const _size = useFormCommonProps.useFormSize(void 0, { formItem: false });
    const ns = index.useNamespace("form-item");
    const labelId = index$1.useId().value;
    const inputIds = Vue.ref([]);
    const validateState = Vue.ref("");
    const validateStateDebounced = index$2.debouncedRef(validateState, 100);
    const validateMessage = Vue.ref("");
    const formItemRef = Vue.ref();
    let initialValue = void 0;
    let isResettingField = false;
    const labelPosition = Vue.computed(() => props.labelPosition || (formContext == null ? void 0 : formContext.labelPosition));
    const labelStyle = Vue.computed(() => {
      if (labelPosition.value === "top") return {};
      return { width: style.addUnit(props.labelWidth ?? (formContext == null ? void 0 : formContext.labelWidth)) };
    });
    const contentStyle = Vue.computed(() => {
      if (labelPosition.value === "top" || (formContext == null ? void 0 : formContext.inline)) return {};
      if (!props.label && !props.labelWidth && isNested) return {};
      const labelWidth = style.addUnit(props.labelWidth ?? (formContext == null ? void 0 : formContext.labelWidth));
      if (!props.label && !slots.label) return { marginLeft: labelWidth };
      return {};
    });
    const formItemClasses = Vue.computed(() => [
      ns.b(),
      ns.m(_size.value),
      ns.is("error", validateState.value === "error"),
      ns.is("validating", validateState.value === "validating"),
      ns.is("success", validateState.value === "success"),
      ns.is("required", isRequired.value || props.required),
      ns.is("no-asterisk", formContext == null ? void 0 : formContext.hideRequiredAsterisk),
      (formContext == null ? void 0 : formContext.requireAsteriskPosition) === "right" ? "asterisk-right" : "asterisk-left",
      {
        [ns.m("feedback")]: formContext == null ? void 0 : formContext.statusIcon,
        [ns.m(`label-${labelPosition.value}`)]: labelPosition.value
      }
    ]);
    const _inlineMessage = Vue.computed(() => types.isBoolean(props.inlineMessage) ? props.inlineMessage : (formContext == null ? void 0 : formContext.inlineMessage) || false);
    const validateClasses = Vue.computed(() => [ns.e("error"), { [ns.em("error", "inline")]: _inlineMessage.value }]);
    const propString = Vue.computed(() => {
      if (!props.prop) return "";
      return shared_esmBundler.isArray(props.prop) ? props.prop.join(".") : props.prop;
    });
    const hasLabel = Vue.computed(() => {
      return !!(props.label || slots.label);
    });
    const labelFor = Vue.computed(() => {
      return props.for ?? (inputIds.value.length === 1 ? inputIds.value[0] : void 0);
    });
    const isGroup = Vue.computed(() => {
      return !labelFor.value && hasLabel.value;
    });
    const isNested = !!parentFormItemContext;
    const fieldValue = Vue.computed(() => {
      const model = formContext == null ? void 0 : formContext.model;
      if (!model || !props.prop) return;
      return objects.getProp(model, props.prop).value;
    });
    const normalizedRules = Vue.computed(() => {
      const { required } = props;
      const rules = [];
      if (props.rules) rules.push(...castArray.default(props.rules));
      const formRules = formContext == null ? void 0 : formContext.rules;
      if (formRules && props.prop) {
        const _rules = objects.getProp(formRules, props.prop).value;
        if (_rules) rules.push(...castArray.default(_rules));
      }
      if (required !== void 0) {
        const requiredRules = rules.map((rule, i) => [rule, i]).filter(([rule]) => "required" in rule);
        if (requiredRules.length > 0) for (const [rule, i] of requiredRules) {
          if (rule.required === required) continue;
          rules[i] = {
            ...rule,
            required
          };
        }
        else rules.push({ required });
      }
      return rules;
    });
    const validateEnabled = Vue.computed(() => normalizedRules.value.length > 0);
    const getFilteredRule = (trigger) => {
      return normalizedRules.value.filter((rule) => {
        if (!rule.trigger || !trigger) return true;
        if (shared_esmBundler.isArray(rule.trigger)) return rule.trigger.includes(trigger);
        else return rule.trigger === trigger;
      }).map(({ trigger: trigger2, ...rule }) => rule);
    };
    const isRequired = Vue.computed(() => normalizedRules.value.some((rule) => rule.required));
    const shouldShowError = Vue.computed(() => validateStateDebounced.value === "error" && props.showMessage && ((formContext == null ? void 0 : formContext.showMessage) ?? true));
    const currentLabel = Vue.computed(() => `${props.label || ""}${(formContext == null ? void 0 : formContext.labelSuffix) || ""}`);
    const setValidationState = (state) => {
      validateState.value = state;
    };
    const onValidationFailed = (error) => {
      var _a;
      const { errors, fields } = error;
      if (!errors || !fields) console.error(error);
      setValidationState("error");
      validateMessage.value = errors ? ((_a = errors == null ? void 0 : errors[0]) == null ? void 0 : _a.message) ?? `${props.prop} is required` : "";
      formContext == null ? void 0 : formContext.emit("validate", props.prop, false, validateMessage.value);
    };
    const onValidationSucceeded = () => {
      setValidationState("success");
      formContext == null ? void 0 : formContext.emit("validate", props.prop, true, "");
    };
    const doValidate = async (rules) => {
      const modelName = propString.value;
      return new index$3.default({ [modelName]: rules }).validate({ [modelName]: fieldValue.value }, { firstFields: true }).then(() => {
        onValidationSucceeded();
        return true;
      }).catch((err) => {
        onValidationFailed(err);
        return Promise.reject(err);
      });
    };
    const validate = async (trigger, callback) => {
      if (isResettingField || !props.prop) return false;
      const hasCallback = shared_esmBundler.isFunction(callback);
      if (!validateEnabled.value) {
        callback == null ? void 0 : callback(false);
        return false;
      }
      const rules = getFilteredRule(trigger);
      if (rules.length === 0) {
        callback == null ? void 0 : callback(true);
        return true;
      }
      setValidationState("validating");
      return doValidate(rules).then(() => {
        callback == null ? void 0 : callback(true);
        return true;
      }).catch((err) => {
        const { fields } = err;
        callback == null ? void 0 : callback(false, fields);
        return hasCallback ? false : Promise.reject(fields);
      });
    };
    const clearValidate = () => {
      setValidationState("");
      validateMessage.value = "";
      isResettingField = false;
    };
    const resetField = async () => {
      const model = formContext == null ? void 0 : formContext.model;
      if (!model || !props.prop) return;
      const computedValue = objects.getProp(model, props.prop);
      isResettingField = true;
      computedValue.value = cloneDeep.default(initialValue);
      await Vue.nextTick();
      clearValidate();
      isResettingField = false;
    };
    const addInputId = (id) => {
      if (!inputIds.value.includes(id)) inputIds.value.push(id);
    };
    const removeInputId = (id) => {
      inputIds.value = inputIds.value.filter((listId) => listId !== id);
    };
    const setInitialValue = (value) => {
      initialValue = cloneDeep.default(value);
    };
    Vue.watch(() => props.error, (val) => {
      validateMessage.value = val || "";
      setValidationState(val ? "error" : "");
    }, { immediate: true });
    Vue.watch(() => props.validateStatus, (val) => setValidationState(val || ""));
    const context = Vue.reactive({
      ...Vue.toRefs(props),
      $el: formItemRef,
      size: _size,
      validateMessage,
      validateState,
      labelId,
      inputIds,
      isGroup,
      hasLabel,
      fieldValue,
      addInputId,
      removeInputId,
      resetField,
      clearValidate,
      validate,
      propString,
      setInitialValue
    });
    Vue.provide(constants.formItemContextKey, context);
    Vue.onMounted(() => {
      if (props.prop) {
        setInitialValue(fieldValue.value);
        formContext == null ? void 0 : formContext.addField(context);
      }
    });
    Vue.onBeforeUnmount(() => {
      formContext == null ? void 0 : formContext.removeField(context);
    });
    __expose({
      size: _size,
      validateMessage,
      validateState,
      validate,
      clearValidate,
      resetField,
      setInitialValue
    });
    return (_ctx, _cache) => {
      var _a;
      return Vue.openBlock(), Vue.createElementBlock("div", {
        ref_key: "formItemRef",
        ref: formItemRef,
        class: Vue.normalizeClass(formItemClasses.value),
        role: isGroup.value ? "group" : void 0,
        "aria-labelledby": isGroup.value ? Vue.unref(labelId) : void 0
      }, [Vue.createVNode(Vue.unref(formLabelWrap.default), {
        "is-auto-width": labelStyle.value.width === "auto",
        "update-all": ((_a = Vue.unref(formContext)) == null ? void 0 : _a.labelWidth) === "auto"
      }, {
        default: Vue.withCtx(() => [!!(__props.label || _ctx.$slots.label) ? (Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(labelFor.value ? "label" : "div"), {
          key: 0,
          id: Vue.unref(labelId),
          for: labelFor.value,
          class: Vue.normalizeClass(Vue.unref(ns).e("label")),
          style: Vue.normalizeStyle(labelStyle.value)
        }, {
          default: Vue.withCtx(() => [Vue.renderSlot(_ctx.$slots, "label", { label: currentLabel.value }, () => [Vue.createTextVNode(Vue.toDisplayString(currentLabel.value), 1)])]),
          _: 3
        }, 8, [
          "id",
          "for",
          "class",
          "style"
        ])) : Vue.createCommentVNode("v-if", true)]),
        _: 3
      }, 8, ["is-auto-width", "update-all"]), Vue.createElementVNode("div", {
        class: Vue.normalizeClass(Vue.unref(ns).e("content")),
        style: Vue.normalizeStyle(contentStyle.value)
      }, [Vue.renderSlot(_ctx.$slots, "default"), Vue.createVNode(Vue.TransitionGroup, { name: `${Vue.unref(ns).namespace.value}-zoom-in-top` }, {
        default: Vue.withCtx(() => [shouldShowError.value ? Vue.renderSlot(_ctx.$slots, "error", {
          key: 0,
          error: validateMessage.value
        }, () => [Vue.createElementVNode("div", { class: Vue.normalizeClass(validateClasses.value) }, Vue.toDisplayString(validateMessage.value), 3)]) : Vue.createCommentVNode("v-if", true)]),
        _: 3
      }, 8, ["name"])], 6)], 10, _hoisted_1);
    };
  }
});
exports.default = form_item_vue_vue_type_script_setup_true_lang_default;
