import { concat } from '../_util/utils';

const getChildrenByValues = function (nodeList) {
  let values = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  const arr = [...values];
  values.forEach(value => {
    const node = nodeList.get(value);
    if (node.hasChildren) {
      // 比Array.concat快
      concat(arr, node.childrenPath);
    }
  });
  return arr;
};
const getParentByValues = function (nodeList) {
  let values = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  const res = {};
  values.forEach(value => {
    const node = nodeList.get(value);
    if (!node) {
      return;
    }
    if (!res[node.level]) {
      res[node.level] = [];
    }
    res[node.level].push(node.value);
  });
  const levels = Object.keys(res).map(key => Number(key));
  const maxLevel = levels[levels.length - 1];
  for (let level = maxLevel; level > 0; level--) {
    const levelValues = res[level];
    if (levelValues) {
      levelValues.forEach(value => {
        const node = nodeList.get(value);
        const parentValue = node.indexPath[node.indexPath.length - 2];
        if (parentValue) {
          const parentNode = nodeList.get(parentValue);
          if (parentNode.children.every(child => levelValues.includes(child.value))) {
            if (!res[level - 1]) {
              res[level - 1] = [];
            }
            if (!res[level - 1].includes(parentValue)) {
              res[level - 1].push(parentValue);
            }
          }
        }
      });
    }
  }
  const arr = [];
  Object.values(res).forEach(levelValues => {
    // 比Array.concat快
    concat(arr, levelValues);
  });
  return arr;
};
const getBrotherKeys = (node, props, nodeList) => {
  var _nodeList$get;
  const parentNode = node.indexPath[node.indexPath.length - 2];
  const arr = [];
  (parentNode ? ((_nodeList$get = nodeList.get(parentNode)) === null || _nodeList$get === void 0 ? void 0 : _nodeList$get.children) || [] : props.data).forEach(item => {
    const value = item[props.valueField];
    if (value !== node.value) {
      arr.push(value);
    }
  });
  return arr;
};

export { getBrotherKeys, getChildrenByValues, getParentByValues };
