"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "FormItem", {
    enumerable: true,
    get: function() {
        return FormItem;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _call_super = require("@swc/helpers/_/_call_super");
var _class_call_check = require("@swc/helpers/_/_class_call_check");
var _create_class = require("@swc/helpers/_/_create_class");
var _define_property = require("@swc/helpers/_/_define_property");
var _inherits = require("@swc/helpers/_/_inherits");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _sliced_to_array = require("@swc/helpers/_/_sliced_to_array");
var _to_consumable_array = require("@swc/helpers/_/_to_consumable_array");
var _react = /*#__PURE__*/ _interop_require_default._(require("react"));
var _components = require("@tarojs/components");
var _context = require("../form/context");
var _index = /*#__PURE__*/ _interop_require_default._(require("../cell/index"));
var _typings = require("../../utils/typings");
var _isforwardrefcomponent = require("../../utils/is-forward-ref-component");
var _toarray = require("../../utils/to-array");
var _useform = require("../form/useform");
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    required: false,
    name: '',
    label: '',
    rules: [
        {
            required: false,
            message: ''
        }
    ],
    errorMessageAlign: 'left',
    shouldUpdate: false,
    noStyle: false
});
var _React_Component;
var FormItem = /*#__PURE__*/ function(_superClass) {
    "use strict";
    (0, _inherits._)(FormItem, _superClass);
    function FormItem(props) {
        (0, _class_call_check._)(this, FormItem);
        var _this;
        _this = (0, _call_super._)(this, FormItem, [
            props
        ]), (0, _define_property._)(_this, "cancelRegister", void 0), (0, _define_property._)(_this, "componentRef", void 0), (0, _define_property._)(_this, "eventOff", void 0), (0, _define_property._)(_this, "getControlled", function(children) {
            var _children_props;
            var _this_context_formInstance = _this.context.formInstance, setFieldsValue = _this_context_formInstance.setFieldsValue, getFieldValue = _this_context_formInstance.getFieldValue;
            var dispatch = _this.context.formInstance.getInternal(_useform.SECRET).dispatch;
            var _this_props = _this.props, _this_props_name = _this_props.name, name = _this_props_name === void 0 ? '' : _this_props_name;
            if (children === null || children === void 0 ? void 0 : (_children_props = children.props) === null || _children_props === void 0 ? void 0 : _children_props.defaultValue) {
                if (process.env.NODE_ENV !== 'production') {
                    console.warn('[NutUI] FormItem:', '请通过 initialValue 设置初始值，而不是 defaultValue');
                }
            }
            var fieldValue = getFieldValue(name);
            var _obj;
            var controlled = (0, _object_spread_props._)((0, _object_spread._)({}, children.props), (_obj = {
                className: children.props.className
            }, (0, _define_property._)(_obj, _this.props.valuePropName || 'value', fieldValue !== undefined ? fieldValue : _this.props.initialValue), (0, _define_property._)(_obj, _this.props.trigger || 'onChange', function() {
                for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                    args[_key] = arguments[_key];
                }
                // args [a, b]
                var originOnChange = children.props[_this.props.trigger || 'onChange'];
                if (originOnChange) {
                    originOnChange.apply(void 0, (0, _to_consumable_array._)(args));
                }
                var _args = (0, _sliced_to_array._)(args, 1), next = _args[0];
                if (_this.props.getValueFromEvent) {
                    var _this_props;
                    next = (_this_props = _this.props).getValueFromEvent.apply(_this_props, (0, _to_consumable_array._)(args));
                }
                setFieldsValue((0, _define_property._)({}, name, next));
            }), _obj));
            var validateTrigger = _this.props.validateTrigger;
            var mergedValidateTrigger = validateTrigger || _this.context.validateTrigger;
            var validateTriggers = (0, _toarray.toArray)(mergedValidateTrigger);
            validateTriggers.forEach(function(trigger) {
                var originTrigger = controlled[trigger];
                controlled[trigger] = function() {
                    for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                        args[_key] = arguments[_key];
                    }
                    if (originTrigger) {
                        originTrigger.apply(void 0, (0, _to_consumable_array._)(args));
                    }
                    if (_this.props.rules && _this.props.rules.length) {
                        dispatch({
                            name: _this.props.name
                        });
                    }
                };
            });
            if ((0, _isforwardrefcomponent.isForwardRefComponent)(children)) {
                controlled.ref = function(componentInstance) {
                    var originRef = children.ref;
                    if (originRef) {
                        if (typeof originRef === 'function') {
                            originRef(componentInstance);
                        }
                        if ('current' in originRef) {
                            originRef.current = componentInstance;
                        }
                    }
                    _this.componentRef = componentInstance;
                };
            }
            return controlled;
        }), (0, _define_property._)(_this, "refresh", function() {
            _this.setState(function(param) {
                var resetCount = param.resetCount;
                return {
                    resetCount: resetCount + 1
                };
            });
        }), (0, _define_property._)(_this, "onStoreChange", function(type) {
            if (type === 'reset') {
                _this.context.formInstance.errors[_this.props.name] = [];
                _this.refresh();
            } else {
                _this.forceUpdate();
            }
        }), (0, _define_property._)(_this, "renderLayout", function(childNode) {
            var _item_;
            var _$_object_spread = (0, _object_spread._)({}, defaultProps, _this.props), label = _$_object_spread.label, name = _$_object_spread.name, required = _$_object_spread.required, rules = _$_object_spread.rules, className = _$_object_spread.className, style = _$_object_spread.style, errorMessageAlign = _$_object_spread.errorMessageAlign, align = _$_object_spread.align;
            var requiredInRules = rules === null || rules === void 0 ? void 0 : rules.some(function(rule) {
                return rule.required;
            });
            var item = name ? _this.context.formInstance.errors[name] : [];
            var starPosition = _this.context.formInstance.starPosition;
            var renderStar = (required || requiredInRules) && /*#__PURE__*/ _react.default.createElement(_components.Text, {
                className: "nut-form-item-label-".concat(starPosition, "-required required")
            }, "*");
            var renderLabel = /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_components.Text, {
                className: "nut-form-item-labeltxt"
            }, starPosition === 'left' ? renderStar : null, label, starPosition === 'right' ? renderStar : null));
            return /*#__PURE__*/ _react.default.createElement(_index.default, {
                className: "".concat(_this.getClassNameWithDirection('nut-form-item'), " ").concat(className),
                style: style,
                align: align,
                onClick: function onClick(e) {
                    return _this.props.onClick && _this.props.onClick(e, _this.componentRef);
                }
            }, label ? /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "nut-cell-title ".concat(_this.getClassNameWithDirection('nut-form-item-label'))
            }, renderLabel) : null, /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "nut-cell-value ".concat(_this.getClassNameWithDirection('nut-form-item-body'))
            }, /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "nut-form-item-body-slots"
            }, childNode), /*#__PURE__*/ _react.default.createElement(_components.View, {
                className: "nut-form-item-body-tips",
                style: {
                    textAlign: errorMessageAlign,
                    display: (item === null || item === void 0 ? void 0 : item.length) ? 'initial' : 'none'
                }
            }, item === null || item === void 0 ? void 0 : (_item_ = item[0]) === null || _item_ === void 0 ? void 0 : _item_.message)));
        });
        _this.componentRef = /*#__PURE__*/ _react.default.createRef();
        _this.state = {
            resetCount: 1
        };
        return _this;
    }
    (0, _create_class._)(FormItem, [
        {
            key: "componentDidMount",
            value: function componentDidMount() {
                // Form设置initialValues时的处理
                var _this_context_formInstance_getInternal = this.context.formInstance.getInternal(_useform.SECRET), _this_context_formInstance_getInternal_store = _this_context_formInstance_getInternal.store, store = _this_context_formInstance_getInternal_store === void 0 ? {} : _this_context_formInstance_getInternal_store, setInitialValues = _this_context_formInstance_getInternal.setInitialValues;
                if (this.props.initialValue && this.props.name && !Object.keys(store).includes(this.props.name)) {
                    setInitialValues((0, _object_spread_props._)((0, _object_spread._)({}, store), (0, _define_property._)({}, this.props.name, this.props.initialValue)), true);
                }
                // 注册组件实例到FormStore
                var _this_context_formInstance_getInternal1 = this.context.formInstance.getInternal(_useform.SECRET), registerField = _this_context_formInstance_getInternal1.registerField, registerUpdate = _this_context_formInstance_getInternal1.registerUpdate;
                this.cancelRegister = registerField(this);
                // 这里需要增加事件监听，因为此实现属于依赖触发
                this.eventOff = registerUpdate(this, this.props.shouldUpdate);
            }
        },
        {
            key: "componentWillUnmount",
            value: function componentWillUnmount() {
                if (this.cancelRegister) {
                    this.cancelRegister();
                }
                if (this.eventOff) {
                    this.eventOff();
                }
            }
        },
        {
            key: "getClassNameWithDirection",
            value: function getClassNameWithDirection(className) {
                if (className && this.context.labelPosition) {
                    return "".concat(className, " ").concat(className, "-").concat(this.context.labelPosition);
                }
                return className;
            }
        },
        {
            key: "render",
            value: function render() {
                var children = this.props.children;
                var child = Array.isArray(children) ? children[0] : children;
                var returnChildNode;
                if (!this.props.shouldUpdate) {
                    returnChildNode = /*#__PURE__*/ _react.default.cloneElement(child, this.getControlled(child));
                } else {
                    returnChildNode = child(this.context.formInstance);
                }
                return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, {
                    key: this.state.resetCount
                }, /*#__PURE__*/ _react.default.createElement(_components.View, {
                    className: this.context.disabled ? 'nut-form-item-disabled' : '',
                    catchMove: this.context.disabled
                }, this.props.noStyle ? returnChildNode : this.renderLayout(returnChildNode)));
            }
        }
    ]);
    return FormItem;
}(_React_Component = _react.default.Component);
(0, _define_property._)(FormItem, "defaultProps", defaultProps);
(0, _define_property._)(FormItem, "contextType", _context.Context);
