#include "graphicsItem/graphicsBusSectionItem.h"
#include "graphicsItem/itemControlHandle.h"
#include <QPainter>
#include <QStyleOption>

GraphicsBusSectionItem::GraphicsBusSectionItem(const QRect &rect, QGraphicsItem *parent)
    : GraphicsBaseItem(parent), m_dRatioX(1 / 10.0), m_dRatioY(1 / 10.0)
{
    m_pen = QPen(Qt::blue, 2);
    m_brush = QBrush(QColor(100, 150, 255, 50));
    m_lastBoudingRect = rect;
    m_boundingRect = rect;
    m_dWidth = rect.width();
    m_dHeight = rect.height();
}

GraphicsBusSectionItem::~GraphicsBusSectionItem()
{
}

QPainterPath GraphicsBusSectionItem::shape()
{
    QPainterPath path;
    path.addRect(m_boundingRect);
    return path;
}

void GraphicsBusSectionItem::updateHandles()
{
    GraphicsBaseItem::updateHandles();
}

void GraphicsBusSectionItem::updateCoordinate()
{
    if (!parentItem())
    {
        QPointF pt1, pt2, delta;
        pt1 = mapToScene(QPointF(0, 0));
        pt2 = mapToScene(m_boundingRect.center());
        delta = pt1 - pt2;

        prepareGeometryChange();
        m_boundingRect = QRectF(-m_dWidth / 2, -m_dHeight / 2, m_dWidth, m_dHeight);
        moveBy(-delta.x(), -delta.y());
        updateHandles();
    }

    m_lastBoudingRect = m_boundingRect;
}

void GraphicsBusSectionItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
    painter->setPen(m_pen);
    painter->setBrush(m_brush);
    painter->drawRect(m_boundingRect);

    // 绘制Bus Section标签
    painter->setPen(Qt::blue);
    painter->setFont(QFont("Arial", 10, QFont::Bold));
    painter->drawText(m_boundingRect, Qt::AlignCenter, "BUS");

    if (option->state & QStyle::State_Selected)
    {
        int nPenWidth = 1;
        painter->setPen(QPen(QColor(70, 70, 70), nPenWidth, Qt::DashLine));
        painter->setBrush(Qt::NoBrush);
        painter->drawRect(m_boundingRect_selected);

        // 绘制变换原点
        QPointF originPoint = transformOriginPoint();
        painter->setBrush(Qt::red);
        painter->drawEllipse(originPoint, 4, 4);
    }
}

void GraphicsBusSectionItem::resize(int nHandle, double dSX, double dSY, const QPointF& basePoint)
{
    switch (nHandle)
    {
    case H_left:
    case H_right:
        dSY = 1;
        break;
    case H_top:
    case H_bottom:
        dSX = 1;
        break;
    default:
        break;
    }

    QTransform trans;
    trans.translate(basePoint.x(), basePoint.y());
    trans.scale(dSX, dSY);
    trans.translate(-basePoint.x(), -basePoint.y());

    prepareGeometryChange();
    m_boundingRect = trans.mapRect(m_lastBoudingRect);
    m_dWidth = m_boundingRect.width();
    m_dHeight = m_boundingRect.height();
    update();
}

void GraphicsBusSectionItem::move(const QPointF& delta)
{
    moveBy(delta.x(), delta.y());
}

void GraphicsBusSectionItem::editShape(int nHandle, const QPointF& point)
{
    // Bus Section没有特殊的编辑点
}

