#include "FormAuthCardDetail.h"
#include "ui_FormAuthCardDetail.h"

#include <QWindow>
#include <QTimer>
#include <QScreen>

#include "LanguageManager.h"

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

    this->setAttribute(Qt::WA_TranslucentBackground);
    initComboBox();
    setBackgroundImage();

    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });
    connect(ui->cancel, &QPushButton::clicked,  this, [this]() {
        hide();
    });
    connect(ui->ok, &QPushButton::clicked,      this, [this]() {
        auto data = getNewData();
    });
}

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

AUTH_CARD_INFO FormAuthCardDetail::auth_info() const
{
    return m_auth_info;
}

void FormAuthCardDetail::setAuth_info(const AUTH_CARD_INFO &newAuth_info)
{
    m_auth_info = newAuth_info;
    refreshData();
}

void FormAuthCardDetail::initConnect()
{

}

void FormAuthCardDetail::initComboBox()
{
    QStringList list;
    list << "Valid"
         << "InValid";

    ui->status->addItems(list);
}

void FormAuthCardDetail::setBackgroundImage()
{
    m_bg_image = new QLabel();

    ui->background_layout->addWidget(m_bg_image,
                                     0,
                                     0,
                                     ui->background_layout->rowCount(),
                                     ui->background_layout->columnCount());

    m_bg_image->setPixmap(QPixmap(":/images/price/price_detail_background.png"));
    m_bg_image->lower();
    m_bg_image->setScaledContents(true);
}

void FormAuthCardDetail::refreshData()
{
    ui->idTag->setText(m_auth_info.idTag);
    ui->expiryDate->setDateTime(QDateTime::fromString(m_auth_info.expiryDate, Qt::ISODate));
    ui->parentIdTag->setText(m_auth_info.parentIdTag);
    ui->status->setCurrentText(m_auth_info.status);
}

AUTH_CARD_INFO FormAuthCardDetail::getNewData()
{
    AUTH_CARD_INFO info;
    info.idTag = ui->idTag->text();
    info.expiryDate = ui->expiryDate->dateTime().toString("yyyy-MM-ddTHH:mm:ssZ");
    info.parentIdTag = ui->parentIdTag->text();
    info.status = ui->status->currentText();
    return info;
}

void FormAuthCardDetail::clearData()
{
    ui->idTag->setText("");
    ui->expiryDate->setDateTime(QDateTime::currentDateTimeUtc());
    ui->parentIdTag->setText("");
    ui->status->setCurrentIndex(0);
}

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

    // 获取有效的屏幕几何尺寸（考虑多显示器）
    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 FormAuthCardDetail::showEvent(QShowEvent *event)
{
    centerWindow();
    QWidget::showEvent(event);
}
