#ifndef CURVEEDITOR_H
#define CURVEEDITOR_H

#include <QWidget>
#include <QVector>
#include <QPointF>

/**
 * @brief 曲线节点
 */
struct CurvePoint
{
    /**
     * @brief X坐标，用于表示温度
     */
    qreal x;
    
    /**
     * @brief Y坐标，用于表示风扇转速
     */
    qreal y;
};

/**
 * @brief 曲线编辑器
 */
class CurveEditor : public QWidget
{
    Q_OBJECT
public:
    explicit CurveEditor(QWidget *parent = nullptr);
    
    /**
     * @brief 设置大小
     */
    void setSize(int width, int height);

    /**
     * @brief 设置曲线点
     */
    void setPoints(const QVector<CurvePoint> &points);

    /**
     * @brief 获取当前选中的曲线点
     */
    QVector<CurvePoint> getCurrentPoints() const;

    /**
     * @brief 设置网格宽度
     */
    void setGridWidth(int width);

    /**
     * @brief 设置网格高度
     */
    void setGridHeight(int height);

    /**
     * @brief 设置X轴刻度标签
     */
    void setXTickTag(std::string tag);

    /**
     * @brief 设置Y轴刻度标签
     */
    void setYTickTag(std::string tag);

    /**
     * @brief 设置Y轴刻度步长
     */
    void setYTickStep(int step);

    /**
     * @brief 设置X轴刻度步长
     */
    void setXTickStep(int step);

    /**
     * @brief 设置Y轴刻度范围
     */
    void setYTickRange(int min, int max);

    /**
     * @brief 设置X轴刻度范围
     */
    void setXTickRange(int min, int max);

signals:
    void curveChanged(const QVector<CurvePoint> &points);
    void curveReleased();

protected:
    void paintEvent(QPaintEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;

private:
    bool isDragging() const { return m_dragIndex >= 0; }
    int findPointAt(const QPointF &pos) const;
    void adjustPointPosition(int index);
    void validateCurve();

    QPointF mapToContent(qreal xPercent, qreal yPercent);
    int findPointAt(const QPointF &pos);

    QVector<CurvePoint> m_points;
    QVector<CurvePoint> m_originalPoints;
    int m_dragIndex = -1;
    QPointF m_dragStartPos;
    QRect m_contentRect;
    static constexpr int POINT_RADIUS = 6;
    
    int gridWidth;

    int gridHeight;

    int xTickMin;
    int xTickMax;
    int yTickMin;
    int yTickMax;

    std::string xTickTag;
    std::string yTickTag;

    /**
     * @brief 网格X轴刻度步长
     */
    int xTickStep;

    /**
     * @brief 网格Y轴刻度步长
     */
    int yTickStep;
};

#endif // CURVEEDITOR_H