#include "ImageWidget.h"
#include "ui_ImageWidget.h"
#include <QPainter>
#include <QDebug>
ImageWidget::ImageWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ImageWidget),
    isDragging(false),
    imageOffset(0, 0)
{
    ui->setupUi(this);
}

ImageWidget::~ImageWidget()
{
    delete ui;
}

void ImageWidget::setPixmap(const QPixmap& newPixmap) {
    this->pixmap = newPixmap;
    imageOffset = QPoint(0, 0); // 重置图片偏移量为(0, 0)
    setCursor(Qt::ArrowCursor);
    update(); // 触发重绘
}
void ImageWidget::setPixmapAndPoint(const QPixmap& pixmap, double previousScaleFactor, qreal scaleFactor, QPoint mousePos) {
    this->pixmap = pixmap;
    QPointF imagePos = (mousePos - imageOffset) / previousScaleFactor;
    imageOffset = mousePos - imagePos * scaleFactor;
    update();
}
void ImageWidget::clearPixmap() {
    this->pixmap = QPixmap(); // 将 pixmap 设置为空
    update(); // 触发重绘
}
void ImageWidget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    if (!pixmap.isNull()) {
        // 限制图片偏移量，确保图片不会被拖动到视图外
        int pixmapWidth = pixmap.width();
        int pixmapHeight = pixmap.height();
        int widgetWidth = width();
        int widgetHeight = height();

        // 限制横向偏移量，确保图片不会超出左边或右边
        if (pixmapWidth < widgetWidth) {
            imageOffset.setX(0); // 如果图片宽度小于控件宽度，居中显示
        } else {
            // 图片左边界不能超出控件左边，右边界不能超出控件右边
            imageOffset.setX(qMin(0.0, qMax(static_cast<qreal>(widgetWidth - pixmapWidth), imageOffset.x())));
        }

        // 限制纵向偏移量，确保图片不会超出上边或下边
        if (pixmapHeight < widgetHeight) {
            imageOffset.setY(0); // 如果图片高度小于控件高度，居中显示
        } else {
            // 图片上边界不能超出控件上边，下边界不能超出控件下边
            imageOffset.setY(qMin(0.0, qMax(static_cast<qreal>(widgetHeight - pixmapHeight), imageOffset.y())));
        }
        painter.drawPixmap(imageOffset.x(), imageOffset.y(), pixmap);
    }
}

void ImageWidget::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        lastMousePos = event->pos(); // 记录鼠标按下时的位置
        isDragging = true; // 设置正在拖动的标志
        setCursor(Qt::OpenHandCursor);
    }
}

void ImageWidget::mouseMoveEvent(QMouseEvent *event) {
    if (isDragging && (event->buttons() & Qt::LeftButton)) {
        QPoint delta = event->pos() - lastMousePos; // 计算鼠标移动的偏移量
        imageOffset += delta; // 更新图片的偏移量
        lastMousePos = event->pos(); // 更新鼠标位置
        update();
    }
}

void ImageWidget::mouseReleaseEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        isDragging = false; // 重置正在拖动的标志
        setCursor(Qt::ArrowCursor);
    }
}
void ImageWidget::mouseDoubleClickEvent(QMouseEvent *event){
    if (event->type() == QEvent::MouseButtonDblClick) {
        // 恢复原始图像
        sendDoubleClicksignal();
    }
    QWidget::mouseDoubleClickEvent(event);
}
