export function drawCloudWave(path, start, end, arcRadius, density) {
  const dx = end.x - start.x;
  const dy = end.y - start.y;
  const length = Math.sqrt(dx * dx + dy * dy);

  if (length === 0) return;

  // 计算单位向量
  const unitX = dx / length;
  const unitY = dy / length;

  // 计算垂直向量
  const perpX = -unitY;
  const perpY = unitX;

  // 中点
  const midX = (start.x + end.x) / 2;
  const midY = (start.y + end.y) / 2;

  // 最大弧度点（向外凸）
  const amplitude = arcRadius * density;
  const peakX = midX - perpX * amplitude; // 向外凸
  const peakY = midY - perpY * amplitude;

  // 使用三次贝塞尔曲线创建平滑的圆弧效果
  // 控制点稍微向内收缩，创建更自然的S形曲线
  const control1X = start.x + dx * 0.25;
  const control1Y = start.y + dy * 0.25;
  const control2X = end.x - dx * 0.25;
  const control2Y = end.y - dy * 0.25;

  // 添加弧度偏移
  const arcOffsetX = -perpX * amplitude * 0.3;
  const arcOffsetY = -perpY * amplitude * 0.3;

  path.bezierCurveTo(
    control1X + arcOffsetX,
    control1Y + arcOffsetY,
    control2X + arcOffsetX,
    control2Y + arcOffsetY,
    end.x,
    end.y
  );
}

// // 绘制云线路径
export function drawCloudPath(path, vertices, config, close) {
  const { radius, density } = config;

  if (vertices.length < 3) return;

  // 从第一个顶点开始
  path.moveTo(vertices[0].x, vertices[0].y);
  let n = vertices.length;
  // 如果close为false则不闭合
  if (!close) n--;
  // 为每条边绘制云线效果
  for (let i = 0; i < n; i++) {
    const currentVertex = vertices[i];
    const nextVertex = vertices[(i + 1) % vertices.length];

    // 在当前边绘制云线效果
    drawCloudWave(path, currentVertex, nextVertex, radius, density);
  }

  // if(close) path.closePath();
  path.closePath();
  path.stroke();
  // path.restore()
}

// // 基于原始顶点扩充成更多点
export function expansionHexagonVertices(originalVertices, frequency) {
  const expansionVertices = [];
  let n = originalVertices.length;
  for (let i = 0; i < n; i++) {
    const current = originalVertices[i];
    const next = originalVertices[(i + 1) % originalVertices.length];

    const len = Math.floor(
      Math.sqrt((next.x - current.x) ** 2 + (next.y - current.y) ** 2) / 1 / 8
    );

    for (let j = 0; j < len; j++) {
      const ratio = len === 1 ? 0 : j / (len - 1); // 0 到 1 之间
      const expansionPoint = {
        x: current.x + (next.x - current.x) * ratio,
        y: current.y + (next.y - current.y) * ratio,
      };

      expansionVertices.push(expansionPoint);
    }
  }

  return expansionVertices;
}

// 绘制云线
export function drawCloudLines(path, vertices) {
  const frequency = 8;
  const expansionVertices = expansionHexagonVertices(vertices, frequency);
  // 云线配置
  const config = {
    radius: 15,
    outward: true,
    density: 0.8,
  };

  drawCloudPath(path, expansionVertices, config);
}
