import _extends from 'babel-runtime/helpers/extends';
import _slicedToArray from 'babel-runtime/helpers/slicedToArray';
import * as React from 'react';
import cloneDeep from 'lodash/cloneDeep';
import { useForm as useRcForm } from 'rc-field-form';
import scrollIntoView from 'scroll-into-view-if-needed';
import lodashGet from 'lodash/get';
import lodashSet from 'lodash/set';
import { toArray, getFieldId, cascadeHandler } from '../utils/util';
function toNamePathStr(name) {
    var namePath = 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) {
                    lodashSet(originValue, key, element.format(props.format || 'YYYY-MM-DD'));
                }
                break;
            case 'TimePicker':
                if (element) {
                    lodashSet(originValue, key, element.format(props.format || 'HH:mm:ss'));
                }
                break;
            case 'RangePicker':
                if (element) {
                    lodashSet(originValue, key, element.map(function (v) {
                        return v.format(props.format || 'YYYY-MM-DD HH:mm:ss');
                    }));
                }
                break;
            case 'RichEditor':
                if (element) {
                    lodashSet(originValue, key, element.toHTML());
                }
                break;
            case 'Table':
            case 'TableEdit':
                lodashSet(originValue, key, instance.state.dataSource || []);
                break;
            default:
                break;
        }
    }
}
export default function useForm(form) {
    var _useRcForm = useRcForm(),
        _useRcForm2 = _slicedToArray(_useRcForm, 1),
        rcForm = _useRcForm2[0];

    var itemsRef = React.useRef({});
    var wrapForm = React.useMemo(function () {
        return form || _extends(_extends({}, 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 = toArray(name);
                var fieldId = getFieldId(namePath, wrapForm.__INTERNAL__.name);
                var node = fieldId ? document.getElementById(fieldId) : null;
                if (node) {
                    scrollIntoView(node, _extends({ 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 = cloneDeep(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: lodashGet(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();
                    cascadeHandler(wrapForm, allValues, allDependency);
                }
            } });
    }, [form, rcForm]);
    return [wrapForm];
}