"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.adapterDataToJSON = adapterDataToJSON;
exports.append = append;
exports.appendFormData = appendFormData;
exports.appendRecords = appendRecords;
exports.arrayMove = arrayMove;
exports.axiosConfigAdapter = axiosConfigAdapter;
exports.checkFieldType = checkFieldType;
exports.checkParentByInsert = checkParentByInsert;
exports.childrenInfoForDelete = childrenInfoForDelete;
exports.concurrentPromise = concurrentPromise;
exports.defaultValueField = exports.defaultTextField = void 0;
exports.doExport = doExport;
exports.exchangeTreeNode = exchangeTreeNode;
exports.exportExcel = exportExcel;
exports.findBindField = findBindField;
exports.findBindFieldBy = findBindFieldBy;
exports.findBindFields = findBindFields;
exports.findBindTargetFields = findBindTargetFields;
exports.findMinOrMaxFields = findMinOrMaxFields;
exports.findRootParent = findRootParent;
exports.fixAxiosConfig = fixAxiosConfig;
exports.generateData = generateData;
exports.generateJSONData = generateJSONData;
exports.generateRecordJSONData = generateRecordJSONData;
exports.generateResponseData = generateResponseData;
exports.getBaseType = getBaseType;
exports.getChainFieldName = getChainFieldName;
exports.getIf = getIf;
exports.getIfForMap = getIfForMap;
exports.getLimit = getLimit;
exports.getOrderFields = getOrderFields;
exports.getRecordDynamicProps = getRecordDynamicProps;
exports.getRecordValue = getRecordValue;
exports.getSortedFields = getSortedFields;
exports.getSpliceRecord = getSpliceRecord;
exports.getSplitValue = getSplitValue;
exports.getUniqueFieldNames = getUniqueFieldNames;
exports.getUniqueKeysAndPrimaryKey = getUniqueKeysAndPrimaryKey;
exports.isDirtyRecord = isDirtyRecord;
exports.mergeDataSetProps = mergeDataSetProps;
exports.mergeGroupStates = mergeGroupStates;
exports.normalizeGroups = normalizeGroups;
exports.prepareForSubmit = prepareForSubmit;
exports.prepareSubmitData = prepareSubmitData;
exports.processExportValue = processExportValue;
exports.processIntlField = processIntlField;
exports.processToJSON = processToJSON;
exports.processValue = processValue;
exports.sliceTree = sliceTree;
exports.sortData = sortData;
exports.sortTree = sortTree;
exports.treeSelect = treeSelect;
exports.treeSelectParent = treeSelectParent;
exports.treeUnSelect = treeUnSelect;
exports.treeUnSelectParent = treeUnSelectParent;
exports.useAll = useAll;
exports.useCascade = useCascade;
exports.useDirty = useDirty;
exports.useDirtyField = useDirtyField;
exports.useNormal = useNormal;
exports.useSelected = useSelected;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _querystringify = _interopRequireDefault(require("querystringify"));

var _moment = _interopRequireWildcard(require("moment"));

var _mobx = require("mobx");

var _isPromise = _interopRequireDefault(require("is-promise"));

var _isBoolean = _interopRequireDefault(require("lodash/isBoolean"));

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _isArray = _interopRequireDefault(require("lodash/isArray"));

var _isNumber = _interopRequireDefault(require("lodash/isNumber"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

var _isEmpty2 = _interopRequireDefault(require("lodash/isEmpty"));

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

var _enum = require("./enum");

var _Group = _interopRequireDefault(require("./Group"));

var ObjectChainValue = _interopRequireWildcard(require("../object-chain-value"));

var _localeContext = _interopRequireWildcard(require("../locale-context"));

var _formatter = require("../formatter");

var _treeHelper = require("../tree-helper");

var _iteratorHelper = require("../iterator-helper");

var _math = _interopRequireDefault(require("../math"));

var _typeMismatch = require("../validator/rules/typeMismatch");

var defaultTextField = 'meaning';
exports.defaultTextField = defaultTextField;
var defaultValueField = 'value';
exports.defaultValueField = defaultValueField;

function useNormal(dataToJSON) {
  return [_enum.DataToJSON.normal, _enum.DataToJSON['normal-self']].includes(dataToJSON);
}

function useAll(dataToJSON) {
  return [_enum.DataToJSON.all, _enum.DataToJSON['all-self']].includes(dataToJSON);
}

function useSelected(dataToJSON) {
  return [_enum.DataToJSON.selected, _enum.DataToJSON['selected-self']].includes(dataToJSON);
}

function useCascade(dataToJSON) {
  return [_enum.DataToJSON.dirty, _enum.DataToJSON['dirty-field'], _enum.DataToJSON.selected, _enum.DataToJSON.all, _enum.DataToJSON.normal].includes(dataToJSON);
}

function useDirty(dataToJSON) {
  return [_enum.DataToJSON.dirty, _enum.DataToJSON['dirty-self']].includes(dataToJSON);
}

function useDirtyField(dataToJSON) {
  return [_enum.DataToJSON['dirty-field'], _enum.DataToJSON['dirty-field-self']].includes(dataToJSON);
}

function append(url, suffix) {
  if (suffix) {
    return url + _querystringify["default"].stringify(suffix, url.indexOf('?') === -1);
  }

  return url;
}

function getOrderFields(dataSet) {
  var fields = dataSet.fields,
      combineSort = dataSet.combineSort,
      combineSortFieldNames = dataSet.combineSortFieldNames;

  if (combineSort) {
    var sortFields = new Map();

    if (combineSortFieldNames && combineSortFieldNames.size > 0) {
      combineSortFieldNames.forEach(function (_, fieldName) {
        var field = dataSet.getField(fieldName);

        if (field && field.order) {
          sortFields.set(fieldName, field);
        }
      });
    } else {
      sortFields = fields;
    }

    return (0, _iteratorHelper.iteratorFilterToArray)(sortFields.values(), function (field) {
      return field.order;
    });
  }

  var found = (0, _iteratorHelper.iteratorFind)(fields.values(), function (field) {
    return field.order;
  });

  if (found) {
    return [found];
  }

  return [];
}

function processOneToJSON(value, field, record) {
  var checkRange = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

  if (!(0, _utils.isEmpty)(value)) {
    var range = field.get('range', record);

    if (range && checkRange) {
      if ((0, _mobx.isArrayLike)(range)) {
        if ((0, _isObject["default"])(value)) {
          var _value;

          var _range = (0, _slicedToArray2["default"])(range, 2),
              start = _range[0],
              end = _range[1];

          value = (_value = {}, (0, _defineProperty2["default"])(_value, start, processOneToJSON(value[start], field, record, false)), (0, _defineProperty2["default"])(_value, end, processOneToJSON(value[end], field, record, false)), _value);
        }
      } else if ((0, _mobx.isArrayLike)(value)) {
        value = [processOneToJSON(value[0], field, record, false), processOneToJSON(value[1], field, record, false)];
      }
    } else if ((0, _mobx.isArrayLike)(value)) {
      // Cascacer 值集
      value = value.map(function (v) {
        return processOneToJSON(v, field, record, false);
      });
    } else {
      if ((0, _moment.isDate)(value)) {
        value = (0, _moment["default"])(value);
      }

      if ((0, _moment.isMoment)(value)) {
        var _field$dataSet$getCon = field.dataSet.getConfig('formatter'),
            jsonDate = _field$dataSet$getCon.jsonDate;

        value = jsonDate ? value.format(jsonDate) : +value;
      }

      if (field.get('type', record) === _enum.FieldType.json) {
        value = JSON.stringify(value);
      }
    }
  }

  return value;
}

function processToJSON(value, field, record) {
  if (!(0, _utils.isEmpty)(value)) {
    var multiple = field.get('multiple', record);
    var range = field.get('range', record);

    if ((0, _mobx.isArrayLike)(value) && (multiple || !range)) {
      value = value.map(function (v) {
        return processOneToJSON(v, field, record);
      });

      if ((0, _isString["default"])(multiple)) {
        return value.join(multiple);
      }

      return value;
    }

    return processOneToJSON(value, field, record);
  }

  return value;
}

function arrayMove(array, from, to) {
  var startIndex = to < 0 ? array.length + to : to;
  var item = array.splice(from, 1)[0];
  array.splice(startIndex, 0, item);
}

function processOne(value, field, record) {
  var checkRange = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

  if (!(0, _utils.isEmpty)(value)) {
    var range = field.get('range', record);

    if (range && checkRange) {
      if ((0, _mobx.isArrayLike)(range)) {
        if ((0, _isObject["default"])(value)) {
          var _range2 = (0, _slicedToArray2["default"])(range, 2),
              start = _range2[0],
              end = _range2[1];

          value[start] = processOne(value[start], field, record, false);
          value[end] = processOne(value[end], field, record, false);
        }
      } else if ((0, _mobx.isArrayLike)(value)) {
        value[0] = processOne(value[0], field, record, false);
        value[1] = processOne(value[1], field, record, false);
      }
    } else if (value instanceof Date) {
      value = (0, _moment["default"])(value);
    } else if (!(0, _isObject["default"])(value)) {
      value = (0, _formatter.formatString)(value, {
        trim: field.get('trim', record),
        format: field.get('format', record)
      });

      switch (field.get('type', record)) {
        case _enum.FieldType["boolean"]:
          {
            var trueValue = field.get(_enum.BooleanValue.trueValue, record);
            var falseValue = field.get(_enum.BooleanValue.falseValue, record);

            if (value !== trueValue) {
              value = falseValue;
            }

            break;
          }

        case _enum.FieldType.number:
        case _enum.FieldType.currency:
          if (!isNaN(value)) {
            value = (0, _utils.parseNumber)(value, field.get('precision', record));
          } else {
            value = undefined;
          }

          break;

        case _enum.FieldType.bigNumber:
          value = (0, _utils.parseBigNumber)(value, field.get('precision', record));
          break;

        case _enum.FieldType.string:
        case _enum.FieldType.intl:
        case _enum.FieldType.email:
        case _enum.FieldType.url:
          value = String(value);
          break;

        case _enum.FieldType.date:
        case _enum.FieldType.dateTime:
        case _enum.FieldType.time:
        case _enum.FieldType.week:
        case _enum.FieldType.month:
        case _enum.FieldType.year:
          {
            var _field$dataSet$getCon2 = field.dataSet.getConfig('formatter'),
                jsonDate = _field$dataSet$getCon2.jsonDate;

            value = jsonDate ? (0, _moment["default"])(value, jsonDate) : (0, _moment["default"])(value);
            break;
          }

        case _enum.FieldType.json:
          value = JSON.parse(value);
          break;

        default:
      }
    }
  }

  return value;
}

function processValue(value, field, record, isCreated) {
  if (field) {
    var multiple = field.get('multiple', record);
    var range = field.get('range', record);

    if (multiple && ![_enum.FieldType.attachment, _enum.FieldType.color].includes(field.get('type', record))) {
      if ((0, _utils.isEmpty)(value)) {
        if (isCreated) {
          // for defaultValue
          value = undefined;
        } else {
          value = [];
        }
      } else if (!(0, _isArray["default"])(value)) {
        if ((0, _isString["default"])(multiple) && (0, _isString["default"])(value)) {
          value = value.split(multiple);
        } else {
          value = [value];
        }
      }
    }

    if ((0, _isArray["default"])(value) && (multiple || !range)) {
      return value.map(function (item) {
        return processOne(item, field, record);
      });
    }

    return processOne(value, field, record);
  }

  return value;
} // 处理单个range


var processRangeToText = function processRangeToText(resultValue, field, record) {
  return resultValue.map(function (item) {
    var valueRange = (0, _moment.isMoment)(item) ? item.format() : (0, _isObject["default"])(item) ? item[field.get('textField', record)] : item.toString();
    return valueRange;
  }).join("~");
};

function processExportValue(value, field, record) {
  if (field) {
    var multiple = field.get('multiple', record);
    var range = field.get('range', record);
    var textField = field.get('textField', record);

    if (multiple) {
      if ((0, _utils.isEmpty)(value)) {
        value = [];
      } else if (!(0, _isArray["default"])(value)) {
        if ((0, _isString["default"])(multiple) && (0, _isString["default"])(value)) {
          value = value.split(multiple);
        } else {
          value = [value];
        }
      }
    }

    if ((0, _isArray["default"])(value) && (multiple || !range)) {
      if (!(0, _isEmpty2["default"])(field.getLookup(record))) {
        return value.map(function (item) {
          return field.getText(processOne(item, field, record), undefined, record);
        }).join(',');
      }

      return value.map(function (item) {
        var itemValue = processOne(item, field, record);

        if (textField && itemValue && (0, _isObject["default"])(itemValue)) {
          return itemValue[textField];
        }

        return itemValue;
      }).join(',');
    }

    if ((0, _isArray["default"])(value) && multiple && range) {
      if (!(0, _isEmpty2["default"])(field.getLookup(record))) {
        return value.map(function (item) {
          return field.getText(processRangeToText(processOne(item, field, record), field, record));
        }).join(',');
      }

      return value.map(function (item) {
        return processRangeToText(processOne(item, field, record), field, record);
      }).join(',');
    }

    if (!(0, _isEmpty2["default"])(field.getLookup(record))) {
      return field.getText(processOne(value, field, record), undefined, record);
    }

    var resultValue = processOne(value, field, record);

    if ((0, _moment.isMoment)(resultValue)) {
      return resultValue.format();
    }

    if (textField && resultValue && (0, _isObject["default"])(resultValue)) {
      if (range && (0, _mobx.isArrayLike)(resultValue)) {
        return processRangeToText(resultValue, field, record);
      }

      return resultValue[textField];
    }

    return resultValue;
  }

  return value;
}
/**
 * 实现如果名字是带有属性含义`.`找到能够导出的值
 * @param dataItem 一行数据
 * @param name 对应的fieldname
 * @param isBind 是否是从绑定获取值
 */


function getSplitValue(dataItem, name) {
  var isBind = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  var nameArray = name.split('.');

  if (nameArray.length > 1) {
    var levelValue = dataItem;

    for (var i = 0; i < nameArray.length; i++) {
      if (!(0, _isObject["default"])(levelValue)) {
        break;
      }

      if (isBind || i !== 0) {
        levelValue = levelValue[nameArray[i]];
      }
    }

    return levelValue;
  }

  if (isBind) {
    return dataItem ? dataItem[name] : undefined;
  }

  return dataItem;
}

function childrenInfoForDelete(json, children) {
  return Object.keys(children).reduce(function (data, name) {
    var child = children[name];

    if (child) {
      data[name] = [childrenInfoForDelete({}, child.children)];
    }

    return data;
  }, json);
}

function dataSorter(fields, getter) {
  var m = Number.MIN_SAFE_INTEGER;
  return function (record1, record2) {
    var result = 0;
    fields.some(function (field) {
      var name = field.name,
          order = field.order;
      var a = getter(record1, name) || m;
      var b = getter(record2, name) || m;

      if ((0, _isString["default"])(a) || (0, _isString["default"])(b)) {
        result = order === _enum.SortOrder.asc ? String(a).localeCompare(String(b)) : String(b).localeCompare(String(a));
      } else {
        result = order === _enum.SortOrder.asc ? a - b : b - a;
      }

      return result !== 0;
    });
    return result;
  };
}

function sortData(data, dataSet) {
  if (data.length > 1 && !dataSet.paging) {
    var orderFields = getOrderFields(dataSet);

    if (orderFields.length > 0) {
      data.sort(dataSorter(orderFields, function (item, key) {
        return item[key];
      }));
      var childrenField = dataSet.props.childrenField;

      if (childrenField) {
        data.forEach(function (item) {
          var childData = item[childrenField];

          if (childData) {
            sortData(childData, dataSet);
          }
        });
      }
    }
  }

  return data;
}

function appendRecords(dataSet, appendData, parent) {
  if (appendData.length) {
    var originalData = dataSet.originalData,
        records = dataSet.records,
        _dataSet$props = dataSet.props,
        childrenField = _dataSet$props.childrenField,
        parentField = _dataSet$props.parentField,
        idField = _dataSet$props.idField;
    var appended = false;

    if (childrenField) {
      if (parent) {
        appendData.forEach(function (record) {
          var key = record.key;
          var children = parent.children;

          if (children) {
            if (!children.find(function (child) {
              return child.key === key;
            })) {
              children.push(record);
            }
          } else {
            parent.children = [record];
          }

          if (!records.find(function (r) {
            return r.key === key;
          })) {
            originalData.push(record);
            records.push(record);
          }
        });
        appended = true;
      }
    } else if (parentField && idField) {
      appendData.forEach(function (record) {
        var parentId = record.get(parentField);
        var key = record.key;
        var found;
        var foundParent;
        records.some(function (r) {
          if (r.get(idField) === parentId) {
            record.parent = r;
            var children = r.children;

            if (children) {
              if (!children.find(function (child) {
                return child.key === key;
              })) {
                children.push(record);
              }
            } else {
              r.children = [record];
            }

            foundParent = r;
          }

          if (r.key === key) {
            found = r;
          }

          return found && foundParent;
        });

        if (!found) {
          originalData.push(record);
          records.push(record);
        }
      });
      appended = true;
    }

    if (!appended) {
      appendData.forEach(function (record) {
        var key = record.key;

        if (!records.find(function (r) {
          return r.key === key;
        })) {
          originalData.push(record);
          records.push(record);
        }
      });
    }
  }
}

function sortTree(records, orderFields, deep) {
  if (records.length > 1 && orderFields.length > 0) {
    if (deep) {
      records.forEach(function (child) {
        var children = child.children;

        if (children) {
          child.children = sortTree(children, orderFields, true);
        }
      });
    }

    return records.sort(dataSorter(orderFields, function (item, key) {
      return item.get(key);
    }));
  }

  return records;
} // 获取单个页面能够展示的数据


function sliceTree(idField, parentField, allData, pageSize) {
  if (allData.length) {
    var rootMap = new Map();
    var itemMap = new Map();
    allData.forEach(function (item) {
      var id = item[idField];

      if (!(0, _isNil["default"])(id)) {
        var node = {
          item: item,
          children: []
        };
        itemMap.set(id, node);
        rootMap.set(id, node);
      }
    });
    itemMap.forEach(function (node, key) {
      var parent = itemMap.get(node.item[parentField]);

      if (parent) {
        parent.children.push(node);
        rootMap["delete"](key);
      }
    });
    return (0, _treeHelper.treeReduce)((0, _iteratorHelper.iteratorSliceToArray)(rootMap.values(), 0, pageSize), function (previousValue, node) {
      return previousValue.concat(node.item);
    }, []);
  }

  return [];
}

function checkParentByInsert(_ref) {
  var parent = _ref.parent;

  if (parent && !parent.current) {
    throw new Error((0, _localeContext.$l)('DataSet', 'cannot_add_record_when_head_no_current'));
  }
}

function getValueType(value) {
  if ((0, _isBoolean["default"])(value)) {
    return _enum.FieldType["boolean"];
  }

  if ((0, _isNumber["default"])(value)) {
    return _enum.FieldType.number;
  }

  if (_typeMismatch.colorRgbaReg.test(value) || _typeMismatch.colorHexReg.test(value)) {
    return _enum.FieldType.color;
  }

  if ((0, _isString["default"])(value)) {
    return _enum.FieldType.string;
  }

  if ((0, _moment.isMoment)(value)) {
    return _enum.FieldType.date;
  }

  if (_math["default"].isBigNumber(value)) {
    return _enum.FieldType.bigNumber;
  }

  if ((0, _isObject["default"])(value)) {
    return _enum.FieldType.object;
  }

  return _enum.FieldType.auto;
}

function getBaseType(type) {
  switch (type) {
    case _enum.FieldType.number:
    case _enum.FieldType.currency:
      return _enum.FieldType.number;

    case _enum.FieldType.dateTime:
    case _enum.FieldType.time:
    case _enum.FieldType.week:
    case _enum.FieldType.month:
    case _enum.FieldType.year:
      return _enum.FieldType.date;

    case _enum.FieldType.intl:
    case _enum.FieldType.url:
    case _enum.FieldType.email:
      return _enum.FieldType.string;

    default:
      return type;
  }
}

function checkFieldType(value, field, record) {
  if (process.env.NODE_ENV !== 'production' && !(0, _utils.isEmpty)(value)) {
    var fieldType = getBaseType(field.get('type', record));

    if (fieldType !== _enum.FieldType.auto) {
      if ((0, _mobx.isArrayLike)(value)) {
        return value.every(function (item) {
          return checkFieldType(item, field, record);
        });
      }

      var valueType = field.get('type', record) === _enum.FieldType["boolean"] && [field.get(_enum.BooleanValue.trueValue, record), field.get(_enum.BooleanValue.falseValue, record)].includes(value) ? _enum.FieldType["boolean"] : getValueType(value);

      if (fieldType !== _enum.FieldType.reactNode && (fieldType === _enum.FieldType.number ? ![_enum.FieldType.number, _enum.FieldType.bigNumber].includes(valueType) : fieldType !== valueType)) {
        (0, _utils.warning)(false, "Value type error: The value<".concat(value, ">'s type is ").concat(valueType, ", but the field<").concat(field.name, ">'s type is ").concat(fieldType, "."));
        return false;
      }
    }
  }

  return true;
}

var iframe;
/**
 * 目前定义为服务端请求的方法
 * @param url 导出地址
 * @param data 导出传递参数
 * @param method 默认post请求
 */

function doExport(url, data) {
  var method = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'post';

  if (!iframe) {
    iframe = document.createElement('iframe');
    iframe.id = '_export_window';
    iframe.name = '_export_window';
    iframe.style.cssText = 'position:absolute;left:-10000px;top:-10000px;width:1px;height:1px;display:none';
    document.body.appendChild(iframe);
  }

  var form = document.createElement('form');
  form.target = '_export_window';
  form.method = method;
  form.action = url;
  var s = document.createElement('input');
  s.id = '_request_data';
  s.type = 'hidden';
  s.name = '_request_data';
  s.value = JSON.stringify(data);
  form.appendChild(s);
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

function throwCycleBindingFields() {
  var map = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Map();
  var keys = Array.from(map.keys());
  throw new Error("DataSet: Cycle binding fields[".concat((0, _toConsumableArray2["default"])(keys).join(' -> '), " -> ").concat(keys[0], "]."));
}

function getChainFieldNamePrivate(record, fieldName) {
  var linkedMap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Map();
  var init = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var field = record.dataSet.getField(fieldName);

  if (field) {
    var bind = field.get('bind', record);

    if (bind) {
      if (linkedMap.has(fieldName)) {
        throwCycleBindingFields(linkedMap);
      }

      linkedMap.set(fieldName, field);
      var names = bind.split('.');

      if (names.length > 0) {
        if (names.length === 1) {
          return getChainFieldNamePrivate(record, bind, linkedMap);
        }

        return names.reduce(function (chainFieldName, name) {
          return [getChainFieldNamePrivate(record, chainFieldName, linkedMap, false), name].join('.');
        });
      }
    }
  } else if (init && fieldName.indexOf('.') > -1) {
    return fieldName.split('.').reduce(function (chainFieldName, name) {
      return [getChainFieldNamePrivate(record, chainFieldName, linkedMap, false), name].join('.');
    });
  }

  return fieldName;
}

function getChainFieldName(record, fieldName) {
  return getChainFieldNamePrivate(record, fieldName);
}

function findBindTargetFields(myField, fields, deep, record) {
  var bindFields = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new Map();
  var bind = myField.get('bind', record);

  if (bind) {
    (0, _iteratorHelper.iteratorSome)(fields.entries(), function (_ref2) {
      var _ref3 = (0, _slicedToArray2["default"])(_ref2, 2),
          fieldName = _ref3[0],
          field = _ref3[1];

      if (field !== myField) {
        if (bind === fieldName || bind.startsWith("".concat(fieldName, "."))) {
          if (bindFields.has(fieldName)) {
            throwCycleBindingFields(bindFields);
          }

          bindFields.set(fieldName, field);

          if (deep) {
            findBindTargetFields(field, fields, deep, record, bindFields);
          }

          return true;
        }
      }

      return false;
    });
  }

  return Array.from(bindFields.values());
}

function findBindFields(myField, fields, deep, record) {
  var bindFields = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new Map();
  var name = myField.name;
  fields.forEach(function (field, fieldName) {
    if (field !== myField) {
      var bind = field.get('bind', record);

      if (bind && (bind === name || bind.startsWith("".concat(name, ".")))) {
        if (bindFields.has(fieldName)) {
          throwCycleBindingFields(bindFields);
        }

        bindFields.set(fieldName, field);

        if (deep) {
          findBindFields(field, fields, deep, record, bindFields);
        }
      }
    }
  });
  return Array.from(bindFields.values());
}

function findBindField(myField, chainFieldName, record) {
  return (0, _iteratorHelper.iteratorFind)(record.dataSet.fields.values(), function (field) {
    var fieldName = field.name;

    if (fieldName !== myField) {
      var bind = field.get('bind', record);

      if (bind) {
        return chainFieldName === getChainFieldName(record, fieldName);
      }
    }

    return false;
  });
}

function findMinOrMaxFields(myField, fields, record) {
  var fieldName = myField.name;
  var minOrMaxFields = [];
  fields.forEach(function (field) {
    var name = field.name;

    if (fieldName !== name && !(0, _isNil["default"])(record.get(name)) && (field.get('min', record) === fieldName || field.get('max', record) === fieldName)) {
      minOrMaxFields.push(field);
    }
  });
  return minOrMaxFields;
}

function generateRecordJSONData(array, record, dataToJSON) {
  var normal = useNormal(dataToJSON);
  var json = normal ? !record.isRemoved && record.toData() : record.toJSONData();

  if (json && (normal || useAll(dataToJSON) || !useDirty(dataToJSON) && !useDirtyField(dataToJSON) || json.__dirty)) {
    delete json.__dirty;
    array.push(json);
  }
}

function prepareSubmitData(records, dataToJSON) {
  var created = [];
  var updated = [];
  var destroyed = [];

  function storeWith(status) {
    switch (status) {
      case _enum.RecordStatus.add:
        return created;

      case _enum.RecordStatus["delete"]:
        return destroyed;

      default:
        return updated;
    }
  }

  records.forEach(function (record) {
    return generateRecordJSONData(storeWith(record.status), record, dataToJSON);
  });
  return [created, updated, destroyed];
}

function defaultAxiosConfigAdapter(config) {
  return config;
}

function generateConfig(config, dataSet, data, params, options) {
  if ((0, _isString["default"])(config)) {
    return {
      url: config
    };
  }

  if (typeof config === 'function') {
    return config((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, options), {}, {
      data: data,
      dataSet: dataSet,
      params: params
    }));
  }

  return config;
}

function axiosConfigAdapter(type, dataSet, data, params, options) {
  var newConfig = {
    data: data,
    params: params,
    method: 'post'
  };

  var _ref4 = dataSet.getConfig('transport') || {},
      globalConfig = _ref4[type],
      _ref4$adapter = _ref4.adapter,
      globalAdapter = _ref4$adapter === void 0 ? defaultAxiosConfigAdapter : _ref4$adapter;

  var _dataSet$transport = dataSet.transport,
      config = _dataSet$transport[type],
      adapter = _dataSet$transport.adapter;

  if (globalConfig) {
    (0, _extends2["default"])(newConfig, generateConfig(globalConfig, dataSet, data, params, options));
  }

  if (config) {
    (0, _extends2["default"])(newConfig, generateConfig(config, dataSet, data, params, options));
  }

  if (newConfig.data && newConfig.method && newConfig.method.toLowerCase() === 'get') {
    newConfig.params = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, newConfig.params), newConfig.data);
  }

  return (adapter || globalAdapter)(newConfig, type) || newConfig;
} // 查询顶层父亲节点


function findRootParent(children) {
  if (children.parent) {
    return findRootParent(children.parent);
  }

  return children;
}

function prepareForSubmit(type, data, configs, dataSet) {
  if (data.length) {
    var newConfig = axiosConfigAdapter(type, dataSet, data);

    if (newConfig.url) {
      configs.push(newConfig);
    } else {
      return data;
    }
  }

  return [];
}

function generateResponseData(item, dataKey) {
  if (item) {
    if ((0, _isArray["default"])(item)) {
      return item;
    }

    if ((0, _isObject["default"])(item)) {
      if (dataKey) {
        var result = ObjectChainValue.get(item, dataKey);

        if (result === undefined) {
          return [item];
        }

        if ((0, _isArray["default"])(result)) {
          return result;
        }

        if ((0, _isObject["default"])(result)) {
          return [result];
        }
      } else {
        return [item];
      }
    }
  }

  return [];
}

function getRecordValue(record, cb, fieldName) {
  if (fieldName) {
    if ((0, _mobx.isArrayLike)(fieldName)) {
      return fieldName.reduce(function (value, key) {
        value[key] = getRecordValue(record, cb, key);
        return value;
      }, {});
    }

    var dataSet = record.dataSet;
    var chainFieldName = getChainFieldName(record, fieldName);
    var _dataSet$props2 = dataSet.props,
        checkField = _dataSet$props2.checkField,
        treeCheckStrictly = _dataSet$props2.treeCheckStrictly;

    if (treeCheckStrictly !== true && checkField && chainFieldName === getChainFieldName(record, checkField)) {
      var field = dataSet.getField(checkField);
      var trueValue = field ? field.get(_enum.BooleanValue.trueValue, record) : true;
      var falseValue = field ? field.get(_enum.BooleanValue.falseValue, record) : false;
      var children = record.children;

      if (children) {
        return children.every(function (child) {
          return cb(child, checkField) === trueValue;
        }) ? trueValue : falseValue;
      }
    }

    return ObjectChainValue.get(record.data, chainFieldName);
  }
}

function processIntlField(name, callback, fieldProps, dataSet) {
  var field = callback((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, fieldProps), {}, {
    name: name
  }));

  if (fieldProps && fieldProps.type === _enum.FieldType.intl) {
    var transformRequest = fieldProps.transformRequest;
    var tlsKey = dataSet.getConfig('tlsKey');
    var supports = _localeContext["default"].supports;
    var languages = Object.keys(supports);
    var intlFields = new Map();
    languages.forEach(function (language) {
      return intlFields.set("".concat(tlsKey, ".").concat(name, ".").concat(language), callback({
        name: "".concat(tlsKey, ".").concat(name, ".").concat(language),
        type: _enum.FieldType.string,
        label: "".concat(supports[language]),
        transformRequest: transformRequest,
        dynamicProps: {
          bind: function bind(_ref5) {
            var record = _ref5.record;

            if (record) {
              var tls = record.get(tlsKey) || {};

              if (name in tls && dataSet.lang === language) {
                return name;
              }
            }
          }
        }
      }));
    });
    return [field, intlFields];
  }

  return [field, undefined];
}

function findBindFieldBy(myField, fields, prop, record) {
  var value = myField.get(prop, record);
  var myName = myField.name;
  return (0, _iteratorHelper.iteratorFind)(fields.values(), function (field) {
    var bind = field.get('bind', record);
    return bind && bind === "".concat(myName, ".").concat(value);
  });
}

function getLimit(limit, record, minOrMax, type) {
  if ((0, _isString["default"])(limit) && record.dataSet.getField(limit)) {
    return record.get(limit);
  }

  if (limit === undefined) {
    var configLimit = record.dataSet.getConfig(minOrMax);

    if (configLimit && typeof configLimit === 'function') {
      return configLimit(type);
    }
  }

  return limit;
}

function adapterDataToJSON(isSelected, noCascade) {
  if (isSelected) {
    if (noCascade) {
      return _enum.DataToJSON['selected-self'];
    }

    return _enum.DataToJSON.selected;
  }

  if (noCascade) {
    return _enum.DataToJSON['dirty-self'];
  }

  return undefined;
}

function generateData(records) {
  var dirty = false;
  var data = records.reduce(function (list, record) {
    if (record.isRemoved) {
      dirty = true;
    } else {
      var d = record.toData();

      if (d.__dirty) {
        dirty = true;
      }

      delete d.__dirty;
      list.push(d);
    }

    return list;
  }, []);
  return {
    dirty: dirty,
    data: data
  };
}

function generateJSONData(ds, records) {
  var dataToJSON = ds.dataToJSON;
  var data = [];
  records.forEach(function (record) {
    return generateRecordJSONData(data, record, dataToJSON);
  });
  return {
    dirty: data.length > 0,
    data: data
  };
}

function getUniqueFieldNames(dataSet) {
  var keys = [];
  dataSet.fields.forEach(function (field, key) {
    if (field.get('unique')) {
      keys.push(key);
    }
  });
  return keys;
}

function getUniqueKeysAndPrimaryKey(dataSet) {
  var keys = getUniqueFieldNames(dataSet);
  var primaryKey = dataSet.props.primaryKey;

  if (primaryKey) {
    keys.push(primaryKey);
  }

  return keys;
}

function isDirtyRecord(record) {
  return record.status !== _enum.RecordStatus.sync || record.dirty;
}

function getSpliceRecord(records, inserts, fromRecord) {
  if (fromRecord) {
    if (inserts.includes(fromRecord)) {
      return getSpliceRecord(records, inserts, records[records.indexOf(fromRecord) + 1]);
    }

    return fromRecord;
  }
} // bugs in react native


function fixAxiosConfig(config) {
  var method = config.method;

  if (method && method.toLowerCase() === 'get') {
    delete config.data;
  }

  return config;
}

function normalizeGroupsToTree(groups) {
  var map1 = new Map();
  var map2 = new Map();
  groups.forEach(function (group) {
    var subGroups = group.subGroups,
        value = group.value;
    map1.set(String(value), group);
    map2.set(String(value), group);

    if (subGroups.length) {
      group.subGroups = normalizeGroupsToTree(subGroups);
    }
  });

  if (map1.size) {
    map1.forEach(function (group) {
      var parentValue = group.parentValue;
      var parent = parentValue ? map1.get(String(parentValue)) : undefined;

      if (parent) {
        if (parent.children) {
          parent.children.push(group);
        } else {
          parent.children = [group];
        }

        group.parent = parent;
        map2["delete"](String(group.value));
      }
    });
    return (0, _toConsumableArray2["default"])(map2.values());
  }

  return groups;
}

var EMPTY_GROUP_KEY = Symbol('__empty_group__');

function normalizeGroups(groups, hGroups, records, parentFields) {
  var optGroups = [];
  var emptyGroup = new _Group["default"](EMPTY_GROUP_KEY, 0);
  records.forEach(function (record) {
    var previousGroup;
    groups.forEach(function (name) {
      var value = record.get(name);

      if (!previousGroup) {
        previousGroup = optGroups.find(function (item) {
          return item.value === value;
        });

        if (!previousGroup) {
          previousGroup = new _Group["default"](name, optGroups.length, value);
          optGroups.push(previousGroup);
        }
      } else {
        var _previousGroup = previousGroup,
            subGroups = _previousGroup.subGroups;
        var parent = previousGroup;
        previousGroup = subGroups.find(function (item) {
          return item.value === value;
        });

        if (!previousGroup) {
          previousGroup = new _Group["default"](name, subGroups.length, value, parent);
          subGroups.push(previousGroup);
        }
      }

      var parentField = parentFields && parentFields.get(name);

      if (previousGroup && previousGroup.parentName !== parentField) {
        previousGroup.parentName = parentField;
        previousGroup.parentValue = record.get(parentField);
      }
    });

    if (hGroups.length) {
      var _ref6 = previousGroup || emptyGroup,
          subHGroups = _ref6.subHGroups;

      if (!subHGroups) {
        subHGroups = new Set();
        (previousGroup || emptyGroup).subHGroups = subHGroups;
      }

      hGroups.forEach(function (key) {
        var label = record.get(key);

        if (!previousGroup) {
          previousGroup = optGroups.find(function (item) {
            return item.value === label;
          });

          if (!previousGroup) {
            previousGroup = new _Group["default"](key, optGroups.length, label);
            optGroups.push(previousGroup);
          }
        } else {
          var _previousGroup2 = previousGroup,
              subGroups = _previousGroup2.subGroups;
          var parent = previousGroup;
          previousGroup = subGroups.find(function (item) {
            return item.value === label;
          });

          if (!previousGroup) {
            previousGroup = new _Group["default"](key, subGroups.length, label, parent);
            subGroups.push(previousGroup);
          }
        }
      });

      if (previousGroup) {
        subHGroups.add(previousGroup);
      }
    }

    if (previousGroup) {
      var _previousGroup3 = previousGroup,
          groupRecords = _previousGroup3.records;
      groupRecords.push(record);
      var parent = previousGroup;

      while (parent) {
        parent.totalRecords.push(record);
        parent = parent.parentGroup;
      }
    }
  });

  if (parentFields && parentFields.size) {
    return normalizeGroupsToTree(optGroups);
  }

  if (!groups.length) {
    if (hGroups.length) {
      emptyGroup.subGroups = optGroups;
    } else {
      emptyGroup.records = records.slice();
    }

    return [emptyGroup];
  }

  return optGroups;
}

function mergeHGroupStates(newGroups, oldGroups) {
  if (newGroups && oldGroups && newGroups.size && oldGroups.size) {
    oldGroups.forEach(function (oldGroup) {
      var state = oldGroup.state;

      if (state) {
        var name = oldGroup.name,
            value = oldGroup.value;
        var newGroup = (0, _iteratorHelper.iteratorFind)(newGroups.values(), function (group) {
          return group.name === name && group.value === value;
        });

        if (newGroup) {
          newGroup.mergeState(state);
          mergeGroupStates(newGroup.subGroups, oldGroup.subGroups);
          mergeHGroupStates(newGroup.subHGroups, oldGroup.subHGroups);
        }
      }
    });
  }
}

function mergeGroupStates(newGroups, oldGroups) {
  if (oldGroups && oldGroups.length && newGroups.length) {
    oldGroups.forEach(function (oldGroup) {
      var state = oldGroup.state;

      if (state) {
        var name = oldGroup.name,
            value = oldGroup.value;
        var newGroup = newGroups.find(function (group) {
          return group.name === name && group.value === value;
        });

        if (newGroup) {
          newGroup.mergeState(state);
          mergeGroupStates(newGroup.subGroups, oldGroup.subGroups);
          mergeHGroupStates(newGroup.subHGroups, oldGroup.subHGroups);
        }
      }
    });
  }

  return newGroups;
}
/**
 *
 * @param data 导出需要导出的数据
 * @param excelname 导出表单的名字
 */


function exportExcel(data, excelName, getXLSX) {
  var promise = getXLSX();

  if (!promise || !(0, _isPromise["default"])(promise)) {
    throw new Error('For using the excel export, please set the `xlsx` hook of configure to import xlsx module.');
  }

  promise.then(function (XLSX) {
    var ws = XLSX.utils.json_to_sheet(data, {
      skipHeader: true
    });
    /* 新建空workbook，然后加入worksheet */

    var wb = XLSX.utils.book_new();
    /* 新建book */

    XLSX.utils.book_append_sheet(wb, ws);
    /* 生成xlsx文件(book,sheet数据,sheet命名) */

    XLSX.writeFile(wb, "".concat(excelName, ".xlsx"));
    /* 写文件(book,xlsx文件名称) */
  });
}

function getSortedFields(dataSet) {
  var fields = dataSet.fields;

  if (dataSet.$needToSortFields) {
    var normalFields = [];
    var objectBindFields = [];
    var bindFields = [];
    var transformResponseField = [];
    var dynamicFields = [];
    var dynamicObjectBindFields = [];
    var dynamicBindFields = [];
    fields.forEach(function (field, name, map) {
      var entry = [name, field];
      var dynamicProps = field.get('dynamicProps') || field.get('computedProps');
      var type = field.get('type');
      var bind = field.get('bind');
      var transformResponse = field.get('transformResponse');

      if (dynamicProps) {
        if (dynamicProps.bind) {
          if (type === _enum.FieldType.object) {
            dynamicObjectBindFields.push(entry);
          } else {
            dynamicBindFields.push(entry);
          }
        } else {
          dynamicFields.push(entry);
        }
      } else if (bind) {
        var targetNames = bind.split('.');
        targetNames.pop();

        if (targetNames.some(function (targetName) {
          var target = map.get(targetName);
          return target && (target.get('computedProps') || target.get('dynamicProps'));
        })) {
          if (type === _enum.FieldType.object) {
            dynamicObjectBindFields.push(entry);
          } else {
            dynamicBindFields.push(entry);
          }
        } else if (transformResponse) {
          transformResponseField.push(entry);
        } else if (type === _enum.FieldType.object) {
          objectBindFields.push(entry);
        } else {
          bindFields.push(entry);
        }
      } else {
        normalFields.push(entry);
      }
    });
    fields.replace([].concat(normalFields, objectBindFields, bindFields, transformResponseField, dynamicFields, dynamicObjectBindFields, dynamicBindFields));
    delete dataSet.$needToSortFields;
  }

  return fields;
}

function concurrentPromise(_x, _x2) {
  return _concurrentPromise.apply(this, arguments);
}

function _concurrentPromise() {
  _concurrentPromise = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(promiseLoaders, cancelFnc) {
    var promiseLoadersLength, fail;
    return _regenerator["default"].wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            promiseLoadersLength = promiseLoaders.length;
            fail = false;
            return _context2.abrupt("return", new Promise(function (resolve, reject) {
              var resulet = Array(promiseLoadersLength).fill(null); // 依次执行promise
              // 最大并发数

              // 依次执行promise
              // 最大并发数
              var maxConcurrent = Math.min(5, promiseLoadersLength);
              var currentPromiseIndex = 0;

              var execPromise = /*#__PURE__*/function () {
                var _ref7 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(loader, index) {
                  var res;
                  return _regenerator["default"].wrap(function _callee$(_context) {
                    while (1) {
                      switch (_context.prev = _context.next) {
                        case 0:
                          if (!fail) {
                            _context.next = 2;
                            break;
                          }

                          return _context.abrupt("return");

                        case 2:
                          if (!cancelFnc(resulet.filter(Boolean).length)) {
                            _context.next = 6;
                            break;
                          }

                          fail = true;
                          reject();
                          return _context.abrupt("return");

                        case 6:
                          _context.prev = 6;

                          if (loader) {
                            _context.next = 9;
                            break;
                          }

                          throw new Error('loader is undefined');

                        case 9:
                          _context.next = 11;
                          return loader.getPromise();

                        case 11:
                          res = _context.sent;
                          _context.next = 19;
                          break;

                        case 14:
                          _context.prev = 14;
                          _context.t0 = _context["catch"](6);
                          fail = true;
                          reject(_context.t0);
                          return _context.abrupt("return");

                        case 19:
                          resulet[index] = res; // 判断是否完结

                          if (!(currentPromiseIndex === promiseLoadersLength - 1 && resulet.every(Boolean))) {
                            _context.next = 23;
                            break;
                          }

                          resolve(resulet);
                          return _context.abrupt("return");

                        case 23:
                          // 执行下一个promise
                          if (currentPromiseIndex < promiseLoadersLength - 1) {
                            ++currentPromiseIndex;
                            execPromise(promiseLoaders[currentPromiseIndex], currentPromiseIndex);
                          }

                        case 24:
                        case "end":
                          return _context.stop();
                      }
                    }
                  }, _callee, null, [[6, 14]]);
                }));

                return function execPromise(_x3, _x4) {
                  return _ref7.apply(this, arguments);
                };
              }(); // 初始化执行


              // 初始化执行
              for (var i = 0; i < maxConcurrent; i++) {
                execPromise(promiseLoaders[i], i);
              }

              currentPromiseIndex = maxConcurrent - 1;
            }));

          case 3:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _concurrentPromise.apply(this, arguments);
}

function treeSelect(dataSet, record, selected) {
  dataSet.select(record);

  if (record.isSelected) {
    selected.push(record);
    var children = record.children;

    if (children) {
      children.forEach(function (child) {
        return treeSelect(dataSet, child, selected);
      });
    }
  }
}

function treeUnSelect(dataSet, record, unSelected) {
  dataSet.unSelect(record);

  if (!record.isSelected) {
    unSelected.push(record);
    var children = record.children;

    if (children) {
      children.forEach(function (child) {
        return treeUnSelect(dataSet, child, unSelected);
      });
    }
  }
}

function treeSelectParent(dataSet, record, selected) {
  var parent = record.parent;

  if (parent && !parent.isSelected) {
    dataSet.select(parent);
    selected.push(parent);
    treeSelectParent(dataSet, parent, selected);
  }
}

function treeUnSelectParent(dataSet, record, unSelected) {
  var parent = record.parent;

  if (parent && parent.isSelected) {
    var children = parent.children;

    if (children && children.every(function (child) {
      return !child.isSelected;
    })) {
      dataSet.unSelect(parent);
      unSelected.push(parent);
      treeUnSelectParent(dataSet, parent, unSelected);
    }
  }
}

function exchangeTreeNode(newRecord, oldRecord) {
  var parent = oldRecord.parent,
      children = oldRecord.children;
  newRecord.parent = parent;
  newRecord.children = children;

  if (parent) {
    var parentChildren = parent.children;

    if (parentChildren) {
      var index = parentChildren.indexOf(oldRecord);

      if (index !== -1) {
        parentChildren.splice(index, 1, newRecord);
      }
    }
  }

  return newRecord;
}

function getIf(target, propName, defaultValue) {
  var value = target[propName];

  if (value === undefined) {
    target[propName] = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
    return target[propName];
  }

  return value;
}

function getIfForMap(target, propName, defaultValue) {
  var value = target.get(propName);

  if (value === undefined) {
    var newValue = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
    target.set(propName, newValue);
    return newValue;
  }

  return value;
}

function getRecordDynamicProps(record, key, defaultValue) {
  var recordProps = record.dataSet.props.record;

  if (recordProps) {
    var dynamicProps = recordProps.dynamicProps;

    if (dynamicProps) {
      var hook = dynamicProps[key];

      if (hook) {
        var result = hook(record);

        if (result !== undefined) {
          return result;
        }
      }
    }

    var value = recordProps[key];

    if (value !== undefined) {
      return value;
    }
  }

  return defaultValue;
}

function mergeDataSetProps(props, dataSetProps) {
  if (typeof dataSetProps === 'function') {
    return dataSetProps(props || {});
  }

  return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), dataSetProps);
}

function appendFormData(formData, data) {
  Object.keys(data).forEach(function (key) {
    return formData.append(key, data[key]);
  });
}
//# sourceMappingURL=utils.js.map
