#include "util/creatingSelector.h"
#include "graphicsItem/graphicsRectItem.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>

CreatingSelector::CreatingSelector(QObject *parent)
    : BaseSelector(parent)
{
    m_type = ST_cerating;
    m_pCreatingItem = nullptr;
    m_scalBasePoint = QPointF();
}
CreatingSelector::~CreatingSelector()
{

}

void CreatingSelector::mousePressEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    if (event->button() != Qt::LeftButton)
        return;

    scene->clearSelection();
    ms_ptMouseDown = event->scenePos();
    ms_ptMouseLast = event->scenePos();

    switch (m_creatingType) {
    case GIT_rect:
        m_pCreatingItem = new GraphicsRectItem(QRect(1, 1, 1, 1));
        break;
    case GIT_roundRect:
        m_pCreatingItem = new GraphicsRectItem(QRect(1, 1, 1, 1), true);
        break;
    default:
        break;
    }

    ms_ptMouseDown += QPoint(2, 2);
    m_pCreatingItem->setPos(event->scenePos());
    scene->addItem(m_pCreatingItem);
    m_pCreatingItem->setSelected(true);

    ms_nDragHandle = H_rightBottom;
    setCursor(scene, Qt::CrossCursor);
}

void CreatingSelector::mouseMoveEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    ms_ptMouseLast = event->scenePos();

    if (m_pCreatingItem)
    {

        if(m_scalBasePoint.isNull()) //基准点不能采用临时变量，因为handle的坐标也在不断变化，计算会出现问题
        {
            m_scalBasePoint = m_pCreatingItem->getSymmetricPointPos(ms_nDragHandle);
            if(m_scalBasePoint.x() == 0)
                m_scalBasePoint.setX(1);
            if(m_scalBasePoint.y() == 0)
                m_scalBasePoint.setY(1);
        }

        //计算缩放倍数
        QPointF iniDelta = m_pCreatingItem->mapFromScene(ms_ptMouseDown) - m_scalBasePoint;
        QPointF lastDelta = m_pCreatingItem->mapFromScene(ms_ptMouseLast) - m_scalBasePoint;
        double sx = lastDelta.x() / iniDelta.x();
        double sy = lastDelta.y() / iniDelta.y();

        m_pCreatingItem->resize(ms_nDragHandle, sx, sy, m_scalBasePoint);
    }
}

void CreatingSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, DesignerScene* scene)
{
    if (event->scenePos() == (ms_ptMouseDown - QPoint(2, 2))) //最小拖动范围
    {
        if(m_pCreatingItem)
        {
            m_pCreatingItem->setSelected(false);
            scene->removeItem(m_pCreatingItem);
            delete m_pCreatingItem;
        }
    }
    else if (m_pCreatingItem && ms_ptMouseLast != ms_ptMouseDown)
    {
        m_pCreatingItem->updateCoordinate();
        emit scene->signalAddItem(m_pCreatingItem);
    }

    ms_nDragHandle = H_none;
    m_pCreatingItem = nullptr;
    m_scalBasePoint = QPointF();
    setCursor(scene, Qt::ArrowCursor);
    emit setWorkingSelector(ST_base);
}
