#include "QGraphicsItemArrow.h"
#include<QPainter>

QGraphicsItemArrow::QGraphicsItemArrow(QGraphicsItem* startItem, QGraphicsItem* endItem)
{
    m_startItem = startItem;
    m_endItem = endItem;
}

QRectF QGraphicsItemArrow::boundingRect() const
{
    QPointF startPoint = m_startItem->sceneBoundingRect().center();
    QPointF endPoint = m_endItem->sceneBoundingRect().center();
    endPoint.setY(endPoint.y() - m_endItem->sceneBoundingRect().height() / 2);
    startPoint.setY(startPoint.y() + m_startItem->sceneBoundingRect().height() / 2);
    // 计算箭头的边界框
    qreal extra = 20; // 确保箭头的尖端和形状完全在边界框内
    QRectF rect = QRectF(startPoint, endPoint).normalized();
    rect.adjust(-extra, -extra, extra, extra);
    return rect;
}

void QGraphicsItemArrow::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget /*= Q_NULLPTR*/)
{
    QPointF startPoint = m_startItem->sceneBoundingRect().center();
    QPointF endPoint = m_endItem->sceneBoundingRect().center();
    endPoint.setY(endPoint.y() - m_endItem->sceneBoundingRect().height() / 2);
    startPoint.setY(startPoint.y() + m_startItem->sceneBoundingRect().height() / 2);
    // 设置画笔
    //QPen pen(Qt::black); // 可以根据需要修改颜色
    //painter->setPen(pen);

    //// 获取起始和结束点


    //// 绘制线条
    //painter->drawLine(startPoint, endPoint);

    ////不加入可能会影响刷新
    //setLine(startPoint.x(), startPoint.y(), endPoint.x(), endPoint.y());

    //// 计算箭头头部的位置和方向
    //double angle = std::atan2(endPoint.y() - startPoint.y(), endPoint.x() - startPoint.x());
    //QPointF arrowHead1 = endPoint - QPointF(sin(angle + M_PI / 6) * 10, cos(angle + M_PI / 6) * 10);
    //QPointF arrowHead2 = endPoint - QPointF(sin(angle - M_PI / 6) * 10, cos(angle - M_PI / 6) * 10);

    //// 绘制箭头头部
    //painter->drawLine(endPoint, arrowHead1);
    //painter->drawLine(endPoint, arrowHead2);


    Q_UNUSED(option);
    Q_UNUSED(widget);

    QPen pen(Qt::black);
    pen.setWidth(2);
    painter->setPen(pen);

    QLineF line(startPoint, endPoint);
    if (line.length() == 0.0)
        return;

    double angle = std::atan2(-line.dy(), line.dx());
    QLineF arrowHead[3];
    arrowHead[0] = QLineF(endPoint, endPoint - QPointF(sin(angle + M_PI / 3) * 20, cos(angle + M_PI / 3) * 20));
    arrowHead[1] = QLineF(endPoint, endPoint - QPointF(sin(angle + M_PI - M_PI / 3) * 20, cos(angle + M_PI - M_PI / 3) * 20));
    arrowHead[2] = QLineF(endPoint, endPoint - QPointF(sin(angle + M_PI) * 20, cos(angle + M_PI) * 20));

    painter->drawLine(line);
    painter->drawLine(arrowHead[0]);
    painter->drawLine(arrowHead[1]);
}
