import { Vector2, Vector3 } from 'three';

export const getNearKeyPoint = (keyPoints: THREE.Vec2[], point: THREE.Vec2) => {
  let nearPoint;
  let diff = Infinity;
  let tmpPoint, tmpDiff;
  for (let i = 0; i < keyPoints.length; i++) {
    tmpPoint = keyPoints[i];
    tmpDiff = Math.abs(tmpPoint.x - point.x) + Math.abs(tmpPoint.y - point.y);
    if (tmpDiff < diff) {
      diff = tmpDiff;
      nearPoint = tmpPoint;
    }
  }
  return nearPoint;
};

/**
 * @desc 计算最佳线路时，需要转换数据
 */
export function standardKeyPointsChanger(path: any[]) {
  // 转换 v1 的邻近点规则
  const keyPoints: any = [];

  const map: Record<string, any> = {};
  for (const item of path) {
    const node1 = map[JSON.stringify(item.begin)];
    const node2 = map[JSON.stringify(item.end)];

    if (!node1) {
      // 初始化
      map[JSON.stringify(item.begin)] = {
        id: JSON.stringify(item.begin),
        x: item.begin[0],
        y: item.begin[1],
        neighbours: [
          {
            id: JSON.stringify(item.end),
            d: item.distance
          }
        ]
      };
    } else {
      // 继续添加 neighbours
      node1.neighbours.push({
        id: JSON.stringify(item.end),
        d: item.distance
      });
    }

    if (!node2) {
      // 初始化
      map[JSON.stringify(item.end)] = {
        id: JSON.stringify(item.end),
        x: item.end[0],
        y: item.end[1],
        neighbours: [
          {
            id: JSON.stringify(item.begin),
            d: item.distance
          }
        ]
      };
    } else {
      // 继续添加 neighbours
      node2.neighbours.push({
        id: JSON.stringify(item.begin),
        d: item.distance
      });
    }
  }
  for (const key of Object.keys(map)) {
    keyPoints.push(map[key]);
  }
  return keyPoints;
}

/**
 * @desc 截取精度
 */
export function myTruncate(point: number[], precision = 3) {
  const [x, y] = point;
  if (isNaN(+x) || isNaN(+y)) {
    return [];
  }
  // 精度缩小
  return [
    parseFloat((+x).toFixed(precision)),
    parseFloat((+y).toFixed(precision))
  ];
}

export function getDistance(p1: Vector3 | Vector2, p2: Vector3 | Vector2) {
  return Math.abs(
    Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2))
  );
}

/**
 * @desc 把字符串转换成 float
 */
export function parsePath(path: any) {
  const _parseArr = (arr: string[]) => {
    return [parseFloat(arr[0]), parseFloat(arr[1])];
  };
  for (const item of path) {
    Object.assign(item, {
      begin: _parseArr(item.begin),
      end: _parseArr(item.end),
      distance: parseFloat(item.distance)
    });
  }
  return path;
}
