#include "FormPrice.h"
#include "ui_FormPrice.h"

#include <QWindow>
#include <QTimer>
#include <QScreen>
#include <QDebug>
#include <QScroller>
#include <QGraphicsDropShadowEffect>

#include "LanguageManager.h"

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

    initWidget();
    initConnect();
}

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

void FormPrice::initWidget()
{
    this->setAttribute(Qt::WA_TranslucentBackground);

    initTableWidget();

    setBackgroundImage();
}

void FormPrice::initConnect()
{
    connect(ui->close, &QToolButton::clicked, this, &FormPrice::closeBtnClicked);
    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() {
        ui->retranslateUi(this);
    });
}

void FormPrice::initTableWidget()
{
    ui->tableWidget->horizontalHeader()->hide();
    ui->tableWidget->verticalHeader()->hide();

    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    QScroller::grabGesture(ui->tableWidget,              QScroller::TouchGesture);
    QScroller::grabGesture(ui->tableWidget->viewport(),  QScroller::LeftMouseButtonGesture);

    ui->tableWidget->setColumnCount(4);

    addTableWidgetItem("6:00-12:00",    "1.25",     "1.00",     "0.25");
    addTableWidgetItem("13:00-14:00",   "1.25",     "1.00",     "0.25");
    addTableWidgetItem("15:00-16:00",   "1.25",     "1.00",     "0.25");
    addTableWidgetItem("17:00-18:00",   "1.25",     "1.00",     "0.25");
    addTableWidgetItem("19:00-20:00",   "1.25",     "1.00",     "0.25");
    addTableWidgetItem("21:00-22:00",   "1.25",     "1.00",     "0.25");

    selectTableWidgetRow(0);
}

void FormPrice::clearTableWidgetItem()
{
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);
}

void FormPrice::selectTableWidgetRow(int row)
{
    ui->tableWidget->selectRow(row);
}

void FormPrice::addTableWidgetItem(const QString &period, const QString &total, const QString &electricity, const QString &service)
{
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);
    auto period_item = new QTableWidgetItem(period);
    period_item->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 0, period_item);

    auto total_item = new QTableWidgetItem(total);
    total_item->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 1, total_item);

    auto elec_item = new QTableWidgetItem(electricity);
    elec_item->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 2, elec_item);

    auto service_item = new QTableWidgetItem(service);
    service_item->setTextAlignment(Qt::AlignCenter);
    ui->tableWidget->setItem(row, 3, service_item);

    ui->tableWidget->setRowHeight(row, 60);
}

void FormPrice::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_background.png"));
    m_bg_image->lower();
    m_bg_image->setScaledContents(true);
}

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

void FormPrice::closeBtnClicked()
{
    this->hide();
}
