var _excluded = ["type", "name", "component", "props", "decorator", "decoratorProps", "dataSource", "reactions", "rules", "children", "items", "tooltip", "request", "data"];

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 _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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

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

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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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

import React, { memo, useCallback, useRef, useMemo } from 'react';
import { createSchemaField } from '@formily/react';
import { cls, isUsable } from '@teamix/utils';
import adapterType from './adapterType';
import adapterComponent from './adapterComponent';
import adapterDecorator from './adapterDecorator';
import initializeRequest from './initializeRequest';
import initializeReactions from './initializeReactions';
import initializeDataSource from './initializeDataSource';
import initializeRules from './initializeRules';
import initializeArrayCards from './initializeArrayCards';
import initializeArrayCollapse from './initializeArrayCollapse';
import initializeArrayTable from './initializeArrayTable';
import initializeArrayItems from './initializeArrayItems';
import initializeFormButton from './initializeFormButton';
import initializeFormGroup from './initializeFormGroup';
import initializeFormStep from './initializeFormStep';
import initializeFormTab from './initializeFormTab';
import initializeFormCollapse from './initializeFormCollapse';
import initializeSelectTable from './initializeSelectTable';
import { $request, $common, $dataSource, $validator } from './reactions';
import fieldTypeMap from '../fieldTypeMap';
import { getFieldName, mapSchemaName } from '../utils';
import warning from '../warning';
export default /*#__PURE__*/memo(function (_ref) {
  var schema = _ref.schema,
      scope = _ref.scope,
      components = _ref.components;
  var schemaScopeRef = useRef({}); // 创建 SchemaField

  var SchemaField = useMemo(function () {
    return createSchemaField();
  }, []); // 格式化 schema

  var formatSchema = useCallback(function (schema) {
    var parentSuffix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    var schemaProperties = {};
    schema === null || schema === void 0 ? void 0 : schema.forEach(function (item, index) {
      var suffix = "".concat(parentSuffix).concat(index);
      var newItem = warning(item);
      var _newItem = newItem,
          originalComponent = _newItem.component; // 根据component的不同，初始化为内置的item

      if (originalComponent) {
        if (Object.keys(fieldTypeMap).includes(originalComponent)) {// ProField接管组件
        } else {
          // 未接管组件，判断是否为Formily组件别名
          newItem = _objectSpread(_objectSpread({}, newItem), {}, {
            component: adapterComponent(originalComponent)
          });
        } // 初始化高级组件 - FormButtonGroup/Subimt/Reset


        if (['FormButtonGroup', 'Submit', 'Reset'].includes(originalComponent)) {
          newItem = initializeFormButton(newItem);
        } // 初始化高级组件 - ArrayCards


        if (['ArrayCards'].includes(originalComponent)) {
          newItem = initializeArrayCards(newItem);
        } // 初始化高级组件 - ArrayCollapse


        if (['ArrayCollapse'].includes(originalComponent)) {
          newItem = initializeArrayCollapse(newItem);
        } // 初始化高级组件 - ArrayTable


        if (['ArrayTable'].includes(originalComponent)) {
          newItem = initializeArrayTable(newItem);
        } // 初始化高级组件 - ArrayItems


        if (['ArrayItems'].includes(originalComponent)) {
          newItem = initializeArrayItems(newItem);
        } // 初始化布局组件 - FormStep


        if (['FormStep'].includes(originalComponent)) {
          newItem = initializeFormStep(newItem);
        } // 初始化布局组件 - FormGroup


        if (['FormGroup'].includes(originalComponent)) {
          newItem = initializeFormGroup(newItem);
        } // 初始化布局组件 - FormTab


        if (['FormTab'].includes(originalComponent)) {
          newItem = initializeFormTab(newItem);
        } // 初始化布局组件 - FormCollapse


        if (['FormCollapse'].includes(originalComponent)) {
          newItem = initializeFormCollapse(newItem);
        } // 初始化选择表格 - SelectTable


        if (['SelectTable'].includes(originalComponent)) {
          newItem = initializeSelectTable(newItem);
        }
      }

      var _newItem2 = newItem,
          type = _newItem2.type,
          name = _newItem2.name,
          component = _newItem2.component,
          props = _newItem2.props,
          decorator = _newItem2.decorator,
          decoratorProps = _newItem2.decoratorProps,
          dataSource = _newItem2.dataSource,
          reactions = _newItem2.reactions,
          rules = _newItem2.rules,
          children = _newItem2.children,
          items = _newItem2.items,
          tooltip = _newItem2.tooltip,
          request = _newItem2.request,
          data = _newItem2.data,
          otherProps = _objectWithoutProperties(_newItem2, _excluded); // 默认字段名


      var defaultName = !name ? getFieldName(component === null || component === void 0 ? void 0 : component.replace(/\./g, ''), suffix) : name; // 默认类型

      var defaultType = adapterType(type, originalComponent); // 默认装饰组件

      var defaultDecorator = adapterDecorator(decorator, originalComponent); // 默认装饰组件属性

      var tooltipProps = tooltip ? {
        tooltip: tooltip
      } : {};

      var defaultDecoratorProps = _objectSpread(_objectSpread({}, tooltipProps), decoratorProps); // 初始化request


      var _initializeRequest = initializeRequest(request, "".concat(suffix, "r")),
          requestReactions = _initializeRequest.reactions,
          requestScope = _initializeRequest.scope; // 初始化dataSource


      var _initializeDataSource = initializeDataSource(dataSource, "".concat(suffix, "d")),
          defaultDataSource = _initializeDataSource.dataSource,
          dataSourceReactions = _initializeDataSource.reactions,
          dataSourceScope = _initializeDataSource.scope,
          dataSourceData = _initializeDataSource.data,
          dataSourceProps = _initializeDataSource.props; // 初始化rules validator


      var _initializeRules = initializeRules(rules, "".concat(suffix, "v")),
          defaultRules = _initializeRules.rules,
          rulesScope = _initializeRules.scope; // 合并reactions，初始化reactions


      var defaultReactions = initializeReactions(reactions, [].concat(_toConsumableArray(requestReactions), _toConsumableArray(dataSourceReactions))); // 合并scope

      Object.entries(_objectSpread(_objectSpread(_objectSpread({}, requestScope), dataSourceScope), rulesScope)).map(function (_ref2) {
        var _ref3 = _slicedToArray(_ref2, 2),
            k = _ref3[0],
            v = _ref3[1];

        schemaScopeRef.current[k] = v;
      }); // 合并字段属性

      var defaultProps = _objectSpread(_objectSpread(_objectSpread({}, props), dataSourceProps), {}, {
        className: cls(props === null || props === void 0 ? void 0 : props.className, dataSourceProps === null || dataSourceProps === void 0 ? void 0 : dataSourceProps.className)
      });

      var formatParam = mapSchemaName(_objectSpread(_objectSpread({}, otherProps), {}, {
        type: defaultType,
        component: component,
        props: defaultProps,
        decorator: defaultDecorator,
        decoratorProps: defaultDecoratorProps,
        rules: defaultRules,
        reactions: defaultReactions,
        dataSource: defaultDataSource,
        data: _objectSpread(_objectSpread(_objectSpread({}, data), dataSourceData), {}, {
          __placeholder: true
        })
      })); // 递归子组件

      var recursiveProperties = (children === null || children === void 0 ? void 0 : children.length) ? {
        properties: formatSchema(children, suffix)
      } : {}; // 递归items（类似子组件，会先由各initialize方法格式化为固定形式，type不同不统一处理）
      // 例如：[{ name: 'items', type: 'object', children: items }]

      var recursiveItems = items ? formatSchema([items], suffix) : {}; // 配置组件属性

      if (isUsable(item)) {
        schemaProperties[defaultName] = _objectSpread(_objectSpread(_objectSpread({}, formatParam), recursiveProperties), recursiveItems);
      }
    });
    return schemaProperties;
  }, []);
  var formilySchema = useMemo(function () {
    return {
      type: 'object',
      properties: formatSchema(schema)
    };
  }, [schema]);

  var mergedScope = _objectSpread(_objectSpread({}, scope), {}, {
    $request: $request,
    $common: $common,
    $dataSource: $dataSource,
    $validator: $validator
  }, schemaScopeRef.current);

  return /*#__PURE__*/React.createElement(SchemaField, {
    schema: formilySchema,
    components: components,
    scope: mergedScope
  });
});