/**
 * ldesign v0.3.13
 * (c) 2023 ldesign
 * @license MIT
 */

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { defineComponent, toRefs, provide, ref, reactive, computed, createVNode } from 'vue';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import isEmpty from 'lodash/isEmpty';
import isBoolean from 'lodash/isBoolean';
import isArray from 'lodash/isArray';
import isFunction from 'lodash/isFunction';
import { requestSubmit } from '../utils/dom.js';
import '../hooks/index.js';
import props from './props.js';
import { FormInjectionKey, useCLASSNAMES } from './const.js';
import { useTNodeJSX } from '../hooks/tnode.js';
import { usePrefixClass } from '../hooks/useConfig.js';
import '../_chunks/dep-512eb181.js';
import 'lodash/isString';
import '../utils/easing.js';
import '../hooks/icon.js';
import '../hooks/slot.js';
import '../hooks/useCommonClassName.js';
import '../config-provider/useConfig.js';
import 'lodash/cloneDeep';
import '../config-provider/context.js';
import 'lodash/mergeWith';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '@babel/runtime/helpers/typeof';
import 'dayjs';
import '../_chunks/dep-ac28b67c.js';
import '../config-provider/type.js';
import '../hooks/useDefaultValue.js';
import 'lodash/kebabCase';
import '../hooks/useDestroyOnClose.js';
import '../hooks/useKeepAnimation.js';
import '../hooks/useRipple.js';
import '../utils/set-style.js';
import '../hooks/useVirtualScroll.js';
import '../hooks/useVModel.js';
import 'lodash/camelCase';
import '../utils/render-tnode.js';
import 'lodash/isObject';

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var _Form = defineComponent({
  name: "TForm",
  props: _objectSpread({}, props),
  setup: function setup(props2, _ref) {
    var expose = _ref.expose;
    var renderContent = useTNodeJSX();
    var _toRefs = toRefs(props2),
      disabled = _toRefs.disabled;
    provide("formDisabled", {
      disabled: disabled
    });
    var formRef = ref(null);
    var children = ref([]);
    var _toRefs2 = toRefs(props2),
      showErrorMessage = _toRefs2.showErrorMessage,
      labelWidth = _toRefs2.labelWidth,
      labelAlign = _toRefs2.labelAlign,
      data = _toRefs2.data,
      colon = _toRefs2.colon,
      requiredMark = _toRefs2.requiredMark,
      rules = _toRefs2.rules,
      errorMessage = _toRefs2.errorMessage,
      resetType = _toRefs2.resetType;
    provide(FormInjectionKey, reactive({
      showErrorMessage: showErrorMessage,
      labelWidth: labelWidth,
      labelAlign: labelAlign,
      data: data,
      colon: colon,
      requiredMark: requiredMark,
      rules: rules,
      errorMessage: errorMessage,
      resetType: resetType,
      children: children,
      renderContent: renderContent
    }));
    var COMPONENT_NAME = usePrefixClass("form");
    var CLASS_NAMES = useCLASSNAMES();
    var formClass = computed(function () {
      return [CLASS_NAMES.value.form, _defineProperty({}, "".concat(COMPONENT_NAME.value, "-inline"), props2.layout === "inline")];
    });
    var FORM_ITEM_CLASS_PREFIX = usePrefixClass("form-item__");
    var getFirstError = function getFirstError(result) {
      if (isBoolean(result)) return "";
      var _Object$keys = Object.keys(result),
        _Object$keys2 = _slicedToArray(_Object$keys, 1),
        firstKey = _Object$keys2[0];
      if (props2.scrollToFirstError) scrollTo(".".concat(FORM_ITEM_CLASS_PREFIX.value + firstKey));
      var resArr = result[firstKey];
      if (!isArray(resArr)) return "";
      return resArr.filter(function (item) {
        return !item.result;
      })[0].message;
    };
    var scrollTo = function scrollTo(selector) {
      var _formRef$value;
      var dom = (_formRef$value = formRef.value) === null || _formRef$value === void 0 ? void 0 : _formRef$value.querySelector(selector);
      var behavior = props2.scrollToFirstError;
      if (behavior) dom && dom.scrollIntoView({
        behavior: behavior
      });
    };
    var needValidate = function needValidate(name, fields) {
      if (!fields || !isArray(fields)) return true;
      return fields.includes("".concat(name));
    };
    var formatValidateResult = function formatValidateResult(validateResultList) {
      var result = validateResultList.reduce(function (r, err) {
        return Object.assign(r || {}, err);
      }, {});
      Object.keys(result).forEach(function (key) {
        if (result[key] === true) delete result[key];
      });
      return isEmpty(result) ? true : result;
    };
    var validate = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(param) {
        var _props2$onValidate;
        var _ref4, fields, _ref4$trigger, trigger, showErrorMessage2, list, arr, result, firstError;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _ref4 = param || {}, fields = _ref4.fields, _ref4$trigger = _ref4.trigger, trigger = _ref4$trigger === void 0 ? "all" : _ref4$trigger, showErrorMessage2 = _ref4.showErrorMessage;
              list = children.value.filter(function (child) {
                return isFunction(child.validate) && needValidate(String(child.name), fields);
              }).map(function (child) {
                return child.validate(trigger, showErrorMessage2);
              });
              _context.next = 4;
              return Promise.all(list);
            case 4:
              arr = _context.sent;
              result = formatValidateResult(arr);
              firstError = getFirstError(result);
              (_props2$onValidate = props2.onValidate) === null || _props2$onValidate === void 0 ? void 0 : _props2$onValidate.call(props2, {
                validateResult: result,
                firstError: firstError
              });
              return _context.abrupt("return", result);
            case 9:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function validate(_x) {
        return _ref3.apply(this, arguments);
      };
    }();
    var validateOnly = /*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(params) {
        var _ref6, fields, _ref6$trigger, trigger, list, arr;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _ref6 = params || {}, fields = _ref6.fields, _ref6$trigger = _ref6.trigger, trigger = _ref6$trigger === void 0 ? "all" : _ref6$trigger;
              list = children.value.filter(function (child) {
                return isFunction(child.validateOnly) && needValidate(String(child.name), fields);
              }).map(function (child) {
                return child.validateOnly(trigger);
              });
              _context2.next = 4;
              return Promise.all(list);
            case 4:
              arr = _context2.sent;
              return _context2.abrupt("return", formatValidateResult(arr));
            case 6:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return function validateOnly(_x2) {
        return _ref5.apply(this, arguments);
      };
    }();
    var submitParams = ref();
    var _onSubmit = function onSubmit(e) {
      if (props2.preventSubmitDefault && e) {
        e.preventDefault();
        e.stopPropagation();
      }
      validate(submitParams.value).then(function (r) {
        var _props2$onSubmit;
        (_props2$onSubmit = props2.onSubmit) === null || _props2$onSubmit === void 0 ? void 0 : _props2$onSubmit.call(props2, {
          validateResult: r,
          firstError: getFirstError(r),
          e: e
        });
      });
      submitParams.value = void 0;
    };
    var submit = /*#__PURE__*/function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(params) {
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              submitParams.value = params;
              requestSubmit(formRef.value);
            case 2:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      return function submit(_x3) {
        return _ref7.apply(this, arguments);
      };
    }();
    var resetParams = ref();
    var _onReset = function onReset(e) {
      var _props2$onReset;
      if (props2.preventSubmitDefault && e) {
        e.preventDefault();
        e.stopPropagation();
      }
      children.value.filter(function (child) {
        var _resetParams$value;
        return isFunction(child.resetField) && needValidate(String(child.name), (_resetParams$value = resetParams.value) === null || _resetParams$value === void 0 ? void 0 : _resetParams$value.fields);
      }).forEach(function (child) {
        var _resetParams$value2;
        return child.resetField((_resetParams$value2 = resetParams.value) === null || _resetParams$value2 === void 0 ? void 0 : _resetParams$value2.type);
      });
      resetParams.value = void 0;
      (_props2$onReset = props2.onReset) === null || _props2$onReset === void 0 ? void 0 : _props2$onReset.call(props2, {
        e: e
      });
    };
    var reset = function reset(params) {
      resetParams.value = params;
      formRef.value.reset();
    };
    var clearValidate = function clearValidate(fields) {
      children.value.forEach(function (child) {
        if (isFunction(child.resetHandler) && needValidate(String(child.name), fields)) child.resetHandler();
      });
    };
    var setValidateMessage = function setValidateMessage(validateMessage) {
      var keys = Object.keys(validateMessage);
      if (!keys.length) return;
      var list = children.value.filter(function (child) {
        return isFunction(child.setValidateMessage) && keys.includes("".concat(child.name));
      }).map(function (child) {
        return child.setValidateMessage(validateMessage[child.name]);
      });
      Promise.all(list);
    };
    expose({
      validate: validate,
      submit: submit,
      reset: reset,
      clearValidate: clearValidate,
      setValidateMessage: setValidateMessage,
      validateOnly: validateOnly
    });
    return function () {
      return createVNode("form", {
        "ref": formRef,
        "class": formClass.value,
        "onSubmit": function onSubmit(e) {
          return _onSubmit(e);
        },
        "onReset": function onReset(e) {
          return _onReset(e);
        }
      }, [renderContent("default")]);
    };
  }
});

export { _Form as default };
//# sourceMappingURL=form.js.map
