#include "loadingmask.h"
#include <QPainter>
#include <QResizeEvent>

LoadingMask::LoadingMask(QWidget *parent) : QWidget(parent) {
    // 设置为无边框窗口
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
    setAttribute(Qt::WA_TranslucentBackground);
    
    // 初始化加载提示标签
    loadingLabel = new QLabel(this);
    loadingLabel->setStyleSheet("QLabel { color: white; font-size: 16px; "
                               "background-color: rgba(0, 0, 0, 120); "
                               "padding: 10px 20px; border-radius: 5px; }");
    loadingLabel->setAlignment(Qt::AlignCenter);
    
    // 初始化超时定时器
    timeoutTimer = new QTimer(this);
    timeoutTimer->setSingleShot(true);
    connect(timeoutTimer, &QTimer::timeout, this, &LoadingMask::onTimeout);
    
    // 安装事件过滤器以处理父窗口大小变化
    if (parent) {
        parent->installEventFilter(this);
    }
}

void LoadingMask::show(QWidget* parent, const QString &text, int timeout) {
    // 创建新的遮罩实例（会在隐藏时自动删除）
    LoadingMask* mask = new LoadingMask(parent);
    mask->setAttribute(Qt::WA_DeleteOnClose);
    
    // 设置遮罩大小为父窗口大小
    mask->setGeometry(parent->rect());
    
    // 设置提示文本
    mask->loadingLabel->setText(text);
    mask->loadingLabel->adjustSize();
    mask->loadingLabel->move((mask->width() - mask->loadingLabel->width()) / 2,
                           (mask->height() - mask->loadingLabel->height()) / 2);
    
    // 启动超时定时器
    if (timeout > 0) {
        mask->timeoutTimer->start(timeout);
    }
    
    mask->QWidget::show();
    mask->raise();
}

void LoadingMask::hideOverlay() {
    timeoutTimer->stop();
    close(); // 使用 close 而不是 hide，因为设置了 DeleteOnClose
}

void LoadingMask::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.fillRect(rect(), QColor(0, 0, 0, 128)); // 半透明黑色背景
}

bool LoadingMask::eventFilter(QObject *watched, QEvent *event) {
    if (watched == parent()) {
        if (event->type() == QEvent::Resize) {
            // 父窗口大小改变时，调整遮罩层大小
            QResizeEvent *resizeEvent = static_cast<QResizeEvent*>(event);
            setGeometry(0, 0, resizeEvent->size().width(), resizeEvent->size().height());
            
            // 重新居中显示加载提示
            loadingLabel->move((width() - loadingLabel->width()) / 2,
                             (height() - loadingLabel->height()) / 2);
        }
    }
    return QWidget::eventFilter(watched, event);
}

void LoadingMask::onTimeout() {
    hideOverlay();
} 