/**
 * 绘制网格
 * @param color 网格颜色
 * @param w canvas画布宽
 * @param h canvas画布高
 * @param pen canvas 画笔
 * @param status 默认true，保存画布状态
 */
export function drawGrid(
  color: string,
  w: number,
  h: number,
  pen: any,
  status = true
) {
  const step = 100;
  const w_l = w / step;
  const h_l = h / step;

  if (status) {
    pen.save();
  }
  // 横着的线
  for (let i = 0; i <= h_l; i++) {
    pen.beginPath();
    pen.strokeStyle = color;
    pen.moveTo(0, i * step);
    pen.lineTo(w, i * step);
    pen.stroke();
  }
  // 竖着的线
  for (let i = 0; i <= w_l; i++) {
    pen.beginPath();
    pen.moveTo(i * step, 0);
    pen.lineTo(i * step, h);
    pen.stroke();
  }
  if (status) {
    pen.restore();
  }
}

/**
 * canvas旋转中心偏移值
 * @param width canvas宽
 * @param center 中心坐标点 center:{x:100,y:100}
 * @param arc 旋转的弧度值
 */
export function rotateOriginOffset(
  width: number,
  center: { x: number; y: number },
  arc: any
) {
  const r1 = width - center.x;
  const xRes1 = Math.cos(arc) * r1;
  const yRes1 = Math.sin(arc) * r1;
  const x1 = center.x + xRes1;
  const y1 = center.y + yRes1;

  const x0 = width;
  const y0 = center.y;
  const c0 = Math.sqrt(Math.pow(x0, 2) + Math.pow(y0, 2));
  const arc0 = Math.atan2(y0, x0);
  const arc_0 = arc0 + arc;
  const y2 = Math.sin(arc_0) * c0;
  const x2 = y2 / Math.tan(arc_0);

  const xLength = x1 - x2;
  const yLength = y1 - y2;
  return {
    x: xLength,
    y: yLength,
  };
}

/**
 * 角度值转弧度值
 * @param degree 角度值
 */
export function toArc(degree: number) {
  return (degree * Math.PI) / 180;
}
