// 删除无用字段
const deletsNoUseKey = (node) => {
  delete node.id;
  delete node.preNodeId;
  delete node.x;
  delete node.y;
  delete node.style;
  delete node.size;
  delete node.depth;
  delete node.selected;
  delete node.anchorPoints;
  delete node.contentHover;
  return node;
};

// 给节点添加结构id
function setNodeIdByList(nodeList, preNodeId, nodeMap) {
  if (!Array.isArray(nodeList) || nodeList.length <= 0) return;
  for (let i = 0; i < nodeList.length; i++) {
    const node = nodeList[i];
    // 把节点存入 nodeMap
    nodeMap.set(String(node.id), node);
    node.nodeId = preNodeId ? preNodeId + "-" + i : i + "";
    setNodeIdByList(node.children, String(node.nodeId), nodeMap);
  }
}

// 修改节点的data数据中指向节点
const setNextNodeId = (node, nodeMap) => {
  const nodeData = node.data;
  // 修改选项的对应节点
  if (node.nodeType === "root-node" || node.nodeType === "plot-node") {
    const optionsList = nodeData.optionsList || [];
    optionsList.forEach((optionItem) => {
      const nextNode = nodeMap.get(optionItem.nodeId) || {};
      optionItem.nextNodeId = nextNode.nodeId;
    });
  } else if (node.nodeType === "jumpNodeId") {
    const nextNode = nodeMap.get(node.jumpNodeId) || {};
    node.nextNodeId = nextNode.nodeId;
  }
};

// 对节点的自定义数据 data 进行修改
function transformNodeDataByList(nodeList, nodeMap) {
  if (!Array.isArray(nodeList) || nodeList.length <= 0) return;
  for (let i = 0; i < nodeList.length; i++) {
    const node = nodeList[i];
    node.nodeType = node.type;
    node.data.nodeName = node.data.name;
    setNextNodeId(node, nodeMap);
    transformNodeDataByList(node.children, nodeMap);
  }
}

// 修改数据
export const transformGraphdata = (graphData) => {
  // 记录id和节点的映射
  let nodeMap = new Map();
  // 先给所有数据添加 nodeId
  setNodeIdByList([graphData], "", nodeMap);
  // 处理节点的 data 数据
  transformNodeDataByList([graphData], nodeMap);
  // nodeMap 里面有所有的节点，在这里把所有节点的无用字段去除一下
  nodeMap.forEach((node) => {
    deletsNoUseKey(node);
  });
  return graphData;
};

export const transfromReturnGraphdata = (graphData) => {
  // 记录id和节点的映射
  let nodeMap = new Map();
  // 先给所有数据添加 nodeId
  setNodeIdByList([graphData], "", nodeMap);
  // 处理节点的 data 数据
  transformReturnNodeDataByList([graphData], nodeMap);
  return graphData;
};

// 对节点的自定义数据 data 进行修改
function transformReturnNodeDataByList(nodeList, nodeMap) {
  if (!Array.isArray(nodeList) || nodeList.length <= 0) return;
  for (let i = 0; i < nodeList.length; i++) {
    const node = nodeList[i];
    node.id = String(node.id);
    node.type = node.nodeType;
    node.data.name = node.data.nodeName;
    setNextNodeId(node, nodeMap);
    transformReturnNodeDataByList(node.children, nodeMap);
  }
}
