import { createVNode as _createVNode } from "vue";
import { defineComponent, provide } from "vue";
import { FormContextKey } from "./interface";
const formProps = {
  prefixCls: {
    default: 'x-form'
  },
  model: Object,
  layout: {
    type: String,
    default: 'horizontal'
  },
  labelWidth: Number,
  rules: Object
};
export default defineComponent({
  name: 'x-form',
  props: formProps,

  setup(props, {
    expose,
    slots
  }) {
    const formItems = {};

    function addItem(vm) {
      formItems[vm.props.prop] = vm;
    }

    function delItem(vm) {
      delete formItems[vm.props.prop];
    }

    async function validate() {
      await validateFields(Object.keys(formItems));
    }

    async function validateFields(fields) {
      const arr = fields.map(field => formItems[field]).map(item => {
        return item.validate();
      });
      await Promise.all(arr);
    }

    function clearValidate() {
      Object.values(formItems).forEach(item => item.clearValidate());
    }

    function resetFields() {
      Object.values(formItems).forEach(item => item.resetField());
    }

    expose({
      validate,
      validateFields,
      clearValidate,
      resetFields
    });
    provide(FormContextKey, {
      props,
      addItem,
      delItem
    });
    return () => {
      const {
        prefixCls,
        layout
      } = props;
      const cls = [prefixCls, `${prefixCls}-${layout}`];
      return _createVNode("form", {
        "class": cls
      }, { ...slots
      });
    };
  }

});