#include "DialogChargingPopup.h"
#include "ui_DialogChargingPopup.h"

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

#include "LanguageManager.h"

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

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

    ui->value->setValidator(new QIntValidator(0, 1000, this));
    ui->value->setInputMethodHints(Qt::ImhDigitsOnly);

    updateShow(type);
    setStyleSheet("QLineEdit { "
                  "background-color: #3A3A3F; "
                  "color: white;"
                  "border-radius: 5px;"
                  "}"
                  "QPushButton {"
                  "background: rgb(124, 176, 243);"
                  "border-radius:10px;"
                  "}");

    initConnect();
}

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

int DialogChargingPopup::getValue()
{
    return ui->value->text().toInt();
}

void DialogChargingPopup::initWidget()
{
    initSocButtonGroup();
    initTimeButtonGroup();
    initEnergyButtonGroup();
}

void DialogChargingPopup::initConnect()
{
    connect(ui->cancel, &QPushButton::clicked, this, [this]() {
        reject();
    });
    connect(ui->ok,     &QPushButton::clicked, this, [this]() {
        accept();
    });
    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });

    // 监听全局键盘事件
    connect(QGuiApplication::inputMethod(), &QInputMethod::visibleChanged,
            this, &DialogChargingPopup::onKeyboardVisibilityChanged);

    // 监听按钮组当前选中按钮信号
    connect(soc_btn_group,      &QButtonGroup::idClicked, this, [this](int id) {
        ui->value->setText(QString::number(id));
    });
    connect(time_btn_group,     &QButtonGroup::idClicked, this, [this](int id) {
        ui->value->setText(QString::number(id));
    });
    connect(energy_btn_group,   &QButtonGroup::idClicked, this, [this](int id) {
        ui->value->setText(QString::number(id));
    });
}

void DialogChargingPopup::updateShow(int type)
{
    switch (type) {
    case EditType::SOC:
        ui->titles->setText(tr("SOC"));
        ui->stackedWidget->setCurrentWidget(ui->soc_widget);
        break;
    case EditType::ENERGY:
        ui->titles->setText(tr("ENERGY"));
        ui->stackedWidget->setCurrentWidget(ui->energy_widget);
        break;
    case EditType::TIME:
        ui->titles->setText(tr("TIME"));
        ui->stackedWidget->setCurrentWidget(ui->time_widget);
        break;
    default:
        break;
    }
}

void DialogChargingPopup::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 DialogChargingPopup::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 DialogChargingPopup::initTimeButtonGroup()
{
    time_btn_group = new QButtonGroup();
    time_btn_group->addButton(ui->btn_10_time, 10);
    time_btn_group->addButton(ui->btn_15_time, 15);
    time_btn_group->addButton(ui->btn_20_time, 20);
    time_btn_group->addButton(ui->btn_25_time, 25);
    time_btn_group->addButton(ui->btn_30_time, 30);
    time_btn_group->addButton(ui->btn_35_time, 35);
    time_btn_group->addButton(ui->btn_40_time, 40);
    time_btn_group->addButton(ui->btn_45_time, 45);
    time_btn_group->addButton(ui->btn_50_time, 50);
    time_btn_group->addButton(ui->btn_55_time, 55);
    time_btn_group->addButton(ui->btn_60_time, 60);
    time_btn_group->addButton(ui->btn_65_time, 65);
    time_btn_group->addButton(ui->btn_70_time, 70);
    time_btn_group->addButton(ui->btn_75_time, 75);
    time_btn_group->addButton(ui->btn_80_time, 80);
    time_btn_group->addButton(ui->btn_85_time, 85);
    time_btn_group->addButton(ui->btn_90_time, 90);
    time_btn_group->addButton(ui->btn_95_time, 95);
    time_btn_group->addButton(ui->btn_100_time, 100);
}

void DialogChargingPopup::initSocButtonGroup()
{
    soc_btn_group = new QButtonGroup();
    soc_btn_group->addButton(ui->btn_10_soc, 10);
    soc_btn_group->addButton(ui->btn_15_soc, 15);
    soc_btn_group->addButton(ui->btn_20_soc, 20);
    soc_btn_group->addButton(ui->btn_25_soc, 25);
    soc_btn_group->addButton(ui->btn_30_soc, 30);
    soc_btn_group->addButton(ui->btn_35_soc, 35);
    soc_btn_group->addButton(ui->btn_40_soc, 40);
    soc_btn_group->addButton(ui->btn_45_soc, 45);
    soc_btn_group->addButton(ui->btn_50_soc, 50);
    soc_btn_group->addButton(ui->btn_55_soc, 55);
    soc_btn_group->addButton(ui->btn_60_soc, 60);
    soc_btn_group->addButton(ui->btn_65_soc, 65);
    soc_btn_group->addButton(ui->btn_70_soc, 70);
    soc_btn_group->addButton(ui->btn_75_soc, 75);
    soc_btn_group->addButton(ui->btn_80_soc, 80);
    soc_btn_group->addButton(ui->btn_85_soc, 85);
    soc_btn_group->addButton(ui->btn_90_soc, 90);
    soc_btn_group->addButton(ui->btn_95_soc, 95);
    soc_btn_group->addButton(ui->btn_100_soc, 100);
}

void DialogChargingPopup::initEnergyButtonGroup()
{
    energy_btn_group = new QButtonGroup();
    energy_btn_group->addButton(ui->btn_10_energy, 10);
    energy_btn_group->addButton(ui->btn_15_energy, 15);
    energy_btn_group->addButton(ui->btn_20_energy, 20);
    energy_btn_group->addButton(ui->btn_25_energy, 25);
    energy_btn_group->addButton(ui->btn_30_energy, 30);
    energy_btn_group->addButton(ui->btn_35_energy, 35);
    energy_btn_group->addButton(ui->btn_40_energy, 40);
    energy_btn_group->addButton(ui->btn_45_energy, 45);
    energy_btn_group->addButton(ui->btn_50_energy, 50);
    energy_btn_group->addButton(ui->btn_55_energy, 55);
    energy_btn_group->addButton(ui->btn_60_energy, 60);
    energy_btn_group->addButton(ui->btn_65_energy, 65);
    energy_btn_group->addButton(ui->btn_70_energy, 70);
    energy_btn_group->addButton(ui->btn_75_energy, 75);
    energy_btn_group->addButton(ui->btn_80_energy, 80);
    energy_btn_group->addButton(ui->btn_85_energy, 85);
    energy_btn_group->addButton(ui->btn_90_energy, 90);
    energy_btn_group->addButton(ui->btn_95_energy, 95);
    energy_btn_group->addButton(ui->btn_100_energy, 100);
}

void DialogChargingPopup::onKeyboardVisibilityChanged()
{
    QInputMethod *im = QGuiApplication::inputMethod();
    if (im->isVisible()) {
        // 保存原始位置
        m_originalPos = pos();
        // 计算键盘高度（更准确的方式）
        int keyboardHeight = QGuiApplication::primaryScreen()->geometry().height() / 2;

        // 确保窗口不会与键盘重叠
        QRect screenGeo = screen()->availableGeometry();
        QRect widgetGeo = this->geometry();
        int newY = qMin(widgetGeo.y(),
                        screenGeo.bottom() - keyboardHeight - widgetGeo.height() - 20);
        if (newY != widgetGeo.bottom()) {
            move(widgetGeo.x(), newY);
        }
    } else {
        // 恢复原始位置（带动画效果更友好）
        QPropertyAnimation *anim = new QPropertyAnimation(this, "pos");
        anim->setDuration(100);
        anim->setEndValue(m_originalPos);
        anim->start(QAbstractAnimation::DeleteWhenStopped);
    }
}

void DialogChargingPopup::showEvent(QShowEvent *event)
{
    centerWindow();
    ui->value->setFocus();
    QDialog::showEvent(event);
}
