'use strict';

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

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

var _extends3 = _interopRequireDefault(_extends2);

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

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

exports['default'] = useForm;

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _cloneDeep = require('lodash/cloneDeep');

var _cloneDeep2 = _interopRequireDefault(_cloneDeep);

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

var _scrollIntoViewIfNeeded = require('scroll-into-view-if-needed');

var _scrollIntoViewIfNeeded2 = _interopRequireDefault(_scrollIntoViewIfNeeded);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _set = require('lodash/set');

var _set2 = _interopRequireDefault(_set);

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

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 }; }

function toNamePathStr(name) {
    var namePath = (0, _util.toArray)(name);
    return namePath.join('_');
}
// 处理特殊组件的值 (moment转string等)
function handleSpecialComponentVal(instance, element, originValue, key) {
    if (instance['componentName'] || instance.constructor['componentName']) {
        var props = instance.props;

        var componentName = instance['componentName'] || instance.constructor['componentName'];
        switch (componentName) {
            case 'Picker':
                if (element) {
                    (0, _set2['default'])(originValue, key, element.format(props.format || 'YYYY-MM-DD'));
                }
                break;
            case 'TimePicker':
                if (element) {
                    (0, _set2['default'])(originValue, key, element.format(props.format || 'HH:mm:ss'));
                }
                break;
            case 'RangePicker':
                if (element) {
                    (0, _set2['default'])(originValue, key, element.map(function (v) {
                        return v.format(props.format || 'YYYY-MM-DD HH:mm:ss');
                    }));
                }
                break;
            case 'RichEditor':
                if (element) {
                    (0, _set2['default'])(originValue, key, element.toHTML());
                }
                break;
            case 'Table':
            case 'TableEdit':
                (0, _set2['default'])(originValue, key, instance.state.dataSource || []);
                break;
            default:
                break;
        }
    }
}
function useForm(form) {
    var _useRcForm = (0, _rcFieldForm.useForm)(),
        _useRcForm2 = (0, _slicedToArray3['default'])(_useRcForm, 1),
        rcForm = _useRcForm2[0];

    var itemsRef = React.useRef({});
    var wrapForm = React.useMemo(function () {
        return form || (0, _extends3['default'])((0, _extends3['default'])({}, rcForm), { __INTERNAL__: {
                itemRef: function itemRef(name) {
                    return function (node) {
                        var namePathStr = toNamePathStr(name);
                        if (node) {
                            itemsRef.current[namePathStr] = node;
                        } else {
                            delete itemsRef.current[namePathStr];
                        }
                    };
                },
                allDependency: {},
                changeHandler: {}
            }, scrollToField: function scrollToField(name) {
                var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

                var namePath = (0, _util.toArray)(name);
                var fieldId = (0, _util.getFieldId)(namePath, wrapForm.__INTERNAL__.name);
                var node = fieldId ? document.getElementById(fieldId) : null;
                if (node) {
                    (0, _scrollIntoViewIfNeeded2['default'])(node, (0, _extends3['default'])({ scrollMode: 'if-needed', block: 'nearest' }, options));
                }
            }, getFieldInstance: function getFieldInstance(name) {
                var namePathStr = toNamePathStr(name);
                return itemsRef.current[namePathStr];
            }, setFieldValue: function setFieldValue(val) {
                rcForm.setFieldsValue(val);
            }, setFieldSource: function setFieldSource(value) {
                var changeHandler = wrapForm.__INTERNAL__.changeHandler;

                Object.keys(value).forEach(function (v) {
                    if (changeHandler[v]) {
                        changeHandler[v](value[v], v, 'source');
                    }
                });
            }, setFieldVisible: function setFieldVisible(value) {
                var changeHandler = wrapForm.__INTERNAL__.changeHandler;

                Object.keys(value).forEach(function (v) {
                    changeHandler[v] && changeHandler[v](value[v], v, 'visible');
                });
            }, setFieldRequired: function setFieldRequired(value) {
                var changeHandler = wrapForm.__INTERNAL__.changeHandler;

                Object.keys(value).forEach(function (v) {
                    changeHandler[v] && changeHandler[v](value[v], v, 'required');
                });
            }, setFieldDisabled: function setFieldDisabled(value) {
                var changeHandler = wrapForm.__INTERNAL__.changeHandler;

                Object.keys(value).forEach(function (v) {
                    changeHandler[v] && changeHandler[v](value[v], v, 'disabled');
                });
            }, setFieldsDisabled: function setFieldsDisabled(value) {
                var changeHandler = wrapForm.__INTERNAL__.changeHandler;

                var allValues = rcForm.getFieldsValue();
                Object.keys(allValues).forEach(function (v) {
                    changeHandler[v] && changeHandler[v](value, v, 'disabled');
                });
            }, getFormValue: function getFormValue(nameList, filterFunc) {
                var originValue = (0, _cloneDeep2['default'])(rcForm.getFieldsValue(nameList, filterFunc));
                for (var key in originValue) {
                    if (Object.prototype.hasOwnProperty.call(originValue, key)) {
                        var _ret = function () {
                            var element = originValue[key];
                            var namePathStr = toNamePathStr(key);
                            var instance = itemsRef.current[namePathStr];
                            var instances = instance ? [{ name: namePathStr, instance: instance, element: element }] : [];
                            // 兼容Form.List输出的数组结构
                            if (Array.isArray(element) && itemsRef.current && instances.length <= 0) {
                                Object.keys(itemsRef.current).forEach(function (refKey) {
                                    if (refKey.includes(namePathStr)) {
                                        var path = refKey.replace(/_/g, '.');
                                        instances.push({
                                            name: path,
                                            instance: itemsRef.current[refKey],
                                            element: (0, _get2['default'])(originValue, path)
                                        });
                                    }
                                });
                            }
                            if (instances.length <= 0) {
                                return 'continue';
                            }
                            instances.forEach(function (ref) {
                                handleSpecialComponentVal(ref.instance, ref.element, originValue, ref.name);
                            });
                        }();

                        if (_ret === 'continue') continue;
                    }
                }
                return originValue;
            }, setFieldsValue: function setFieldsValue(value) {
                var allDependency = wrapForm.__INTERNAL__.allDependency;

                rcForm.setFieldsValue(value);
                if (Object.keys(allDependency).length) {
                    var allValues = rcForm.getFieldsValue();
                    (0, _util.cascadeHandler)(wrapForm, allValues, allDependency);
                }
            } });
    }, [form, rcForm]);
    return [wrapForm];
}
module.exports = exports['default'];