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

WaferGraphicsView::WaferGraphicsView(QGraphicsScene* scene, QWidget* parent)
    : QGraphicsView(scene, parent), selecting(false), selectionRect(nullptr), scaleFactor(1.0) {
    setRenderHint(QPainter::Antialiasing);
    setDragMode(QGraphicsView::ScrollHandDrag); // 支持拖动视图
}

// void WaferGraphicsView::mousePressEvent(QMouseEvent* event) {
//     if (event->button() == Qt::LeftButton) {
//         // 开始框选
//         selecting = true;
//         selectionStart = mapToScene(event->pos());
//         if (!selectionRect) {
//             selectionRect = new QGraphicsRectItem();
//             selectionRect->setPen(QPen(Qt::DashLine));
//             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());
//     }
//     QGraphicsView::mouseMoveEvent(event);
// }

// void WaferGraphicsView::mouseReleaseEvent(QMouseEvent* event) {
//     if (event->button() == Qt::LeftButton && selecting) {
//         selecting = false;
//         if (selectionRect) {
//             QRectF selectedArea = selectionRect->rect();
//             scene()->removeItem(selectionRect);
//             delete selectionRect;
//             selectionRect = nullptr;

//             // 输出选中区域内的晶圆信息
//             QList<QGraphicsItem*> items = scene()->items(selectedArea, Qt::IntersectsItemShape);
//             qDebug() << "Selected Dies:";
//             for (QGraphicsItem* item : items) {
//                 DieItem* die = dynamic_cast<DieItem*>(item);
//                 if (die) {
//                     qDebug() << "Row:" << die->getRow() << "Col:" << die->getCol();
//                 }
//             }
//         }
//     }
//     QGraphicsView::mouseReleaseEvent(event);
// }

void WaferGraphicsView::wheelEvent(QWheelEvent* event) {
    const double zoomFactor = 1.1; // 每次缩放的倍率
    const double minScale = 1;
    const double maxScale = 10.0;

    if (event->angleDelta().y() > 0) {
        if (scaleFactor < maxScale) {
            scale(zoomFactor, zoomFactor);
            scaleFactor *= zoomFactor;
        }
    } else {
        if (scaleFactor > minScale) {
            scale(1.0 / zoomFactor, 1.0 / zoomFactor);
            scaleFactor /= zoomFactor;
        }
    }

    event->accept();
}
