import _ from "lodash";

// 求两点间的距离
export function getDis(s, t) {
  return Math.sqrt((s.x - t.x) * (s.x - t.x) + (s.y - t.y) * (s.y - t.y));
}

export function getAngle(source, target, _dis) {
  let r;
  if (target.x > source.x) {
    if (target.y > source.y) {
      r = Math.asin((target.y - source.y) / _dis);
    } else {
      r = Math.asin((source.y - target.y) / _dis);
      r = -r;
    }
  } else {
    if (target.y > source.y) {
      r = Math.asin((target.y - source.y) / _dis);
      r = Math.PI - r;
    } else {
      r = Math.asin((source.y - target.y) / _dis);
      r -= Math.PI;
    }
  }
  return r * (180 / Math.PI);
}

// 求元素移动到目标位置所需要的 transform 属性值
export function getTransform(source, target, _dis) {
  let r = getAngle(source, target, _dis);
  // return `translate(${source.x},${source.y})`
  return `translate(${source.x},${source.y}) rotate(${r})`;
}

export function findRepeatRelation(edges, relation) {
  return edges.filter(v => {
    const mapSrouce = typeof v.source === "object" ? v.source.id : v.source;
    const mapTarget = typeof v.target === "object" ? v.target.id : v.target;
    const currentSource = typeof relation.source === "object" ? relation.source.id : relation.source;
    const currentTarget = typeof relation.target === "object" ? relation.target.id : relation.target;

    const flag1 = mapSrouce === currentSource && mapTarget === currentTarget;
    const flag2 = mapSrouce === currentTarget && mapTarget === currentSource;
    return flag1 || flag2;
  });
}

export function formatLinks(links) {
  links.forEach(function(link) {
    const sameAll = findRepeatRelation(links, { source: link.source, target: link.target });
    sameAll.forEach(function(s, i) {
      s.sameIndex = i + 1;
      s.sameTotal = sameAll.length;
      s.sameUneven = s.sameIndex % 2 !== 0;
      s.sameMiddleLink = s.sameUneven === true && s.sameTotal === s.sameIndex;
      s.sameLowerHalf = s.sameIndex <= s.sameTotal / 2;
    });
  });
  return links;
}

export function computedNewNodes(nodes, rawNodes) {
  const newNodes = [];
  rawNodes.forEach(rawNode => {
    const node = nodes.find(v => v.id === rawNode.id);
    if (node) {
      newNodes.push(node);
    } else {
      newNodes.push(_.cloneDeep(rawNode));
    }
  });
  return newNodes;
}

export function computedNewLinks(links, rawLinks) {
  const newLinks = [];
  rawLinks.forEach(rawLink => {
    const link = links.find(v => v.linkId === rawLink.linkId);
    if (link) {
      newLinks.push(link);
    } else {
      newLinks.push(_.cloneDeep(rawLink));
    }
  });
  return newLinks;
}
