#include "DialogErrorNoteCode.h"
#include "ui_DialogErrorNoteCode.h"

#include <QScreen>
#include <QTimer>
#include <QWindow>
#include <QDebug>
#include <QIntValidator>
#include <QPropertyAnimation>

#include "LanguageManager.h"

DialogErrorNoteCode::DialogErrorNoteCode(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::DialogErrorNoteCode)
{
    ui->setupUi(this);

    setBackground();
    initConnect();

    ui->error_code->setDisplayBase(CustomLineEdit::Base_Hex);
    setWindowModality(Qt::WindowModal);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
}

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

void DialogErrorNoteCode::clear()
{
    ui->error_code->setText("0");
    ui->error_note->setText("Please enter the error comment...");
}

ERROR_NOTE DialogErrorNoteCode::error_info() const
{
    return m_error_info;
}

void DialogErrorNoteCode::setError_info(const ERROR_NOTE &newError_info)
{
    m_error_info = newError_info;
}

void DialogErrorNoteCode::initConnect()
{
    connect(ui->cancel, &QPushButton::clicked,  this, [this]() {
        reject();
    });
    connect(ui->ok,     &QPushButton::clicked,  this, [this]() {
        updateData();
        accept();
    });

    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });
}

void DialogErrorNoteCode::refreshData()
{
    ui->error_code->setText(QString("0x%1").arg(QString::number(m_error_info.error_code, 16).toUpper()));
    ui->error_note->setText(m_error_info.error_note);
}

void DialogErrorNoteCode::updateData()
{
    bool ok = false;
    m_error_info.error_code = ui->error_code->text().toUInt(&ok, 0);
    m_error_info.error_note = ui->error_note->text();
}

void DialogErrorNoteCode::setBackground()
{
    m_background = new QLabel();
    ui->background_layout->addWidget(m_background, 0, 0, ui->background_layout->rowCount(), ui->background_layout->columnCount());
    m_background->setPixmap(QPixmap(":/images/price/dialog_edit_background.png"));
    m_background->lower();
    m_background->setScaledContents(true);
}

void DialogErrorNoteCode::centerWindow()
{
    // 确保窗口尺寸已确定（关键修复）
    this->ensurePolished();
    // this->adjustSize();

    // 获取有效的屏幕几何尺寸（考虑多显示器）
    QScreen *screen = QGuiApplication::primaryScreen();
    if (QWindow *window = this->windowHandle()) {
        screen = window->screen();
    }
    QRect screenGeometry = screen->availableGeometry();

    // 计算居中位置（考虑Wayland特性）
    int x = (screenGeometry.width() - this->width()) / 2 + screenGeometry.x();
    int y = (screenGeometry.height() - this->height()) / 2 + screenGeometry.y();

    if (QGuiApplication::platformName().contains("wayland")) {
        // Wayland专用处理
        if (QWindow *window = this->windowHandle()) {
            // 重要：延迟设置位置，确保Wayland合成器已准备好
            QTimer::singleShot(100, this, [window, x, y]() {
                window->setPosition(QPoint(x, y));

                // 替代requestActivate的方案
                window->setFlags(window->flags() | Qt::WindowStaysOnTopHint);
                QTimer::singleShot(50, [window]() {
                    window->setFlags(window->flags() & ~Qt::WindowStaysOnTopHint);
                });
            });
        }
    } else {
        // 传统X11处理
        this->move(x, y);
    }
}

void DialogErrorNoteCode::showEvent(QShowEvent *event)
{
    centerWindow();
    refreshData();
    QDialog::showEvent(event);
}
