"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 = void 0;

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

var _react2 = require("@formily/react");

var _utils = require("@teamix/utils");

var _adapterType = _interopRequireDefault(require("./adapterType"));

var _adapterComponent = _interopRequireDefault(require("./adapterComponent"));

var _adapterDecorator = _interopRequireDefault(require("./adapterDecorator"));

var _initializeRequest2 = _interopRequireDefault(require("./initializeRequest"));

var _initializeReactions = _interopRequireDefault(require("./initializeReactions"));

var _initializeDataSource2 = _interopRequireDefault(require("./initializeDataSource"));

var _initializeRules2 = _interopRequireDefault(require("./initializeRules"));

var _initializeArrayCards = _interopRequireDefault(require("./initializeArrayCards"));

var _initializeArrayCollapse = _interopRequireDefault(require("./initializeArrayCollapse"));

var _initializeArrayTable = _interopRequireDefault(require("./initializeArrayTable"));

var _initializeArrayItems = _interopRequireDefault(require("./initializeArrayItems"));

var _initializeFormButton = _interopRequireDefault(require("./initializeFormButton"));

var _initializeFormGroup = _interopRequireDefault(require("./initializeFormGroup"));

var _initializeFormStep = _interopRequireDefault(require("./initializeFormStep"));

var _initializeFormTab = _interopRequireDefault(require("./initializeFormTab"));

var _initializeFormCollapse = _interopRequireDefault(require("./initializeFormCollapse"));

var _initializeSelectTable = _interopRequireDefault(require("./initializeSelectTable"));

var _reactions = require("./reactions");

var _fieldTypeMap = _interopRequireDefault(require("../fieldTypeMap"));

var _utils2 = require("../utils");

var _warning = _interopRequireDefault(require("../warning"));

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

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

var _default = /*#__PURE__*/(0, _react.memo)(function (_ref) {
  var schema = _ref.schema,
      scope = _ref.scope,
      components = _ref.components;
  var schemaScopeRef = (0, _react.useRef)({}); // 创建 SchemaField

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

  var formatSchema = (0, _react.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 = (0, _warning.default)(item);
      var _newItem = newItem,
          originalComponent = _newItem.component; // 根据component的不同，初始化为内置的item

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


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


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


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


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


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


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


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


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


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


        if (['SelectTable'].includes(originalComponent)) {
          newItem = (0, _initializeSelectTable.default)(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 ? (0, _utils2.getFieldName)(component === null || component === void 0 ? void 0 : component.replace(/\./g, ''), suffix) : name; // 默认类型

      var defaultType = (0, _adapterType.default)(type, originalComponent); // 默认装饰组件

      var defaultDecorator = (0, _adapterDecorator.default)(decorator, originalComponent); // 默认装饰组件属性

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

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


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


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


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


      var defaultReactions = (0, _initializeReactions.default)(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: (0, _utils.cls)(props === null || props === void 0 ? void 0 : props.className, dataSourceProps === null || dataSourceProps === void 0 ? void 0 : dataSourceProps.className)
      });

      var formatParam = (0, _utils2.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 ((0, _utils.isUsable)(item)) {
        schemaProperties[defaultName] = _objectSpread(_objectSpread(_objectSpread({}, formatParam), recursiveProperties), recursiveItems);
      }
    });
    return schemaProperties;
  }, []);
  var formilySchema = (0, _react.useMemo)(function () {
    return {
      type: 'object',
      properties: formatSchema(schema)
    };
  }, [schema]);

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

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

exports.default = _default;