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

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var vue = require('vue');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var isEmpty = require('lodash/isEmpty');
var isBoolean = require('lodash/isBoolean');
var isArray = require('lodash/isArray');
var isFunction = require('lodash/isFunction');
var utils_dom = require('../utils/dom.js');
var form_props = require('./props.js');
var form_const = require('./const.js');
var hooks_tnode = require('../hooks/tnode.js');
var hooks_useConfig = require('../hooks/useConfig.js');
require('../_chunks/dep-f4db2590.js');
require('lodash/isString');
require('../utils/easing.js');
require('lodash/camelCase');
require('lodash/kebabCase');
require('../utils/render-tnode.js');
require('lodash/isObject');
require('../config-provider/useConfig.js');
require('lodash/cloneDeep');
require('../config-provider/context.js');
require('lodash/mergeWith');
require('lodash/merge');
require('../_common/js/global-config/default-config.js');
require('../_common/js/global-config/locale/zh_CN.js');
require('@babel/runtime/helpers/typeof');
require('dayjs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var isEmpty__default = /*#__PURE__*/_interopDefaultLegacy(isEmpty);
var isBoolean__default = /*#__PURE__*/_interopDefaultLegacy(isBoolean);
var isArray__default = /*#__PURE__*/_interopDefaultLegacy(isArray);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

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__default["default"](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 = vue.defineComponent({
  name: "TForm",
  props: _objectSpread({}, form_props["default"]),
  setup: function setup(props2, _ref) {
    var expose = _ref.expose;
    var renderContent = hooks_tnode.useTNodeJSX();
    var _toRefs = vue.toRefs(props2),
      disabled = _toRefs.disabled;
    vue.provide("formDisabled", {
      disabled: disabled
    });
    var formRef = vue.ref(null);
    var children = vue.ref([]);
    var _toRefs2 = vue.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;
    vue.provide(form_const.FormInjectionKey, vue.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 = hooks_useConfig.usePrefixClass("form");
    var CLASS_NAMES = form_const.useCLASSNAMES();
    var formClass = vue.computed(function () {
      return [CLASS_NAMES.value.form, _defineProperty__default["default"]({}, "".concat(COMPONENT_NAME.value, "-inline"), props2.layout === "inline")];
    });
    var FORM_ITEM_CLASS_PREFIX = hooks_useConfig.usePrefixClass("form-item__");
    var getFirstError = function getFirstError(result) {
      if (isBoolean__default["default"](result)) return "";
      var _Object$keys = Object.keys(result),
        _Object$keys2 = _slicedToArray__default["default"](_Object$keys, 1),
        firstKey = _Object$keys2[0];
      if (props2.scrollToFirstError) scrollTo(".".concat(FORM_ITEM_CLASS_PREFIX.value + firstKey));
      var resArr = result[firstKey];
      if (!isArray__default["default"](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__default["default"](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__default["default"](result) ? true : result;
    };
    var validate = /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee(param) {
        var _props2$onValidate;
        var _ref4, fields, _ref4$trigger, trigger, showErrorMessage2, list, arr, result, firstError;
        return _regeneratorRuntime__default["default"].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__default["default"](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__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(params) {
        var _ref6, fields, _ref6$trigger, trigger, list, arr;
        return _regeneratorRuntime__default["default"].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__default["default"](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 = vue.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__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(params) {
        return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              submitParams.value = params;
              utils_dom.requestSubmit(formRef.value);
            case 2:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      return function submit(_x3) {
        return _ref7.apply(this, arguments);
      };
    }();
    var resetParams = vue.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__default["default"](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__default["default"](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__default["default"](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 vue.createVNode("form", {
        "ref": formRef,
        "class": formClass.value,
        "onSubmit": function onSubmit(e) {
          return _onSubmit(e);
        },
        "onReset": function onReset(e) {
          return _onReset(e);
        }
      }, [renderContent("default")]);
    };
  }
});

exports["default"] = _Form;
//# sourceMappingURL=form.js.map
