
function _typeof(obj) {
  "@babel/helpers - typeof";

  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
    _typeof = function (obj) {
      return typeof obj;
    };
  } else {
    _typeof = function (obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
  }

  return _typeof(obj);
}

function isObject(object) {
  return Object.prototype.toString.call(object) === '[object Object]';
} // is arguments

function isArguments(object) {
  return Object.prototype.toString.call(object) === '[object Arguments]';
} // 定义的数据推导出schema 类型

// $ref 引用
function getPathVal$1(obj, pathStr) {
  var pathArr = pathStr.split('/');

  for (var i = 0; i < pathArr.length; i += 1) {
    if (obj === undefined) return undefined;
    obj = pathArr[i] === '' ? obj : obj[pathArr[i]];
  }

  return obj;
} // 找到ref引用的schema


function findSchemaDefinition($ref) {
  var rootSchema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var origRef = $ref;

  if ($ref.startsWith('#')) {
    // Decode URI fragment representation.
    $ref = decodeURIComponent($ref.substring(1));
  } else {
    throw new Error("Could not find a definition for ".concat(origRef, "."));
  }

  var current = getPathVal$1(rootSchema, $ref);

  if (current === undefined) {
    throw new Error("Could not find a definition for ".concat(origRef, "."));
  }

  if (current.hasOwnProperty('$ref')) {
    return findSchemaDefinition(current.$ref, rootSchema);
  }

  return current;
}



function resolveReference(schema, rootSchema, formData) {
  // Retrieve the referenced schema definition.
  var $refSchema = findSchemaDefinition(schema.$ref, rootSchema); // Drop the $ref property of the source schema.
  // eslint-disable-next-line no-unused-vars

  schema.$ref;
  var localSchema = _objectWithoutProperties(schema, ["$ref"]); // Update referenced schema definition with local schema properties.


  return retrieveSchema(_objectSpread2(_objectSpread2({}, $refSchema), localSchema), rootSchema, formData);
} // 深度递归合并 合并allOf的每2项

function resolveSchema$1(schema) {
  var rootSchema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var formData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  // allOf 、$ref、dependencies 可能被同时配置
  // allOf
  if (schema.hasOwnProperty('allOf')) {
    schema = resolveAllOf(schema, rootSchema, formData);
  } // $ref


  if (schema.hasOwnProperty('$ref')) {
    schema = resolveReference(schema, rootSchema, formData);
  } // dependencies

  /*
  if (schema.hasOwnProperty('dependencies')) {
      const resolvedSchema = resolveDependencies(schema, rootSchema, formData);
      schema = retrieveSchema(resolvedSchema, rootSchema, formData);
  }
  */
  // additionalProperties

  /*
  const hasAdditionalProperties = schema.hasOwnProperty('additionalProperties') && schema.additionalProperties !== false;
  if (hasAdditionalProperties) {
      return stubExistingAdditionalProperties(
          schema,
          rootSchema,
          formData
      );
  }
  */


  return schema;
} // 这个函数将为formData中的每个键创建新的“属性”项
// 查找到附加属性统一到properties[key]格式 并且打上标准




function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);

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

  return keys;
}

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 _objectSpread2(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i] != null ? arguments[i] : {};

    if (i % 2) {
      ownKeys(Object(source), true).forEach(function (key) {
        _defineProperty(target, key, source[key]);
      });
    } else if (Object.getOwnPropertyDescriptors) {
      Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
      ownKeys(Object(source)).forEach(function (key) {
        Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
      });
    }
  }

  return target;
}

function retrieveSchema(schema) {
  var rootSchema = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var formData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

  if (!isObject(schema)) {
    return {};
  }

  return resolveSchema$1(schema, rootSchema, formData);
}

function resolveAllOf(schema, rootSchema, formData) {
  // allOf item中可能存在 $ref
  var resolvedAllOfRefSchema = _objectSpread2(_objectSpread2({}, schema), {}, {
    allOf: schema.allOf.map(function (allOfItem) {
      return retrieveSchema(allOfItem, rootSchema, formData);
    })
  });

  try {
    var allOf = resolvedAllOfRefSchema.allOf,
      originProperties = _objectWithoutProperties(resolvedAllOfRefSchema, ["allOf"]);

    return mergeSchemaAllOf.apply(void 0, [originProperties].concat(_toConsumableArray(allOf)));
  } catch (e) {
    console.error("\u65E0\u6CD5\u5408\u5E76allOf\uFF0C\u4E22\u5F03allOf\u914D\u7F6E\u7EE7\u7EED\u6E32\u67D3: \n".concat(e)); // eslint-disable-next-line no-unused-vars

    resolvedAllOfRefSchema.allOf;
    var resolvedSchemaWithoutAllOf = _objectWithoutProperties(resolvedAllOfRefSchema, ["allOf"]);

    return resolvedSchemaWithoutAllOf;
  }
} // resolve Schema

var guessType = function guessType(value) {
  if (Array.isArray(value)) {
    return 'array';
  }

  if (typeof value === 'string') {
    return 'string';
  }

  if (value == null) {
    return 'null';
  }

  if (typeof value === 'boolean') {
    return 'boolean'; // eslint-disable-next-line no-restricted-globals
  }

  if (!isNaN(value)) {
    return 'number';
  }

  if (_typeof(value) === 'object') {
    return 'object';
  } // Default to string if we can't figure it out


  return 'string';
};

function getSchemaType(schema) {
  var type = schema.type; // 通过const 申明的常量 做类型推断

  if (!type && schema.const) {
    return guessType(schema.const);
  } // 枚举默认字符串


  if (!type && schema.enum) {
    return 'string';
  } // items 推断为 array 类型


  if (!type && schema.items) {
    return 'array';
  } // anyOf oneOf 不申明 type 字段


  if (!type && (schema.properties || schema.additionalProperties)) {
    return 'object';
  }

  if (type instanceof Array && type.length === 2 && type.includes('null')) {
    return type.find(function (curType) {
      return curType !== 'null';
    });
  }

  return type;
} // 深度相等对比

function isFixedItems(schema) {
  return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every(function (item) {
    return isObject(item);
  });
} // 是否为多选

function computeDefaults(_schema, parentDefaults, rootSchema) {
  var rawFormData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var includeUndefinedValues = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  var haveAllFields = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
  var schema = isObject(_schema) ? _schema : {};
  var formData = isObject(rawFormData) ? rawFormData : {}; // allOf 处理合并数据

  if ('allOf' in schema) {
    schema = resolveAllOf(schema, rootSchema, formData);
  } // Compute the defaults recursively: give highest priority to deepest nodes.


  var defaults = parentDefaults;

  if (isObject(defaults) && isObject(schema.default)) {
    // For object defaults, only override parent defaults that are defined in
    // schema.default.
    defaults = mergeObjects(defaults, schema.default);
  } else if ('default' in schema) {
    // Use schema defaults for this node.
    defaults = schema.default;
  } else if ('$ref' in schema) {
    // Use referenced schema defaults for this node.
    var refSchema = findSchemaDefinition(schema.$ref, rootSchema);
    return computeDefaults(refSchema, defaults, rootSchema, formData, includeUndefinedValues, haveAllFields);
  } else if (
    /* ('dependencies' in schema) {
    const resolvedSchema = resolveDependencies(schema, rootSchema, formData);
    return computeDefaults(
    resolvedSchema,
    defaults,
    rootSchema,
    formData,
    includeUndefinedValues,
    haveAllFields
    );
    } else if */
    isFixedItems(schema)) {
    defaults = schema.items.map(function (itemSchema, idx) {
      return computeDefaults(itemSchema, Array.isArray(parentDefaults) ? parentDefaults[idx] : undefined, rootSchema, formData, includeUndefinedValues, haveAllFields);
    });
  } else if ('oneOf' in schema) {
    var matchSchema = retrieveSchema(schema.oneOf[getMatchingOption(formData, schema.oneOf, rootSchema, haveAllFields)], rootSchema, formData);
    schema = mergeObjects(schema, matchSchema);
    delete schema.oneOf; // if (schema.properties && matchSchema.properties) {
    //     // 对象 oneOf 需要合并原属性和 oneOf 属性
    //     const mergeSchema = mergeObjects(schema, matchSchema);
    //     delete mergeSchema.oneOf;
    //     schema = mergeSchema;
    // } else {
    //     schema = matchSchema;
    // }
  } else if ('anyOf' in schema) {
    var _matchSchema = retrieveSchema(schema.anyOf[getMatchingOption(formData, schema.anyOf, rootSchema, haveAllFields)], rootSchema, formData);

    schema = mergeObjects(schema, _matchSchema);
    delete schema.anyOf; // if (schema.properties && matchSchema.properties) {
    //     // 对象 anyOf 需要合并原属性和 anyOf 属性
    //     const mergeSchema = mergeObjects(schema, matchSchema);
    //     delete mergeSchema.anyOf;
    //     schema = mergeSchema;
    // } else {
    //     schema = matchSchema;
    // }
  } // Not defaults defined for this node, fallback to generic typed ones.


  if (typeof defaults === 'undefined') {
    defaults = schema.default;
  } // eslint-disable-next-line default-case


  switch (getSchemaType(schema)) {
    case 'null':
      return null;
    // We need to recur for object schema inner default values.

    case 'object':
      return Object.keys(schema.properties || {}).reduce(function (acc, key) {
        // Compute the defaults for this node, with the parent defaults we might
        // have from a previous run: defaults[key].
        var computedDefault = computeDefaults(schema.properties[key], (defaults || {})[key], rootSchema, (formData || {})[key], includeUndefinedValues, haveAllFields);

        if (includeUndefinedValues || computedDefault !== undefined) {
          acc[key] = computedDefault;
        }

        return acc;
      }, {});

    case 'array':
      // Inject defaults into existing array defaults
      if (Array.isArray(defaults)) {
        defaults = defaults.map(function (item, idx) {
          return computeDefaults(schema.items[idx] || schema.additionalItems || {}, item, rootSchema, {}, includeUndefinedValues, haveAllFields);
        });
      } // Deeply inject defaults into already existing form data


      if (Array.isArray(rawFormData)) {
        defaults = rawFormData.map(function (item, idx) {
          return computeDefaults(schema.items, (defaults || {})[idx], rootSchema, item, {}, includeUndefinedValues, haveAllFields);
        });
      }

      if (schema.minItems) {
        if (!isMultiSelect(schema, rootSchema)) {
          var defaultsLength = defaults ? defaults.length : 0;

          if (schema.minItems > defaultsLength) {
            var defaultEntries = defaults || []; // populate the array with the defaults

            var fillerSchema = Array.isArray(schema.items) ? schema.additionalItems : schema.items;
            var fillerEntries = fillObj(new Array(schema.minItems - defaultsLength), computeDefaults(fillerSchema, fillerSchema.defaults, rootSchema, {}, includeUndefinedValues, haveAllFields));
            return defaultEntries.concat(fillerEntries);
          }
        } else {
          return defaults || [];
        }
      } // undefined 默认一个空数组


      defaults = defaults === undefined ? [] : defaults;
  }

  return defaults;
} // 获取默认form data  


function mergeDefaultsWithFormData(defaults, formData) {
  if (Array.isArray(formData)) {
    if (!Array.isArray(defaults)) {
      defaults = [];
    }

    return formData.map(function (value, idx) {
      if (defaults[idx]) {
        return mergeDefaultsWithFormData(defaults[idx], value);
      }

      return value;
    });
  }

  if (isObject(formData)) {
    var acc = Object.assign({}, defaults); // Prevent mutation of source object.

    return Object.keys(formData).reduce(function (preAcc, key) {
      preAcc[key] = mergeDefaultsWithFormData(defaults ? defaults[key] : {}, formData[key]);
      return preAcc;
    }, acc);
  }

  return formData;
}


function getDefaultFormState(_schema, formData) {
  var rootSchema = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var includeUndefinedValues = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var haveAllFields = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;

  if (!isObject(_schema)) {
    throw new Error("Invalid schema: ".concat(_schema));
  }

  var schema = retrieveSchema(_schema, rootSchema, formData);
  var defaults = computeDefaults(schema, _schema.default, rootSchema, formData, includeUndefinedValues, haveAllFields);

  if (typeof formData === 'undefined') {
    // No form data? Use schema defaults.
    return defaults;
  } // 传入formData时，合并传入数据


  if (isObject(formData) || Array.isArray(formData)) {
    return mergeDefaultsWithFormData(defaults, formData);
  }

  if (formData === 0 || formData === false || formData === '') {
    return formData;
  }

  return formData || defaults;
}

import htmlParser from './html-parser'
export { getDefaultFormState, htmlParser };