#include "WaferGraphicsView.h"
#include <QDebug>
#include <QScrollBar>

WaferGraphicsView::WaferGraphicsView(QGraphicsScene* scene, QWidget* parent)
    : QGraphicsView(scene, parent), selecting(false), selectionRect(nullptr), scaleFactor(1.0) {
    setRenderHint(QPainter::Antialiasing);
    // setDragMode(QGraphicsView::ScrollHandDrag); // 支持拖动视图
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse); // 缩放时以鼠标为中心
}

void WaferGraphicsView::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        // 清空选中的 DieItem
        for (auto& item : selectedItemsMap) {
            DieItem* die = dynamic_cast<DieItem*>(item);
            if (die) {
                die->setSelected(false); // 取消选中状态
            }
        }
        selectedItemsMap.clear();

        // 获取点击位置的 DieItem
        QGraphicsItem* item = itemAt(event->pos());
        DieItem* die = dynamic_cast<DieItem*>(item);
        if (die) {
            // 将 DieItem 添加到 map 中
            selectedItemsMap.insert(qMakePair(die->getRow(), die->getCol()), die);
            die->setSelected(true); // 设置选中状态
        }

        setCursor(Qt::OpenHandCursor);  // 按下时设置为小手
        selecting = true;
        lastPos = event->pos();  // 记录鼠标位置
    } else if (event->button() == Qt::RightButton) {
        // 开始框选
        selecting = true;
        selectionStart = mapToScene(event->pos());
        isDragging = false;
        if (!selectionRect) {
            selectionRect = new QGraphicsRectItem();
            selectionRect->setPen(QPen(Qt::NoPen));
            selectionRect->setBrush(QBrush(QColor(0, 0, 255, 50))); // 半透明蓝色
            scene()->addItem(selectionRect);
        }
        selectionRect->setRect(QRectF(selectionStart, QSizeF()));
    }
    QGraphicsView::mousePressEvent(event);
}

void WaferGraphicsView::mouseMoveEvent(QMouseEvent* event) {
    if (selecting && selectionRect) {
        QPointF currentPos = mapToScene(event->pos());
        selectionRect->setRect(QRectF(selectionStart, currentPos).normalized());
        isDragging = true;
    } else if (selecting) {
        // 计算鼠标当前位置与上次位置的差值
        QPointF delta = event->pos() - lastPos;
        // 平移视图
        horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x());
        verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y());
        lastPos = event->pos();  // 更新鼠标位置
    }
    QGraphicsView::mouseMoveEvent(event);
}

void WaferGraphicsView::mouseReleaseEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton) {
        setCursor(Qt::ArrowCursor);  // 松开时恢复为箭头
        selecting = false;
    } else if (event->button() == Qt::RightButton && selecting) {
        selecting = false;
        if (selectionRect) {
            QRectF selectedArea = selectionRect->rect();
            scene()->removeItem(selectionRect);
            delete selectionRect;
            selectionRect = nullptr;

            QList<QGraphicsItem*> items = scene()->items(selectedArea, Qt::IntersectsItemShape);
            for (QGraphicsItem* item : items) {
                DieItem* die = dynamic_cast<DieItem*>(item);
                if (die) {
                    // 将 DieItem 添加到 map 中
                    selectedItemsMap.insert(qMakePair(die->getRow(), die->getCol()), die);
                    die->setSelected(true); // 设置选中状态
                }
            }
        }
        // 如果没有进行拖动，则弹出右键菜单
        if (!isDragging) {
            QMenu menu;
            QAction* action1 = menu.addAction("菜单项 1");
            QAction* action2 = menu.addAction("菜单项 2");

            connect(action1, &QAction::triggered, this, &WaferGraphicsView::handleAction1);
            connect(action2, &QAction::triggered, this, &WaferGraphicsView::handleAction2);

            menu.exec(event->globalPos());
        }
    }
    QGraphicsView::mouseReleaseEvent(event);
}

void WaferGraphicsView::wheelEvent(QWheelEvent* event) {
    if (event->orientation() == Qt::Vertical) {
        event->ignore(); // 忽略竖直滚轮事件（即禁用滚动条滑动）
        return;
    }
    event->accept();
}

// 处理右键菜单的动作
void WaferGraphicsView::handleAction1() {
    qDebug() << "菜单项 1 被点击";
}

void WaferGraphicsView::handleAction2() {
    qDebug() << "菜单项 2 被点击";
}
