import 'package:flutter/material.dart';

/// 绘制背景方格
/// 入参：xGridNums X轴方格数
/// 入参：yGridNums y轴方格数
class GridBackgroundPainter extends CustomPainter {
  final int xGridNums;
  List<String> mLeadNames = [
    "I",
    "V1",
    "II",
    "V2",
    "III",
    "V3",
    "aVR",
    "V4",
    "aVL",
    "V5",
    "aVF",
    "V6"
  ];

  GridBackgroundPainter(this.xGridNums);

  @override
  void paint(Canvas canvas, Size size) {
    final gridPaint = Paint()
      ..color = Colors.grey.withOpacity(0.5)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0;

    final double xGridSize = size.width / xGridNums;
    final double yGridSize = xGridSize;
    final int yGridNums = (size.height / yGridSize).ceil();

    final double centerY = size.height / 2;

    for (int i = 0; i < xGridNums; i++) {
      final offsetX = i * xGridSize;
      canvas.drawLine(
        Offset(offsetX, 0),
        Offset(offsetX, size.height),
        gridPaint,
      );
    }

    for (int i = 0; i < yGridNums / 2; i++) {
      final offsetY = (i * yGridSize);
      canvas.drawLine(
        Offset(0, centerY + offsetY),
        Offset(size.width, centerY + offsetY),
        gridPaint,
      );
      canvas.drawLine(
        Offset(0, centerY - offsetY),
        Offset(size.width, centerY - offsetY),
        gridPaint,
      );
    }

    canvas.drawLine(
      Offset(size.width - 0.5, 0),
      Offset(size.width - 0.5, size.height),
      gridPaint,
    );

    for (int i = 0; i < 12; i++) {
      /// 绘制两根中心线
      final centerLinePaint = Paint()
        ..color = const Color.fromARGB(255, 1, 4, 148)
        ..style = PaintingStyle.stroke
        ..strokeWidth = 1.0;

      final row = i ~/ 2;
      final column = i % 2;

      // canvas.drawLine(
      //   Offset(column * size.width / 2, (size.height * row / 6)),
      //   Offset((column + 1) * size.width / 2, (size.height * row / 6)),
      //   centerLinePaint,
      // );

      // canvas.drawLine(
      //   Offset(size.width / 2, 0),
      //   Offset(size.width / 2, size.height),
      //   centerLinePaint,
      // );

      final textPainter = TextPainter(
        text: TextSpan(
          text: mLeadNames[i],
          style: TextStyle(
            height: 1,
            color: const Color.fromARGB(255, 99, 99, 99),
            fontSize: 25,
            background: Paint()..color = Colors.white.withOpacity(0.5),
          ),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset((column) * size.width / 2 + 10, (size.height * row / 6) + 10),
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }
}
