import 'package:flutter/material.dart';

class EcgPainterForAll extends CustomPainter {
  /// 分为新数据和历史数据
  final List<int> allPoints;

  /// 横坐标数据量（横轴一共多少个点） 30s * 125 = 3750
  final int xDataCount = 3750;

  final int yGridNumsPerMv; // 多少格是一毫伏特

  /// 纵坐标最大值
  final double yMax;

  EcgPainterForAll({
    required this.allPoints,
    required this.yMax,
    this.yGridNumsPerMv = 5,
  });

  @override
  void paint(Canvas canvas, Size size) {
    if (allPoints.isNotEmpty) {
      drawPoints(canvas, size, allPoints);
    }
    if (allPoints.length < xDataCount) {
      /// 绘制一根x轴直线，补全剩余数据
      final paint = Paint()
        ..color = Colors.green
        ..style = PaintingStyle.stroke
        ..strokeWidth = 3.0;
      final double xGridSize = size.width / xDataCount;
      final startX = allPoints.length * xGridSize;
      final startY = size.height / 2;
      final endX = size.width;
      final endY = size.height / 2;
      canvas.drawLine(Offset(startX, startY), Offset(endX, endY), paint);
    }
  }

  void drawPoints(
    Canvas canvas,
    Size size,
    List<int> points, {
    int offset = 0,
  }) {
    final paint = Paint()
      ..color = Colors.green
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3.0;

    final double xGridSize = size.width / xDataCount;
    final double yScale = size.height / 2 / yMax;

    final double yCenter = size.height / 2;

    final path = Path();
    for (int i = offset; i < points.length; i++) {
      final offsetX = i * xGridSize;
      final offsetY = -points[i] * yScale + yCenter;
      if (i == offset) {
        path.moveTo(offsetX, offsetY);
      } else {
        // 利用 cubicTo 画出平滑的曲线
        // final double preOffsetX = (i - 1) * xGridSize;
        // final double preOffsetY = -points[i - 1] * yScale + yCenter;
        // final double c1x = preOffsetX + (offsetX - preOffsetX) / 2;
        // final double c1y = preOffsetY;
        // final double c2x = preOffsetX + (offsetX - preOffsetX) / 2;
        // final double c2y = offsetY;
        // path.cubicTo(c1x, c1y, c2x, c2y, offsetX, offsetY);
        path.lineTo(offsetX, offsetY);
      }
    }
    canvas.drawPath(path, paint);
  }

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