#include "DialogChargingProfileEdit.h"
#include "ui_DialogChargingProfileEdit.h"

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

#include "DataTypeDef.h"
#include "ConfigManager.h"
#include "LanguageManager.h"
#include "GeneralInterface.h"

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

    initWidget();
    initConnect();
}

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

void DialogChargingProfileEdit::clear()
{
    ui->chargingProfileID->setText("");
    ui->connectorID->setCurrentIndex();
    ui->stackLevel->setCurrentIndex();
    ui->chargingProfilePurpose->setCurrentIndex();
    ui->chargingProfileKind->setCurrentIndex();
    ui->recurrencyKind->setCurrentIndex();
}

charging_profiles_detail_info_t DialogChargingProfileEdit::getChargingProfile()
{
    charging_profiles_detail_info_t info;
    info.chargingProfileId      = ui->chargingProfileID->text().toInt();
    info.connectorId            = ui->connectorID->currentText().toInt();
    info.stackLevel             = ui->stackLevel->currentText().toInt();
    info.chargingProfilePurpose = ui->chargingProfilePurpose->currentText();
    info.chargingProfileKind    = ui->chargingProfileKind->currentText();
    info.recurrencyKind         = ui->recurrencyKind->currentText();

    return info;
}

void DialogChargingProfileEdit::initWidget()
{
    setWindowModality(Qt::WindowModal);
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    setBackground();

    initComboBox();
}

void DialogChargingProfileEdit::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(ui->chargingProfilePurpose, &CustomComboBox::currentTextChanged,    this, [this](const QString& text) {
        if (text == ChargingProfiles::Purpose::CHARGE_POINT_MAX_PROFILE) {
            ui->connectorID_label->setVisible(true);
            ui->connectorID->setVisible(false);
        } else if (text == ChargingProfiles::Purpose::TX_DEFAULT_PROFILE) {
            ui->connectorID_label->setVisible(false);
            ui->connectorID->setVisible(true);
        } else if (text == ChargingProfiles::Purpose::TX_PROFILE) {
            ui->connectorID_label->setVisible(true);
            ui->connectorID->setVisible(false);
        }
    });
    connect(ui->chargingProfileKind, &CustomComboBox::currentIndexChanged,      this, [this](const int& index) {
        switch (index) {
        case ChargingProfiles::Kind::ABSOLUTE_ID:
        case ChargingProfiles::Kind::RELATIVE_ID:
            ui->recurrencyKind->setCurrentIndex(ChargingProfiles::RecurrencyKind::NO_RECURRING_ID);
            ui->recurrencyKind->setEnabled(false);
            break;
        case ChargingProfiles::Kind::RECURRING_ID:
            ui->recurrencyKind->setEnabled(true);
            break;
        default:
            break;
        }
    });
}

void DialogChargingProfileEdit::initComboBox()
{
    initConnectorIdComboBox();
    initStackLevelComboBox();
    initPurposeComboBox();
    initKindComboBox();
    initRecurrencyKindComboBox();
}

void DialogChargingProfileEdit::initConnectorIdComboBox()
{
    auto gun_num = ConfigManager::instance()->ccu_cfg().GUN_Numb;
    QStringList connectorIDItems;
    for (int index = 1; index <= gun_num; index ++) {
        connectorIDItems << QString::number(index);
    }
    ui->connectorID->addItems(connectorIDItems);
    ui->connectorID->setEnabled(gun_num == 1);
}

void DialogChargingProfileEdit::initStackLevelComboBox()
{
    auto stack_level = ConfigManager::instance()->cfg_key().SmartChargingProfile.ChargeProfileMaxStackLevel;
    QStringList stackLevelItems;
    for (int index = 0; index <= stack_level; index ++) {
        stackLevelItems << QString::number(index);
    }
    ui->stackLevel->addItems(stackLevelItems);
}

void DialogChargingProfileEdit::initPurposeComboBox()
{
    QStringList purposeItems;
    purposeItems << ChargingProfiles::Purpose::CHARGE_POINT_MAX_PROFILE
                 << ChargingProfiles::Purpose::TX_DEFAULT_PROFILE
                 << ChargingProfiles::Purpose::TX_PROFILE;

    ui->chargingProfilePurpose->addItems(purposeItems);
}

void DialogChargingProfileEdit::initKindComboBox()
{
    QStringList kind_list;
    kind_list << ChargingProfiles::Kind::ABSOLUTE
              << ChargingProfiles::Kind::RELATIVE
              << ChargingProfiles::Kind::RECURRING;
    ui->chargingProfileKind->addItems(kind_list);
}

void DialogChargingProfileEdit::initRecurrencyKindComboBox()
{
    QStringList recurrencyKindList;
    recurrencyKindList << ChargingProfiles::RecurrencyKind::NO_RECURRING
                       << ChargingProfiles::RecurrencyKind::DAILY
                       << ChargingProfiles::RecurrencyKind::WEEKLY;
    ui->recurrencyKind->addItems(recurrencyKindList);
}

void DialogChargingProfileEdit::refreshData()
{
    ui->recurrencyKind->setEnabled(false);
    ui->connectorID_label->setVisible(true);
    ui->connectorID->setVisible(false);
    auto charging_profiles = ConfigManager::instance()->charging_profiles().chargingProfiles;
    ui->chargingProfileID->setText(QString::number(GeneralInterface::getMaxChargingProfileId(charging_profiles) + 1));
}

void DialogChargingProfileEdit::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 DialogChargingProfileEdit::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 DialogChargingProfileEdit::showEvent(QShowEvent *event)
{
    centerWindow();
    refreshData();
    QDialog::showEvent(event);
}
