#include "DialogLimitEdit.h"
#include "ui_DialogLimitEdit.h"

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

#include "LanguageManager.h"
#include "GeneralInterface.h"

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

    setWindowModality(Qt::WindowModal);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    initConnect();
}

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

Limit DialogLimitEdit::limit_info()
{
    updateData();
    return m_limit_info;
}

void DialogLimitEdit::setLimit_info(const Limit &newLimit_info)
{
    m_limit_info = newLimit_info;
}

void DialogLimitEdit::clear()
{
    m_limit_info.startPeriod    = 0;
    m_limit_info.limit          = 0;
}

void DialogLimitEdit::initWidget()
{
    QStringList unitList;
    unitList << ChargingProfiles::UnitType::AMPERE;
    unitList << ChargingProfiles::UnitType::WATT;
    ui->chargingRateUnit->addItems(unitList);

    QStringList durationUnitList;
    durationUnitList << "HH:mm:ss"
                     << "S";
    ui->startPeriodUnit->addItems(durationUnitList);

    ui->limit->setEditType(EditType::DOUBLE);
}

void DialogLimitEdit::initConnect()
{
    connect(ui->chargingRateUnit, &CustomComboBox::currentIndexChanged, this, [this](const int& index) {
        switch (index) {
        case ChargingProfiles::UnitType::AMPERE_ID:
            ui->unit->setText(tr("A"));
            break;
        case ChargingProfiles::UnitType::WATT_ID:
            ui->unit->setText(tr("KW"));
            break;
        default:
            break;
        }
    });
    connect(ui->cancel, &QPushButton::clicked,  this, [this]() {
        reject();
    });
    connect(ui->ok, &QPushButton::clicked,      this, [this]() {
        accept();
    });
    connect(ui->startPeriodUnit, &CustomComboBox::currentIndexChanged,      this, [this]() {
        setDuration();
    });

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

void DialogLimitEdit::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 DialogLimitEdit::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 DialogLimitEdit::refreshData()
{
    setDuration();
    ui->chargingRateUnit->setCurrentText(m_limit_info.unit);
    ui->limit->setText(QString::number(m_limit_info.limit / 1000.0, 'f', 2));
}

void DialogLimitEdit::setDuration()
{
    switch (ui->startPeriodUnit->currentIndex()) {
    case StartPeriodUnit::UTC_STR:
        ui->startPeriod->setText(GeneralInterface::getCurrentDate(m_limit_info.startPeriod));
        ui->startPeriod->setEditType(EditType::TEXT);
        break;
    case StartPeriodUnit::SECONDS:
        ui->startPeriod->setText(QString::number(m_limit_info.startPeriod));
        ui->startPeriod->setEditType(EditType::INT);
        break;
    default:
        break;
    }
}

void DialogLimitEdit::updateData()
{
    m_limit_info.startPeriod    = getDuration();
    m_limit_info.unit           = ui->chargingRateUnit->currentText();
    m_limit_info.limit          = ui->limit->text().toDouble() * 1000;
}

int DialogLimitEdit::getDuration()
{
    switch (ui->startPeriodUnit->currentIndex()) {
    case StartPeriodUnit::UTC_STR:  return GeneralInterface::getCurrentDate(ui->startPeriod->text());
    case StartPeriodUnit::SECONDS:  return ui->startPeriod->text().toDouble();
    default:
        break;
    }
    return 0;
}

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