#include "loginwindow.h"

#include "global.h"
#include "ui_loginwindow.h"

LoginWindow::LoginWindow(QWidget *parent)
    : QWidget(parent), ui(new Ui::LoginWindow), manager(new QNetworkAccessManager(this)) {
    ui->setupUi(this);
    ui->username->lineEdit()->setPlaceholderText("请输入用户名");
    // 设置窗口为无边框样式
    setWindowFlags(Qt::FramelessWindowHint);
}

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

void LoginWindow::on_btnLogin_clicked() {
    QString username = ui->username->currentText();
    QString password = ui->password->text();
    if (username.isEmpty() || password.isEmpty()) {
        qDebug() << "Error: Username or password cannot be empty.";
        QMessageBox::critical(nullptr, "输入错误", "用户名或密码不能为空，请重新输入。");
        return;
    }

    try {
        // 构造请求数据
        QJsonObject jsonData;
        jsonData["username"] = username;
        jsonData["password"] = password;
        QJsonDocument doc(jsonData);
        QByteArray data = doc.toJson();

        QUrl localUrl("login/pc");

        QUrl fullUrl = apiBackendUrl.resolved(localUrl);

        qDebug() << "fullUrl" << fullUrl;
        // 构造请求
        // QNetworkRequest request(QUrl("http://localhost:8000/api/v1/login/pc")); //
        // 替换为实际的服务器接口地址
        QNetworkRequest request(
            QUrl("http://localhost:8000/api/v1/login/pc"));  // 替换为实际的服务器接口地址
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        // 发送 POST 请求
        QNetworkReply *reply = manager->post(request, data);

        // 处理响应
        QObject::connect(reply, &QNetworkReply::finished, [reply, this]() {
            try {
                if (reply->error() == QNetworkReply::NoError) {
                    QByteArray responseData = reply->readAll();
                    qDebug() << "Response:" << QString::fromUtf8(responseData);
                    // 解析 JSON 响应
                    QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);
                    if (!responseDoc.isNull() && responseDoc.isObject()) {
                        QJsonObject responseObj = responseDoc.object();
                        if (responseObj.contains("code") && responseObj["code"].isDouble()) {
                            int code = responseObj["code"].toInt();
                            // QString Message = responseObj["msg"].toString();
                            if (code == 500) {
                                // 使用指针动态分配内存
                                QMessageBox *msgBox = new QMessageBox;
                                msgBox->setAttribute(Qt::WA_TranslucentBackground, true);
                                msgBox->setWindowTitle("");  // 清空窗口标题
                                msgBox->setText("用户名或密码错误，请重试。");
                                msgBox->setWindowFlags(msgBox->windowFlags() |
                                                       Qt::FramelessWindowHint);
                                msgBox->setStandardButtons(
                                    QMessageBox::NoButton);  // 不设置标准按钮

                                // 设置样式表
                                msgBox->setStyleSheet(
                                    "QMessageBox {"
                                    "    border: none; /* 去除边框 */"
                                    "}"
                                    "QLabel {"
                                    "    color: #a94442; /* 标签文字颜色 */"
                                    "    background-color: transparent; /* 标签背景透明 */"
                                    "    font-size: 20px; /* 设置字体大小，可根据需要调整 */"
                                    "}"
                                    "QPushButton {"
                                    "    visibility: hidden; /* 隐藏按钮 */"
                                    "}");

                                // 使用 QTimer 在 3 秒后自动关闭消息框
                                QTimer::singleShot(1200, msgBox, [msgBox]() {
                                    msgBox->close();
                                    delete msgBox;  // 释放内存
                                });
                                msgBox->show();
                            } else if (code == 200) {
                                // 如果登录成功 存储用户信息 关闭登录接口 打开主界面
                                this->close();
                                MainWindow *mainWindow = new MainWindow();

                                mainWindow->show();
                            }
                        }
                    }
                } else {
                    qDebug() << "Error:" << reply->errorString();
                }
            } catch (const std::exception &e) {
                qDebug() << "Exception in response handling: " << e.what();
            }
            reply->deleteLater();
        });

    } catch (const std::exception &e) {
        qDebug() << "Exception in request sending: " << e.what();
    }
}
