"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    SECRET: function() {
        return SECRET;
    },
    useForm: function() {
        return useForm;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _async_to_generator = require("@swc/helpers/_/_async_to_generator");
var _class_call_check = require("@swc/helpers/_/_class_call_check");
var _define_property = require("@swc/helpers/_/_define_property");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _to_consumable_array = require("@swc/helpers/_/_to_consumable_array");
var _ts_generator = require("@swc/helpers/_/_ts_generator");
var _ts_values = require("@swc/helpers/_/_ts_values");
var _react = require("react");
var _asyncvalidator = /*#__PURE__*/ _interop_require_default._(require("async-validator"));
var SECRET = 'NUT_FORM_INTERNAL';
/**
 * 用于存储表单的数据
 */ var FormStore = function FormStore() {
    "use strict";
    var _this = this;
    var _this1 = this;
    (0, _class_call_check._)(this, FormStore);
    var _this2 = this;
    // 初始化数据
    (0, _define_property._)(this, "initialValues", {});
    (0, _define_property._)(this, "updateList", []);
    // 存放表单中所有的数据 eg. {password: "ddd",username: "123"}
    (0, _define_property._)(this, "store", {});
    // 所有的组件实例
    (0, _define_property._)(this, "fieldEntities", []);
    // 校验成功或失败的回调，onFinish、onFinishFailed
    (0, _define_property._)(this, "callbacks", {});
    (0, _define_property._)(this, "errors", {});
    /**
   * 注册组件实例
   * @param field
   */ (0, _define_property._)(this, "registerField", function(field) {
        _this.fieldEntities.push(field);
        return function() {
            _this.fieldEntities = _this.fieldEntities.filter(function(item) {
                return item !== field;
            });
            if (_this.store) {
                delete _this.store[field.props.name];
            }
        };
    });
    /**
   * 获取 formItem 的值
   * @param name
   */ (0, _define_property._)(this, "getFieldValue", function(name) {
        var _this_store;
        return (_this_store = _this.store) === null || _this_store === void 0 ? void 0 : _this_store[name];
    });
    /**
   * 获取全部字段
   */ (0, _define_property._)(this, "getFieldsValue", function(nameList) {
        if (typeof nameList === 'boolean') {
            return JSON.parse(JSON.stringify(_this.store));
        }
        var fieldsValue = {};
        nameList.forEach(function(field) {
            fieldsValue[field] = _this.getFieldValue(field);
        });
        return fieldsValue;
    });
    /**
   * 设置 form 的初始值，之后在 reset 的时候使用
   * @param values
   * @param init
   */ (0, _define_property._)(this, "setInitialValues", function(values, init) {
        if (init) {
            _this.initialValues = values;
            _this.store = values;
        }
    });
    /**
   * 存储组件数据
   * @param newStore { [name]: newValue }
   */ (0, _define_property._)(this, "setFieldsValue", function(newStore) {
        var needValidate = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
        _this1.store = (0, _object_spread._)({}, _this1.store, newStore);
        _this1.fieldEntities.forEach(function(entity) {
            var name = entity.props.name;
            Object.keys(newStore).forEach(function(key) {
                if (key === name) {
                    entity.onStoreChange('update');
                }
            });
        });
        _this1.updateList.forEach(function(item) {
            var shouldUpdate = item.condition;
            if (typeof item.condition === 'function') {
                shouldUpdate = item.condition();
            }
            if (shouldUpdate) {
                item.entity.onStoreChange('update');
            }
        });
        needValidate && _this1.validateFields();
    });
    (0, _define_property._)(this, "setCallback", function(callback) {
        _this.callbacks = (0, _object_spread._)({}, _this.callbacks, callback);
    });
    (0, _define_property._)(this, "validateFields", /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function(nameList) {
            var filterEntitys, errs, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _loop, _iterator, _step, err;
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        filterEntitys = [];
                        errs = [];
                        _this2.errors.length = 0;
                        if (!nameList || nameList.length === 0) {
                            filterEntitys = _this2.fieldEntities;
                        } else {
                            filterEntitys = _this2.fieldEntities.filter(function(param) {
                                var name = param.props.name;
                                return nameList.includes(name);
                            });
                        }
                        _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                        _state.label = 1;
                    case 1:
                        _state.trys.push([
                            1,
                            6,
                            7,
                            8
                        ]);
                        _loop = function _loop() {
                            var entity, _entity_props, name, _entity_props_rules, rules, descriptor, validator, _this_store, param, errors, _errs;
                            return (0, _ts_generator._)(this, function(_state) {
                                switch(_state.label){
                                    case 0:
                                        entity = _step.value;
                                        _entity_props = entity.props, name = _entity_props.name, _entity_props_rules = _entity_props.rules, rules = _entity_props_rules === void 0 ? [] : _entity_props_rules;
                                        descriptor = {};
                                        if (rules.length) {
                                            // 多条校验规则
                                            if (rules.length > 1) {
                                                descriptor[name] = [];
                                                rules.forEach(function(v) {
                                                    descriptor[name].push(v);
                                                });
                                            } else {
                                                descriptor[name] = rules[0];
                                            }
                                        }
                                        validator = new _asyncvalidator.default(descriptor);
                                        _state.label = 1;
                                    case 1:
                                        _state.trys.push([
                                            1,
                                            3,
                                            4,
                                            5
                                        ]);
                                        return [
                                            4,
                                            validator.validate((0, _define_property._)({}, name, (_this_store = _this2.store) === null || _this_store === void 0 ? void 0 : _this_store[name]))
                                        ];
                                    case 2:
                                        _state.sent();
                                        return [
                                            3,
                                            5
                                        ];
                                    case 3:
                                        param = _state.sent();
                                        errors = param.errors;
                                        if (errors) {
                                            ;
                                            (_errs = errs).push.apply(_errs, (0, _to_consumable_array._)(errors));
                                            _this2.errors[name] = errors;
                                        }
                                        return [
                                            3,
                                            5
                                        ];
                                    case 4:
                                        if (!errs || errs.length === 0) {
                                            _this2.errors[name] = [];
                                        }
                                        return [
                                            7
                                        ];
                                    case 5:
                                        entity.onStoreChange('validate');
                                        return [
                                            2
                                        ];
                                }
                            });
                        };
                        _iterator = filterEntitys[Symbol.iterator]();
                        _state.label = 2;
                    case 2:
                        if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
                            3,
                            5
                        ];
                        return [
                            5,
                            (0, _ts_values._)(_loop())
                        ];
                    case 3:
                        _state.sent();
                        _state.label = 4;
                    case 4:
                        _iteratorNormalCompletion = true;
                        return [
                            3,
                            2
                        ];
                    case 5:
                        return [
                            3,
                            8
                        ];
                    case 6:
                        err = _state.sent();
                        _didIteratorError = true;
                        _iteratorError = err;
                        return [
                            3,
                            8
                        ];
                    case 7:
                        try {
                            if (!_iteratorNormalCompletion && _iterator.return != null) {
                                _iterator.return();
                            }
                        } finally{
                            if (_didIteratorError) {
                                throw _iteratorError;
                            }
                        }
                        return [
                            7
                        ];
                    case 8:
                        return [
                            2,
                            errs
                        ];
                }
            });
        });
        return function(nameList) {
            return _ref.apply(this, arguments);
        };
    }());
    (0, _define_property._)(this, "submit", /*#__PURE__*/ (0, _async_to_generator._)(function() {
        var errors, _this_callbacks_onFinish, _this_callbacks, _this_callbacks_onFinishFailed, _this_callbacks1;
        return (0, _ts_generator._)(this, function(_state) {
            switch(_state.label){
                case 0:
                    return [
                        4,
                        _this2.validateFields()
                    ];
                case 1:
                    errors = _state.sent();
                    if (errors.length === 0) {
                        ;
                        (_this_callbacks_onFinish = (_this_callbacks = _this2.callbacks).onFinish) === null || _this_callbacks_onFinish === void 0 ? void 0 : _this_callbacks_onFinish.call(_this_callbacks, _this2.store);
                    } else if (errors.length > 0) {
                        ;
                        (_this_callbacks_onFinishFailed = (_this_callbacks1 = _this2.callbacks).onFinishFailed) === null || _this_callbacks_onFinishFailed === void 0 ? void 0 : _this_callbacks_onFinishFailed.call(_this_callbacks1, _this2.store, errors);
                    }
                    return [
                        2
                    ];
            }
        });
    }));
    (0, _define_property._)(this, "resetFields", function() {
        _this.errors.length = 0;
        _this.store = _this.initialValues;
        _this.fieldEntities.forEach(function(entity) {
            entity.onStoreChange('reset');
        });
    });
    // 监听事件
    (0, _define_property._)(this, "registerUpdate", function(field, shouldUpdate) {
        _this.updateList.push({
            entity: field,
            condition: shouldUpdate
        });
        return function() {
            _this.updateList = _this.updateList.filter(function(i) {
                return i.entity !== field;
            });
        };
    });
    (0, _define_property._)(this, "dispatch", function(param) {
        var name = param.name;
        _this.validateFields([
            name
        ]);
    });
    (0, _define_property._)(this, "getInternal", function(key) {
        if (key === SECRET) {
            return {
                registerField: _this.registerField,
                setCallback: _this.setCallback,
                setInitialValues: _this.setInitialValues,
                dispatch: _this.dispatch,
                store: _this.store,
                fieldEntities: _this.fieldEntities,
                registerUpdate: _this.registerUpdate
            };
        }
    });
    (0, _define_property._)(this, "getForm", function() {
        return {
            getFieldValue: _this.getFieldValue,
            getFieldsValue: _this.getFieldsValue,
            setFieldsValue: _this.setFieldsValue,
            resetFields: _this.resetFields,
            validateFields: _this.validateFields,
            submit: _this.submit,
            errors: _this.errors,
            getInternal: _this.getInternal
        };
    });
    this.callbacks = {
        onFinish: function onFinish() {},
        onFinishFailed: function onFinishFailed() {}
    };
};
var useForm = function useForm(form) {
    var formRef = (0, _react.useRef)();
    if (!formRef.current) {
        if (form) {
            formRef.current = form;
        } else {
            var formStore = new FormStore();
            formRef.current = formStore.getForm();
        }
    }
    return [
        formRef.current
    ];
};
