import _defineProperty from '@babel/runtime/helpers/esm/defineProperty';
import { defineComponent, computed, provide, toRefs, openBlock, createElementBlock, normalizeClass, normalizeStyle, renderSlot } from 'vue';
import { pxfy } from '../_util/utils';
import getPrefixCls from '../_util/getPrefixCls';
import { useTheme } from '../_theme/useTheme';
import { FORM_NAME, FORM_LAYOUT, provideKey, TRIGGER_TYPE_DEFAULT } from './const';
import { allPromiseFinish } from './utils';
import { formProps } from './interface';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
const prefixCls = getPrefixCls('form');
var script = defineComponent({
  name: FORM_NAME,
  props: formProps,
  emits: ['submit'],
  setup(props, _ref) {
    let {
      emit
    } = _ref;
    useTheme();
    const formFields = {};
    const formClass = computed(() => [prefixCls, `${prefixCls}-${props.layout}`, props.disabled && `${prefixCls}-disabled` // disabled
    ]);
    const formStyle = computed(() => {
      const tempColStyle = props.layout === FORM_LAYOUT.INLINE && props.inlineItemWidth && {
        'grid-template-columns': `repeat(auto-fit, ${pxfy(props.inlineItemWidth)})`
      };
      const gapStyle = props.layout === FORM_LAYOUT.INLINE && props.inlineItemGap && {
        'grid-gap': `${pxfy(props.inlineItemGap)}`
      };
      return _objectSpread(_objectSpread({}, tempColStyle), gapStyle);
    });
    const addField = (formItemProp, formItemContext) => {
      if (formItemProp) {
        formFields[formItemProp] = formItemContext;
      }
    };
    const removeField = formItemProp => {
      delete formFields[formItemProp];
    };
    const validateFields = async function (fieldProps) {
      let trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : TRIGGER_TYPE_DEFAULT;
      if (!props.model) {
        return Promise.reject('Form `model` is required for resetFields to work.');
      }

      // 是否指定prop: 【部分】表单字段校验调用会指定; 【整个】表单校验调用则不会指定
      const specifyPropsFlag = Boolean(fieldProps.length);
      const promiseList = []; // 原始校验结果

      Object.values(formFields).forEach(formField => {
        // Skip if Specify prop but not include
        if (specifyPropsFlag && !fieldProps.includes(formField.prop)) {
          return;
        }
        const promise = formField.validateRules(trigger);
        promiseList.push(promise.then(() => ({
          name: formField.prop,
          errors: []
        })).catch(errors => Promise.reject({
          name: formField.prop,
          errors
        })));
      });
      try {
        return await allPromiseFinish(promiseList); // 汇总校验结果;
      } catch (results) {
        const errorList = [];
        const errorNameList = [];
        results === null || results === void 0 || results.forEach(result => {
          var _result$errors;
          if (result !== null && result !== void 0 && (_result$errors = result.errors) !== null && _result$errors !== void 0 && _result$errors.length) {
            errorList.push(result);
            errorNameList.push(result === null || result === void 0 ? void 0 : result.name);
          }
        });
        return Promise.reject({
          valid: false,
          values: errorNameList,
          errorFields: errorList
        });
      }
    };

    /**
     * 表单校验
     *    fieldProps { string[] }    指定校验字段的 props 数组
     *    return    { Promise }   校验结果
     */
    const validate = function () {
      let fieldProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      return validateFields(fieldProps);
    };

    /** 移除表单项的校验结果 */
    const clearValidate = function () {
      let fieldProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      if (!props.model) {
        return Promise.reject('Form `model` is required for resetFields to work.');
      }

      // 是否指定prop: 【部分】表单字段校验调用会指定; 【整个】表单校验调用则不会指定
      const specifyPropsFlag = Boolean(fieldProps.length);
      Object.values(formFields).forEach(formField => {
        // Skip if Specify prop but not include
        if (specifyPropsFlag && !fieldProps.includes(formField.prop)) {
          return;
        }
        formField.clearValidate();
      });
    };

    /** 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果 */
    const resetFields = function () {
      let fieldProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      if (!props.model) {
        return Promise.reject('Form `model` is required for resetFields to work.');
      }

      // 是否指定prop: 【部分】表单字段校验调用会指定; 【整个】表单校验调用则不会指定
      const specifyPropsFlag = Boolean(fieldProps.length);
      Object.values(formFields).forEach(formField => {
        // Skip if Specify prop but not include
        if (specifyPropsFlag && !fieldProps.includes(formField.prop)) {
          return;
        }
        formField.resetField();
      });
    };
    provide(provideKey, _objectSpread(_objectSpread({}, toRefs(props)), {}, {
      addField,
      removeField
    }));
    const handleSubmit = e => {
      e.preventDefault();
      e.stopPropagation();
      emit('submit', e);
    };
    return {
      formClass,
      formStyle,
      validate,
      clearValidate,
      resetFields,
      handleSubmit
    };
  }
});

function render(_ctx, _cache, $props, $setup, $data, $options) {
  return openBlock(), createElementBlock("form", {
    class: normalizeClass(_ctx.formClass),
    style: normalizeStyle(_ctx.formStyle),
    onSubmit: _cache[0] || (_cache[0] = function () {
      return _ctx.handleSubmit && _ctx.handleSubmit(...arguments);
    })
  }, [renderSlot(_ctx.$slots, "default")], 38 /* CLASS, STYLE, NEED_HYDRATION */);
}

script.render = render;
script.__file = "components/form/form.vue";

export { script as default };
