"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.uniqueArray = exports.transToMapData = exports.toTree = exports.formatNodes = exports.findNode = exports.diffAndUpdate = exports.deleteKrById = exports.deleteChildrenById = exports.checkChildrenLevel = exports.buildTreeNodes = void 0;

var _cloneDeep = _interopRequireDefault(require("clone-deep"));

var _dayjs = _interopRequireDefault(require("dayjs"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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

var insertSort = function insertSort(arr, item) {
  if (!arr.length) return arr.splice(0, 0, item);
  var modelType = item.modelType;
  var index = arr.length;

  if (modelType == 'kr') {
    index = arr.findIndex(function (item) {
      return item.modelType == 'work';
    });
  }

  if (index == -1) index = arr.length;
  arr.splice(index, 0, item);
};

var toTree = function toTree(data, showkr) {
  var cloneData = (0, _cloneDeep["default"])(data);
  var map = {};
  var res = [];
  cloneData.forEach(function (item) {
    return map[item.id] = item;
  });
  cloneData.forEach(function (item) {
    var modelType = item.modelType,
        data = item.data;
    var parent;

    if (modelType == 'work') {
      parent = showkr ? map[data.parentKrId || data.parentId] : map[data.parentId];
    }

    if (modelType == 'kr') {
      parent = map[data.workId];
    }

    if (parent) {
      if (!parent.children) parent.children = [];
      insertSort(parent.children, item);
    } else {
      insertSort(res, item);
    }
  });
  return res;
};

exports.toTree = toTree;

var checkChildrenLevel = function checkChildrenLevel(item, goalLevel, curLevel) {
  var _item$children = item.children,
      children = _item$children === void 0 ? [] : _item$children;
  if (!children.length) return;

  if (goalLevel == curLevel) {
    item.children = [];
  } else {
    children.forEach(function (child) {
      checkChildrenLevel(child, goalLevel, curLevel + 1);
    });
  }
};

exports.checkChildrenLevel = checkChildrenLevel;

var buildTreeNodes = function buildTreeNodes(nodes, goalLevel, showkr) {
  if (!nodes.length) return []; // 生成树

  var initRoots = toTree(nodes, showkr); // 根据层级控制显示，多余的节点放在根节点上

  for (var i = 0; i < initRoots.length; i++) {
    checkChildrenLevel(initRoots[i], goalLevel, 1);
  }

  return initRoots;
}; // 取出所有返回节点，平铺


exports.buildTreeNodes = buildTreeNodes;

var formatNodes = function formatNodes(res, showkr) {
  var searchIds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  var nodes = [];
  var _res$OkrModel = res.OkrModel,
      OkrModel = _res$OkrModel === void 0 ? [] : _res$OkrModel,
      _res$KrModel = res.KrModel,
      KrModel = _res$KrModel === void 0 ? [] : _res$KrModel;
  OkrModel && uniqueArray(OkrModel, 'workId').forEach(function (item) {
    nodes.push({
      id: item.workId,
      data: item,
      modelType: 'work',
      isSearchRes: searchIds.includes(item.workId)
    });
  });
  showkr && KrModel && uniqueArray(KrModel, 'mileStoneId').forEach(function (item) {
    nodes.push({
      id: item.mileStoneId,
      data: item,
      modelType: 'kr'
    });
  });
  return nodes;
};

exports.formatNodes = formatNodes;

var flatTree = function flatTree(current, elements, showkr) {
  var isParentExpand = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  var parentId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  if (!current) return;
  var id = current.id,
      data = current.data,
      modelType = current.modelType,
      _current$children = current.children,
      children = _current$children === void 0 ? [] : _current$children,
      isSearchRes = current.isSearchRes;

  if (modelType === 'root') {
    elements.push({
      id: modelType + id,
      type: 'RootNode',
      data: data,
      isParent: true,
      position: {
        x: 0,
        y: 0
      }
    });
  } else {
    var isChildExpand = false;

    if (showkr) {
      isChildExpand = children.length > 0;
    } else {
      var childTotal = children.filter(function (item) {
        return item.modelType == 'work';
      }).length;
      var krChildTotal = children.filter(function (item) {
        return item.modelType == 'kr';
      }).reduce(function (count, current) {
        return count += (current.children || []).length;
      }, 0);
      isChildExpand = childTotal + krChildTotal > 0;
    }

    elements.push({
      id: "".concat(modelType).concat(id),
      type: 'ChildNode',
      position: {
        x: 0,
        y: 0
      },
      data: {
        id: id,
        data: data,
        isParentExpand: isParentExpand,
        isChildExpand: isChildExpand,
        parentId: parentId,
        modelType: modelType,
        isSearchRes: isSearchRes
      }
    });
  }

  if (children.length) {
    children.forEach(function (child) {
      if (!child) return;

      if (!showkr && child.modelType === 'kr') {
        if (children.length > 0) {
          children.forEach(function (sub) {
            if (!sub) return;
            elements.push({
              id: "e".concat(modelType).concat(id, "-").concat(sub.modelType).concat(sub.id),
              source: modelType + id,
              target: "kr".concat(sub.id)
            });
            flatTree(sub, elements, showkr, current.modelType != 'root', id);
          });
        }
      } else {
        elements.push({
          id: "e".concat(modelType).concat(id, "-").concat(child.modelType).concat(child.id),
          source: modelType + id,
          target: child.modelType + child.id
        });
        flatTree(child, elements, showkr, current.modelType !== 'root', id);
      }
    });
  }
}; // tree to array


var transToMapData = function transToMapData(root, showkr) {
  var elements = [];
  flatTree(root, elements, showkr);
  return elements;
}; // 删除子节点


exports.transToMapData = transToMapData;

var deleteChildrenById = function deleteChildrenById(node, parentId) {
  if (!node) return;
  var id = node.id,
      _node$children = node.children,
      children = _node$children === void 0 ? [] : _node$children;

  if (parentId == id) {
    node.children = [];
  }

  if (children.length > 0) {
    children.forEach(function (child) {
      child && deleteChildrenById(child, parentId);
    });
  }
};

exports.deleteChildrenById = deleteChildrenById;

var diff = function diff(targetArr, source, sourceArr, sourceIndex) {
  var sourceId = source.id,
      sourceChildren = source.children;
  targetArr.forEach(function (target, index) {
    var id = target.id,
        _target$children = target.children,
        children = _target$children === void 0 ? [] : _target$children;

    if (sourceId == id) {
      targetArr[index] = source;
      sourceArr[sourceIndex] = null;
    } else if (children.length > 0) {
      diff(children, source, sourceArr, sourceIndex);
    }
  });
}; // 对比更新


var diffAndUpdate = function diffAndUpdate(targetArr, sourceArr) {
  sourceArr.map(function (source, index) {
    source && diff(targetArr, source, sourceArr, index);
  });
};

exports.diffAndUpdate = diffAndUpdate;

var findNode = function findNode(tree, targetId) {
  var target;

  var search = function search(node, targetId) {
    if (!node) return;
    var id = node.id,
        _node$children2 = node.children,
        children = _node$children2 === void 0 ? [] : _node$children2;

    if (id == targetId) {
      target = node;
    } else if (children.length > 0) {
      children.forEach(function (child) {
        search(child, targetId);
      });
    }
  };

  search(tree, targetId);
  return target;
};

exports.findNode = findNode;

var deleteKrById = function deleteKrById(targetId, current, currentIndex, parent) {
  var id = current.id,
      _current$children2 = current.children,
      children = _current$children2 === void 0 ? [] : _current$children2;

  if (current && current.id == targetId) {
    if (parent) {
      var _parent$children;

      try {
        parent.data.counter.krTotal = parent.data.counter.krTotal - 1;
      } catch (error) {
        throw error;
      }

      (_parent$children = parent.children).splice.apply(_parent$children, [currentIndex, 1].concat(_toConsumableArray(children)));
    }
  } else if (children.length > 0) {
    children.forEach(function (child, index) {
      deleteKrById(targetId, child, index, current);
    });
  }
};

exports.deleteKrById = deleteKrById;

var uniqueArray = function uniqueArray(arr, id) {
  var obj = {};
  arr = arr.reduce(function (item, next) {
    obj[next[id]] ? '' : obj[next[id]] = true && item.push(next);
    return item;
  }, []);
  return arr;
};

exports.uniqueArray = uniqueArray;