"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

var React = _interopRequireWildcard(require("react"));

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

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

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

var _get = _interopRequireDefault(require("lodash/get"));

var _set = _interopRequireDefault(require("lodash/set"));

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

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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, _set.default)(originValue, key, element.format(props.format || 'YYYY-MM-DD'));
        }

        break;

      case 'TimePicker':
        if (element) {
          (0, _set.default)(originValue, key, element.format(props.format || 'HH:mm:ss'));
        }

        break;

      case 'RangePicker':
        if (element) {
          (0, _set.default)(originValue, key, element.map(function (v) {
            return v.format(props.format || 'YYYY-MM-DD HH:mm:ss');
          }));
        }

        break;

      case 'RichEditor':
        if (element) {
          (0, _set.default)(originValue, key, element.toHTML());
        }

        break;

      case 'Table':
      case 'TableEdit':
        (0, _set.default)(originValue, key, instance.state.dataSource || []);
        break;

      default:
        break;
    }
  }
}

function useForm(form) {
  var _useRcForm = (0, _rcFieldForm.useForm)(),
      _useRcForm2 = _slicedToArray(_useRcForm, 1),
      rcForm = _useRcForm2[0];

  var itemsRef = React.useRef({});
  var wrapForm = React.useMemo(function () {
    return form || _objectSpread(_objectSpread({}, 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, _scrollIntoViewIfNeeded.default)(node, _objectSpread({
            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, _cloneDeep.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, _get.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];
}