#include "serversetting.h"
#include "ui_serversetting.h"

ServerSetting::ServerSetting(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerSetting)
{
    ui->setupUi(this);
    initForm();
    initWidget();
}

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

void ServerSetting::setAddress(QString address)
{
    ui->ledAddress->setText(address);
}

void ServerSetting::setUserName(QString username)
{
    ui->ledPort->setText(username);
}

void ServerSetting::setPassword(QString password)
{
    ui->ledPwd->setText(password);
}

void ServerSetting::initForm()
{

    this->setWindowFlag(Qt::FramelessWindowHint);
    this->setWindowFlags(this->windowFlags() | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);
    setAttribute(Qt::WA_TranslucentBackground);
    ui->ledAddress->setPlaceholderText("example.com/ip:port");
    ui->ledPort->setPlaceholderText("admin");
}

void ServerSetting::initWidget()
{
    connect(ui->btnCencel, &QPushButton::clicked, [&](){
        this->hide();
    });
    connect(ui->btnOk, &QPushButton::clicked, [&](){
        emit okClicked(ui->ledAddress->text(), ui->ledPort->text().toInt());
        this->hide();
    });

    this->setWindowModality(Qt::ApplicationModal);
}

void ServerSetting::on_btnOk_clicked()
{
    if (ui->ledAddress->text().isEmpty() || ui->ledPort->text().isEmpty() ||
            ui->ledPwd->text().isEmpty())
        return;

    QString address = ui->ledAddress->text();
    QString userName = ui->ledPort->text();
    QString password = ui->ledPwd->text();

    emit signal_updateServerConfig(address, userName, password);

    TCHttpService::getInstance()->setConfiguration(userName, password, address);
}

void ServerSetting::paintEvent(__attribute__((unused))QPaintEvent *event)
{
//     QStyleOption opt;
// #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
//     opt.init(this);
// #else
//     opt.initFrom(this);
// #endif
//     QPainter painter(this);
//     style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿

    // 绘制圆角背景
    QPainterPath path;
    path.addRoundedRect(rect(), 15, 15); // 30px 圆角半径
    painter.fillPath(path, Qt::white);   // 填充白色
}
