#include "realtimedatawidget.h"
#include <QPainter>
#include <QDateTime>

RealTimeDataWidget::RealTimeDataWidget(QWidget *parent) : QWidget(parent) {
    // 创建 QCustomPlot 对象
    plot = new QCustomPlot(this);

    // 将 QCustomPlot 添加到布局中
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(plot);
    setLayout(layout);

    // 设置 QCustomPlot 的布局
    plot->plotLayout()->clear(); // 清空默认布局
    plot->plotLayout()->addElement(0, 0, new QCPAxisRect(plot)); // 添加坐标轴矩形
    plot->xAxis->setLabel("Time"); // 设置 x 轴标签
    plot->yAxis->setLabel("Value"); // 设置 y 轴标签

    // 设置曲线图的样式
    plot->addGraph();
    plot->graph(0)->setPen(QPen(Qt::blue)); // 设置曲线颜色为蓝色

    // 初始化坐标轴范围
    plot->xAxis->setRange(0, 10);
    plot->yAxis->setRange(0, 1);

    // 进行自动适应范围
    plot->rescaleAxes();
}

void RealTimeDataWidget::addDataPoint(double x, double y) {
    // 添加新的数据点
    xData.append(x);
    yData.append(y);

    // 更新数据点数目,确保不超过 60 个
    if (xData.size() > 60) {
        // 如果超过 60 个数据点,移除最旧的数据点
        xData.removeFirst();
        yData.removeFirst();
    }

    // 设置 x 轴范围的动态增长
    double minVisibleX = qMax(0.0, xData.first()); // 最小可见 x 值
    double maxVisibleX = xData.last(); // 最大可见 x 值

    // 将数据添加到曲线图中
    plot->graph(0)->setData(xData, yData);

    // 设置 x 轴范围
    plot->xAxis->setRange(minVisibleX, maxVisibleX);

    // 更新坐标轴范围
    plot->rescaleAxes();

    // 重新绘制图表
    plot->replot();
}

void RealTimeDataWidget::setYAxisLabel(const QString &label) {
    if (plot) {
        plot->yAxis->setLabel(label);
    }
}