'use strict';

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

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _extends3 = require('babel-runtime/helpers/extends');

var _extends4 = _interopRequireDefault(_extends3);

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _isEqual = require('lodash/isEqual');

var _isEqual2 = _interopRequireDefault(_isEqual);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _rcFieldForm = require('rc-field-form');

var _FieldContext = require('rc-field-form/lib/FieldContext');

var _FieldContext2 = _interopRequireDefault(_FieldContext);

var _ref2 = require('rc-util/lib/ref');

var _omit = require('omit.js');

var _omit2 = _interopRequireDefault(_omit);

var _row = require('../../row');

var _row2 = _interopRequireDefault(_row);

var _context = require('antd/lib/config-provider/context');

var _type = require('./type');

var _devWarning = require('./devWarning');

var _devWarning2 = _interopRequireDefault(_devWarning);

var _FormItemLabel = require('./FormItemLabel');

var _FormItemLabel2 = _interopRequireDefault(_FormItemLabel);

var _FormItemInput = require('./FormItemInput');

var _FormItemInput2 = _interopRequireDefault(_FormItemInput);

var _context2 = require('./context');

var _util = require('./util');

var _reactNode = require('./reactNode');

var _useFrameState3 = require('../hooks/useFrameState');

var _useFrameState4 = _interopRequireDefault(_useFrameState3);

var _useItemRef = require('../hooks/useItemRef');

var _useItemRef2 = _interopRequireDefault(_useItemRef);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var __rest = undefined && undefined.__rest || function (s, e) {
    var t = {};
    for (var p in s) {
        if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
    }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
        if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
    }
    return t;
};

var ValidateStatuses = (0, _type.tuple)('success', 'warning', 'error', 'validating', '');
var MemoInput = React.memo(function (_ref) {
    var children = _ref.children;
    return children;
}, function (prev, next) {
    return prev.value === next.value && prev.update === next.update;
});
function hasValidName(name) {
    if (name === null) {
        (0, _devWarning2['default'])(false, 'Form.Item', '`null` is passed as `name` property');
    }
    return !(name === undefined || name === null);
}
function getInitItem(dependency, name) {
    var item = { name: name };
    if (dependency) {
        if (dependency.disabled) {
            item.type = 'disabled';
        }
        if (dependency.source) {
            item.type = 'source';
        }
    }
}
function FormItem(props) {
    var _a;

    var name = props.name,
        fieldKey = props.fieldKey,
        noStyle = props.noStyle,
        dependencies = props.dependencies,
        customizePrefixCls = props.prefixCls,
        style = props.style,
        className = props.className,
        shouldUpdate = props.shouldUpdate,
        hasFeedback = props.hasFeedback,
        help = props.help,
        rules = props.rules,
        validateStatus = props.validateStatus,
        children = props.children,
        required = props.required,
        label = props.label,
        messageVariables = props.messageVariables,
        _props$trigger = props.trigger,
        trigger = _props$trigger === undefined ? 'onChange' : _props$trigger,
        validateTrigger = props.validateTrigger,
        hidden = props.hidden,
        dependency = props.dependency,
        restProps = __rest(props, ["name", "fieldKey", "noStyle", "dependencies", "prefixCls", "style", "className", "shouldUpdate", "hasFeedback", "help", "rules", "validateStatus", "children", "required", "label", "messageVariables", "trigger", "validateTrigger", "hidden", "dependency"]);

    var destroyRef = (0, _react.useRef)(false);
    // @ts-ignore

    var _useContext = (0, _react.useContext)(_context.ConfigContext),
        getPrefixCls = _useContext.getPrefixCls;

    var _useContext2 = (0, _react.useContext)(_context2.FormContext),
        formName = _useContext2.name,
        requiredMark = _useContext2.requiredMark,
        allDependency = _useContext2.allDependency,
        changeHandler = _useContext2.changeHandler,
        setFieldValue = _useContext2.setFieldValue,
        dataBinding = _useContext2.dataBinding;

    var _useContext3 = (0, _react.useContext)(_context2.FormItemContext),
        updateItemErrors = _useContext3.updateItemErrors;

    var _React$useState = React.useState(!!help),
        _React$useState2 = (0, _slicedToArray3['default'])(_React$useState, 2),
        domErrorVisible = _React$useState2[0],
        innerSetDomErrorVisible = _React$useState2[1];

    var _React$useState3 = React.useState(getInitItem(dependency, name)),
        _React$useState4 = (0, _slicedToArray3['default'])(_React$useState3, 2),
        updateItem = _React$useState4[0],
        innerSetUpdateItem = _React$useState4[1];

    var _React$useState5 = React.useState([]),
        _React$useState6 = (0, _slicedToArray3['default'])(_React$useState5, 2),
        itemRules = _React$useState6[0],
        innerSetItemRules = _React$useState6[1];

    var _React$useState7 = React.useState(dependency && dependency.visible ? dependency.visible.defaultOutput : !hidden),
        _React$useState8 = (0, _slicedToArray3['default'])(_React$useState7, 2),
        domVisible = _React$useState8[0],
        innerSetDomVisible = _React$useState8[1];

    var _React$useState9 = React.useState(dependency && dependency.disabled ? dependency.disabled.defaultOutput : false),
        _React$useState10 = (0, _slicedToArray3['default'])(_React$useState9, 2),
        domDisabled = _React$useState10[0],
        innerSetDomDisabled = _React$useState10[1];

    var _React$useState11 = React.useState(dependency && dependency.source && Array.isArray(dependency.source.defaultOutput) ? dependency.source.defaultOutput : []),
        _React$useState12 = (0, _slicedToArray3['default'])(_React$useState11, 2),
        dataSource = _React$useState12[0],
        innerSetDataSource = _React$useState12[1];

    var _useFrameState = (0, _useFrameState4['default'])({}),
        _useFrameState2 = (0, _slicedToArray3['default'])(_useFrameState, 2),
        inlineErrors = _useFrameState2[0],
        setInlineErrors = _useFrameState2[1];

    var _useContext4 = (0, _react.useContext)(_FieldContext2['default']),
        contextValidateTrigger = _useContext4.validateTrigger;

    var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : contextValidateTrigger;
    React.useEffect(function () {
        var originRules = void 0;
        if (dependency && dependency.required) {
            originRules = rules && rules.length > 0 ? rules.concat({ required: dependency.required.defaultOutput }) : [{ required: dependency.required.defaultOutput }];
        } else {
            originRules = rules || [];
        }
        innerSetItemRules(originRules);
    }, [rules]);
    function setDomErrorVisible(visible) {
        if (!destroyRef.current) {
            innerSetDomErrorVisible(visible);
        }
    }
    var hasName = hasValidName(name);
    // Cache Field NamePath
    var nameRef = (0, _react.useRef)([]);
    changeHandler[name] = function (val, item, type) {
        if (type === 'source') {
            innerSetUpdateItem({
                name: item,
                type: type
            });
            innerSetDataSource(val);
        }
        if (type === 'disabled') {
            innerSetUpdateItem({
                name: item,
                type: type
            });
            innerSetDomDisabled(val);
        }
        if (type === 'visible') {
            innerSetDomVisible(val);
        }
        if (type === 'required') {
            var requireItem = { required: val };
            innerSetItemRules(rules && rules.length > 0 ? rules.concat(requireItem) : [requireItem]);
        }
    };
    if (name && dependency) {
        allDependency[name] = dependency;
    }
    // Should clean up if Field removed
    React.useEffect(function () {
        return function () {
            destroyRef.current = true;
            updateItemErrors(nameRef.current.join('__SPLIT__'), []);
        };
    }, []);
    React.useEffect(function () {
        var _a, _b;
        if (((_a = children === null || children === void 0 ? void 0 : children.props) === null || _a === void 0 ? void 0 : _a.value) && dataBinding) {
            setFieldValue((0, _defineProperty3['default'])({}, name, (_b = children === null || children === void 0 ? void 0 : children.props) === null || _b === void 0 ? void 0 : _b.value));
        }
    }, [(_a = children === null || children === void 0 ? void 0 : children.props) === null || _a === void 0 ? void 0 : _a.value]);
    var prefixCls = getPrefixCls('form', customizePrefixCls);
    // ======================== Errors ========================
    // Collect noStyle Field error to the top FormItem
    var updateChildItemErrors = noStyle ? updateItemErrors : function (subName, subErrors) {
        setInlineErrors(function () {
            var prevInlineErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

            if (!(0, _isEqual2['default'])(prevInlineErrors[subName], subErrors)) {
                return (0, _extends4['default'])((0, _extends4['default'])({}, prevInlineErrors), (0, _defineProperty3['default'])({}, subName, subErrors));
            }
            return prevInlineErrors;
        });
    };
    // ===================== Children Ref =====================
    var getItemRef = (0, _useItemRef2['default'])();
    function renderLayout(baseChildren, fieldId, meta, isRequired) {
        var _itemClassName;

        var _a;
        if (noStyle && domVisible) {
            return baseChildren;
        }
        // ======================== Errors ========================
        // >>> collect sub errors
        var subErrorList = [];
        Object.keys(inlineErrors).forEach(function (subName) {
            subErrorList = [].concat((0, _toConsumableArray3['default'])(subErrorList), (0, _toConsumableArray3['default'])(inlineErrors[subName] || []));
        });
        // >>> merged errors
        var mergedErrors = void 0;
        if (help !== undefined && help !== null) {
            mergedErrors = (0, _util.toArray)(help);
        } else {
            mergedErrors = meta ? meta.errors : [];
            mergedErrors = [].concat((0, _toConsumableArray3['default'])(mergedErrors), (0, _toConsumableArray3['default'])(subErrorList));
        }
        // ======================== Status ========================
        var mergedValidateStatus = '';
        if (validateStatus !== undefined) {
            mergedValidateStatus = validateStatus;
        } else if (meta === null || meta === void 0 ? void 0 : meta.validating) {
            mergedValidateStatus = 'validating';
        } else if (((_a = meta === null || meta === void 0 ? void 0 : meta.errors) === null || _a === void 0 ? void 0 : _a.length) || subErrorList.length) {
            mergedValidateStatus = 'error';
        } else if (meta === null || meta === void 0 ? void 0 : meta.touched) {
            mergedValidateStatus = 'success';
        }
        var itemClassName = (_itemClassName = {}, (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item', true), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-with-help', domErrorVisible || help), (0, _defineProperty3['default'])(_itemClassName, '' + className, !!className), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-has-feedback', mergedValidateStatus && hasFeedback), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-has-success', mergedValidateStatus === 'success'), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-has-warning', mergedValidateStatus === 'warning'), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-has-error', mergedValidateStatus === 'error'), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-is-validating', mergedValidateStatus === 'validating'), (0, _defineProperty3['default'])(_itemClassName, prefixCls + '-item-hidden', !domVisible), _itemClassName);
        // ======================= Children =======================
        return React.createElement(
            _row2['default'],
            (0, _extends4['default'])({ className: (0, _classnames2['default'])(itemClassName), style: style, key: 'row' }, (0, _omit2['default'])(restProps, ['colon', 'extra', 'getValueFromEvent', 'getValueProps',
            // @ts-ignore
            'hasFeedback',
            // @ts-ignore
            'help', 'htmlFor', 'id', 'initialValue', 'isListField',
            // @ts-ignore
            'label', 'labelAlign', 'labelCol', 'normalize', 'preserve',
            // @ts-ignore
            'required', 'tooltip', 'validateFirst',
            // @ts-ignore
            'validateStatus', 'valuePropName', 'wrapperCol'])),
            React.createElement(_FormItemLabel2['default'], (0, _extends4['default'])({ htmlFor: fieldId, required: isRequired, requiredMark: requiredMark }, props, { prefixCls: prefixCls })),
            React.createElement(
                _FormItemInput2['default'],
                (0, _extends4['default'])({}, props, meta, { errors: mergedErrors, prefixCls: prefixCls, status: mergedValidateStatus, onDomErrorVisibleChange: setDomErrorVisible, validateStatus: mergedValidateStatus }),
                React.createElement(
                    _context2.FormItemContext.Provider,
                    { value: { updateItemErrors: updateChildItemErrors } },
                    baseChildren
                )
            )
        );
    }
    var isRenderProps = typeof children === 'function';
    // Record for real component render
    var updateRef = (0, _react.useRef)(0);
    updateRef.current += 1;
    if (!hasName && !isRenderProps && !dependencies) {
        return renderLayout(children);
    }
    var variables = {};
    if (typeof label === 'string') {
        variables.label = label;
    }
    if (messageVariables) {
        variables = (0, _extends4['default'])((0, _extends4['default'])({}, variables), messageVariables);
    }
    return React.createElement(
        _rcFieldForm.Field,
        (0, _extends4['default'])({}, props, { rules: itemRules, messageVariables: variables, trigger: trigger, validateTrigger: mergedValidateTrigger, onReset: function onReset() {
                setDomErrorVisible(false);
            } }),
        function (control, meta, context) {
            var errors = meta.errors;

            var mergedName = (0, _util.toArray)(name).length && meta ? meta.name : [];
            var fieldId = (0, _util.getFieldId)(mergedName, formName);
            if (noStyle) {
                nameRef.current = [].concat((0, _toConsumableArray3['default'])(mergedName));
                if (fieldKey) {
                    var fieldKeys = Array.isArray(fieldKey) ? fieldKey : [fieldKey];
                    nameRef.current = [].concat((0, _toConsumableArray3['default'])(mergedName.slice(0, -1)), (0, _toConsumableArray3['default'])(fieldKeys));
                }
                updateItemErrors(nameRef.current.join('__SPLIT__'), errors);
            }
            var isRequired = required !== undefined ? required : !!(itemRules && itemRules.some(function (rule) {
                if (rule && typeof rule === 'object' && rule.required) {
                    return true;
                }
                if (typeof rule === 'function') {
                    var ruleEntity = rule(context);
                    return ruleEntity && ruleEntity.required;
                }
                return false;
            }));
            // ======================= Children =======================
            var mergedControl = (0, _extends4['default'])({}, control);
            if (dataBinding) {
                delete mergedControl[props.valuePropName || 'value'];
            }
            var childNode = null;
            (0, _devWarning2['default'])(!(shouldUpdate && dependencies), 'Form.Item', "`shouldUpdate` and `dependencies` shouldn't be used together. See https://ant.design/components/form/#dependencies.");
            if (Array.isArray(children) && hasName) {
                (0, _devWarning2['default'])(false, 'Form.Item', '`children` is array of render props cannot have `name`.');
                childNode = children;
            } else if (isRenderProps && (!(shouldUpdate || dependencies) || hasName)) {
                (0, _devWarning2['default'])(!!(shouldUpdate || dependencies), 'Form.Item', '`children` of render props only work with `shouldUpdate` or `dependencies`.');
                (0, _devWarning2['default'])(!hasName, 'Form.Item', "Do not use `name` with `children` of render props since it's not a field.");
            } else if (dependencies && !isRenderProps && !hasName) {
                (0, _devWarning2['default'])(false, 'Form.Item', 'Must set `name` or use render props when `dependencies` is set.');
            } else if ((0, _reactNode.isValidElement)(children)) {
                (0, _devWarning2['default'])(children.props.defaultValue === undefined, 'Form.Item', '`defaultValue` will not work on controlled Field. You should use `initialValues` of Form instead.');
                var childProps = (0, _extends4['default'])((0, _extends4['default'])({}, children.props), mergedControl);
                if (!childProps.id) {
                    childProps.id = fieldId;
                }
                if ((0, _ref2.supportRef)(children)) {
                    childProps.ref = getItemRef(mergedName, children);
                }
                if (updateItem && updateItem.name === name) {
                    if (updateItem.type === 'disabled') {
                        childProps.disabled = domDisabled;
                    }
                    if (updateItem.type === 'source') {
                        if (childProps.dataSource) {
                            childProps.dataSource = dataSource;
                        } else {
                            childProps.options = dataSource;
                        }
                    }
                }
                // We should keep user origin event handler
                var triggers = new Set([].concat((0, _toConsumableArray3['default'])((0, _util.toArray)(trigger)), (0, _toConsumableArray3['default'])((0, _util.toArray)(mergedValidateTrigger))));
                triggers.forEach(function (eventName) {
                    childProps[eventName] = function () {
                        var _a2, _c2;

                        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
                            args[_key] = arguments[_key];
                        }

                        var _a, _b, _c;
                        (_a = mergedControl[eventName]) === null || _a === void 0 ? void 0 : (_a2 = _a).call.apply(_a2, [mergedControl].concat(args));
                        (_c = (_b = children.props)[eventName]) === null || _c === void 0 ? void 0 : (_c2 = _c).call.apply(_c2, [_b].concat(args));
                    };
                });
                childNode = React.createElement(
                    MemoInput,
                    { value: dataBinding ? childProps[props.valuePropName || 'value'] : mergedControl[props.valuePropName || 'value'], update: updateRef.current },
                    (0, _reactNode.cloneElement)(children, childProps)
                );
            } else if (isRenderProps && (shouldUpdate || dependencies) && !hasName) {
                childNode = children(context);
            } else {
                (0, _devWarning2['default'])(!mergedName.length, 'Form.Item', '`name` is only used for validate React element. If you are using Form.Item as layout display, please remove `name` instead.');
                childNode = children;
            }
            return renderLayout(childNode, fieldId, meta, isRequired);
        }
    );
}
exports['default'] = FormItem;
module.exports = exports['default'];