#include "loginwindow.h"

#include "../backendapimanager.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("请输入用户名");
    QMovie *movie = new QMovie(this);
    movie->setFileName(":/icons/icons/hxgc.gif");
    movie->start();
    ui->label->setMovie(movie);
    setWindowFlags(Qt::FramelessWindowHint);
    initUesrCombox();
}

void LoginWindow::initUesrCombox() {
    QStringList allUsernames = RegistryManager::instance()->getAllUsernames();
    for (const QString &username : allUsernames) {
        ui->username->addItem(username);
    }
    ui->username->setCurrentIndex(-1);
}
LoginWindow::~LoginWindow() { delete ui; }

void LoginWindow::on_btnLogin_clicked() {
    QString username = ui->username->currentText();
    QString password = ui->password->text();
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::critical(nullptr, "输入错误", "用户名或密码不能为空，请重新输入。");
        return;
    }
    try {
        this->ui->btnLogin->setStyleSheet(
            "QPushButton#btnLogin {"
            "    background-color: rgb(33, 46, 224);"
            "    color: white;"
            "    border-radius: 5px;"
            "    font: normal 18px 'Microsoft YaHei';"
            "}"
            "QPushButton#btnLogin:disabled {"
            "    background-color: rgb(200, 200, 200);"
            "    color: rgb(0, 0, 0);"
            "}");
        this->ui->btnLogin->setEnabled(false);
        this->ui->btnLogin->setText("登录中...");

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

        QUrl fullUrl = apiBackendUrl.resolved(QUrl("login/pc"));  // 替换为实际的服务器接口地址
        QNetworkRequest request(fullUrl);                         // 替换为实际的服务器接口地址
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        // 发送 POST 请求
        QNetworkReply *reply = manager->post(request, data);
        // 处理响应
        auto handleLoginResponse = [this, username, password](QNetworkReply *reply) {
            try {
                if (reply->error() == QNetworkReply::NoError) {
                    QByteArray responseData = reply->readAll();
                    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();
                            if (code == 500) {
                                QMessageBox *msgBox = new QMessageBox(this);
                                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::singleShot(1500, msgBox, [msgBox]() {
                                    msgBox->close();
                                    delete msgBox;
                                });
                                msgBox->show();
                            } else if (code == 200) {
                                QJsonObject userInfoObj = responseObj["userInfo"].toObject();
                                QJsonObject userObj = userInfoObj["user"].toObject();
                                int userId = userObj["userId"].toInt();
                                QString identity = userObj["identity"].toString();
                                QString userIdStr = QString::number(userId);
                                QString certName = userObj["nickName"].toString();
                                RegistryManager::instance()->saveUserInfo(
                                    userIdStr, username, password, identity, certName);
                                RegistryManager::instance()->setCurentLoginUserId(userIdStr);
                                QString Authority = responseObj["currentAuthority"].toString();
                                globalAuthority = "Bearer " + Authority;
                                this->close();
                                MainWindow *mainWindow = new MainWindow();
                                backendAPIManager::setAuthToken(globalAuthority);

                                /*TODO: delete test code
                                QString jsonString =
                                    "{\"app_version\":\"1.52\",\"blast_latitude\":\"30."
                                    "21122186731856\",\"blast_longitude\":\"120.22146062951883\","
                                    "\"blast_time\":\"2025-06-03 "
                                    "12:00:00\",\"company_code\":\"3701234300003\",\"equipment_"
                                    "sn\":\"F34A0000001\",\"error_deto_count\":\"0\",\"operator_"
                                    "identity\":\"330781198509079292\",\"operator_name\":\"栋工\","
                                    "\"phone\":\"18611112222\",\"project_htid\":\"\",\"project_"
                                    "name\":\"sidf\",\"project_xmbh\":\"\",\"reg_deto_count\":"
                                    "\"2\",\"regs\":[{\"after_test_bus_i\":\"41\",\"after_test_bus_"
                                    "v\":\"8006\",\"before_blasting_i\":\"49\",\"before_blasting_"
                                    "v\":\"13492\",\"bus_leakage_current_i\":\"0\",\"dets\":[{"
                                    "\"delay_time\":\"0.0\",\"freq\":\"0\",\"in_code\":"
                                    "\"005AC8360A4C01A7\",\"out_code\":\"2411104F18000\","
                                    "\"status\":\"0x00\",\"tag\":\"1-1-1\",\"uid\":"
                                    "\"24211104F18000\"},{\"delay_time\":\"80.0\",\"freq\":\"0\","
                                    "\"in_code\":\"015AC8360A4C014E\",\"out_code\":"
                                    "\"2411104F18001\",\"status\":\"0x00\",\"tag\":\"1-2-1\","
                                    "\"uid\":\"24211104F18001\"}],\"equipment_sn\":\"null\","
                                    "\"equipment_version\":\"null\",\"error_deto_count\":\"0\","
                                    "\"net_charged_i\":\"49\",\"net_charged_v\":\"13501\",\"reg_"
                                    "deto_count\":\"2\"}]}";
                                QJsonObject myJsonObject =
                                    QJsonDocument::fromJson(jsonString.toUtf8()).object();
                                qDebug()
                                    << "debug"
                                    << QDateTime::fromString(myJsonObject["blast_time"].toString(),
                                                             "yyyy-MM-dd hh:mm:ss")
                                           .toString(Qt::ISODateWithMs);
                                int row = 1;
                                firingWidget *wt = new firingWidget(row, false, "111");
                                wt->testonBlastSucess(myJsonObject);
                                //<< Delete
                                */

                                QScreen *screen = QGuiApplication::primaryScreen();
                                QRect screenGeometry = screen->geometry();
                                int screenWidth = screenGeometry.width();
                                int screenHeight = screenGeometry.height();
                                mainWindow->resize(screenWidth * 1, screenHeight * 0.95);

                                int windowWidth = mainWindow->width();
                                int windowHeight = mainWindow->height();
                                int x = (screenWidth - windowWidth) / 2;
                                int y = (screenHeight - windowHeight) / 2;

                                mainWindow->move(x, y - 10);
                                mainWindow->show();
                            }
                        }
                    }
                } else {
                    QMessageBox::critical(nullptr, "无法登录，网络请求错误",
                                          QString("错误信息: %1\n错误代码: %2")
                                              .arg(reply->errorString())
                                              .arg(reply->error()));
                }
            } catch (const std::exception &e) {
                qDebug() << "Exception in response handling: " << e.what();
            }
            this->ui->btnLogin->setEnabled(true);
            this->ui->btnLogin->setText("登录");
            reply->deleteLater();
        };

        QObject::connect(reply, &QNetworkReply::finished,
                         [reply, handleLoginResponse]() { handleLoginResponse(reply); });
    } catch (const std::exception &e) {
        qDebug() << "Exception in request sending: " << e.what();
    }
}

void LoginWindow::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void LoginWindow::mouseMoveEvent(QMouseEvent *event) {
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    }
}

void LoginWindow::on_btnClose_clicked() { this->close(); }

void LoginWindow::on_btnMin_clicked() { this->showMinimized(); }

void LoginWindow::on_username_activated(int index) { qDebug() << index; }

void LoginWindow::on_username_currentIndexChanged(int index) {
    QString name = ui->username->currentText();

    QString pass = RegistryManager::instance()->getPasswordByUsername(name);

    ui->password->setText(pass);
}
