#include "specialdlg.h"
#include "tools.h"
#include "globaldefine.h"
#include "base/waitingdlg.h"
#include "LoUIClass/qiplineedit.h"
#include <QMessageBox>
#include <QMetaEnum>

SpecialDlg::SpecialDlg(QWidget *parent) : QDialog(parent) {
    resize(300, 100);
    setWindowTitle(tr("Specify IP"));

    auto vBox = new QVBoxLayout(this);
    vBox->addStretch();

    auto hBox = new QHBoxLayout();
    hBox->addStretch();

    auto label = new QLabel(tr("Specify IP"));
    label->setAlignment(Qt::AlignCenter);
    hBox->addWidget(label);

    auto fdIP = new QIPLineEdit();
    fdIP->setMinimumWidth(160);
    hBox->addWidget(fdIP);

    hBox->addStretch();

    vBox->addLayout(hBox);
    vBox->addStretch();

    hBox = new QHBoxLayout();
    hBox->addStretch();

    auto bnSearch = new QPushButton(tr("Search"));
    hBox->addWidget(bnSearch);

    auto btnCancel = new QPushButton(tr("Cancel"));
    connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject);
    hBox->addWidget(btnCancel);

    hBox->addStretch();

    vBox->addLayout(hBox);

    //绑定信号和槽函数
    connect(bnSearch, &QPushButton::clicked, this, [this, fdIP] {
        QString strTempIp = fdIP->text();
        if(strTempIp=="...") {
            QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input IP address!"));
            return;
        } else if(! isTextValid(strTempIp)) {
            QMessageBox::warning(gMainWin, tr("Attention"), tr("Your IP Address is Invalid!"));
            return;
        }
        auto waitingDlg = new WaitingDlg(gMainWin, tr("Search")+" ...");
        waitingDlg->show();
        auto reply = Tools::netManager().get(reqForJson("http://"+strTempIp+":3000/deviceList?fromDetector=true"));
        //在该ip的3000端口get方法deviceList，可以一次性获取到局域网中设备列表的详细信息
        connect(reply, &QNetworkReply::finished, this, [reply, this, waitingDlg] {
            QJsonDocument json;
            QString err = parseReplyJson(reply);
            if(! err.isEmpty()) {
                waitingDlg->close();
                QMessageBox::critical(gMainWin, tr("Error"), err);
                return;
            }
            waitingDlg->success();
            close();
            QStringList keys = json.object().keys();
            qDebug()<<"json size"<<keys.size();
            for(auto key : keys) gDevicePanel->parseInfo(json[key].toObject(), "");
        });
    });
}
