#include "ctrlnetworkpanel.h"
#include "base/waitingdlg.h"
#include "globaldefine.h"
#include "tools.h"
#include "gutil/qgui.h"
#include <QJsonArray>
#include <QMessageBox>
#include <QStackedLayout>
#include <QGridLayout>

CtrlNetworkPanel::CtrlNetworkPanel(QWidget *parent) : QWidget(parent) {
    auto vBox = new VBox(this);

    lbLanCfg = new QLabel;
    QFont font = lbLanCfg->font();
    font.setPixelSize(16);
    lbLanCfg->setFont(font);
    lbLanCfg->setAlignment(Qt::AlignCenter);
    vBox->addWidget(lbLanCfg);

    auto hBox = new HBox(vBox);
    hBox->addStretch();

    fdDhcp = new QRadioButton;
    fdDhcp->setChecked(true);
    hBox->addWidget(fdDhcp, 0, Qt::AlignTop);

    hBox->addSpacing(30);

    auto vBoxSpecifyIp = new VBox(hBox);
    vBoxSpecifyIp->setContentsMargins(0, 0, 0, 0);

    fdSpecifyIp = new QRadioButton;
    vBoxSpecifyIp->addWidget(fdSpecifyIp, 0, Qt::AlignCenter);

    auto grp = new QButtonGroup(this);
    grp->addButton(fdDhcp);
    grp->addButton(fdSpecifyIp);

    gBoxSpecifyIp = new QGroupBox;
    gBoxSpecifyIp->setMaximumWidth(340);
    gBoxSpecifyIp->setVisible(false);
    connect(fdSpecifyIp, &QRadioButton::toggled, gBoxSpecifyIp, &QWidget::setVisible);
    {
        auto vvv = new VBox(gBoxSpecifyIp);
        auto hhh = new HBox(vvv);

        hhh->addWidget(labelIpAddress = new QLabel);

        fdIP = new QLineEdit;
        fdIP->setInputMask("000.000.000.000;_");
        fdIP->setAlignment(Qt::AlignCenter);
        fdIP->setFixedWidth(160);
        hhh->addWidget(fdIP);

        hhh = new HBox(vvv);

        hhh->addWidget(labelMaskAddress = new QLabel);

        fdMask = new QLineEdit;
        fdMask->setInputMask("000.000.000.000;_");
        fdMask->setAlignment(Qt::AlignCenter);
        fdMask->setFixedWidth(160);
        hhh->addWidget(fdMask);

        hhh = new HBox(vvv);

        hhh->addWidget(labelGateway = new QLabel);

        fdGateWay = new QLineEdit;
        fdGateWay->setInputMask("000.000.000.000;_");
        fdGateWay->setAlignment(Qt::AlignCenter);
        fdGateWay->setFixedWidth(160);
        hhh->addWidget(fdGateWay);

        hhh = new HBox(vvv);

        hhh->addWidget(labelDnsAddress = new QLabel);

        fdDns = new QLineEdit;
        fdDns->setInputMask("000.000.000.000;_");
        fdDns->setAlignment(Qt::AlignCenter);
        fdDns->setFixedWidth(160);
        hhh->addWidget(fdDns);
    }
    vBoxSpecifyIp->addWidget(gBoxSpecifyIp);

    hBox->addStretch();

    hBox = new HBox(vBox);
    hBox->addStretch();

    btnLanSet = new QPushButton;
    btnLanSet->setMinimumSize(QSize(60, 30));
    btnLanSet->setProperty("ssType", "progManageTool");
    connect(btnLanSet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QString ip = fdIP->text();
        QString mask = fdMask->text();
        QString gateWay = fdGateWay->text();
        QString dns = fdDns->text();
        if(fdDhcp->isChecked()) {
            if(ip=="...") ip = "0.255.255.255";
            if(mask=="...") mask = "0.255.255.255";
            if(gateWay=="...") gateWay = "0.255.255.255";
            if(dns=="...") dns = "0.255.255.255";
        } else {
            if(ip=="...") {
                QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input IP address!"));
                fdIP->setFocus();
                return;
            }
            if(mask=="...") {
               QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input Mask address!"));
                fdMask->setFocus();
                return;
            }
            if(gateWay=="...") {
               QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input Gateway address!"));
                fdGateWay->setFocus();
                return;
            }
            if(dns=="...") {
               QMessageBox::warning(gMainWin, tr("Attention"), tr("Please input DNS address!"));
                fdDns->setFocus();
                return;
            }
        }
        QJsonObject json;
        json.insert("_id", "SetEthernet");
        json.insert("_type", "SetEthernet");
        json.insert("dhcp", fdDhcp->isChecked());
        json.insert("ip", ip);
        json.insert("netMask", mask);
        json.insert("gateWay", gateWay);
        json.insert("dns", dns);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetEthernet"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("SetEthernet"))
            }
        }
    });
    hBox->addWidget(btnLanSet);

    hBox->addSpacing(50);

    btnLanGet = new QPushButton;
    btnLanGet->setMinimumSize(QSize(60, 30));
    btnLanGet->setProperty("ssType", "progManageTool");
    connect(btnLanGet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "GetEthernet");
        json.insert("_type", "GetEthernet");
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("GetEthernet"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                Def_CtrlSingleGetReply
                waitingDlg->success();
                if(json["dhcp"].toBool()) {
                    fdDhcp->setChecked(true);
                    gBoxSpecifyIp->setVisible(false);
                } else {
                    fdSpecifyIp->setChecked(true);
                    gBoxSpecifyIp->setVisible(true);
                }
                fdIP->setText(json["ipAddr"].toString());
                fdMask->setText(json["netMask"].toString());
                fdGateWay->setText(json["gateWay"].toString());
                fdDns->setText(json["dnsAddr"].toString());
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                auto cardId = card->m_strCardId;
                connect(reply, &QNetworkReply::finished, this, [reply, cardId] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    if(err.isEmpty()) err = json["dhcp"].toBool() ? tr("DHCP IP") : tr("STATIC IP");
                    gFdResInfo->append(cardId+" "+tr("GetEthernet")+" "+err);
                    gFdResInfo->append("  IP: "+json["ipAddr"].toString());
                    gFdResInfo->append("  Mask: "+json["netMask"].toString());
                    gFdResInfo->append("  GateWay: "+json["gateWay"].toString());
                    gFdResInfo->append("  Dns: "+json["dnsAddr"].toString());
                });
            }
        }
    });
    hBox->addWidget(btnLanGet);

    hBox->addStretch();

    auto line = new QFrame;
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    vBox->addWidget(line);

    label_5 = new QLabel;
    label_5->setFont(font);
    label_5->setAlignment(Qt::AlignCenter);
    vBox->addWidget(label_5);

    hBox = new HBox(vBox);
    hBox->addStretch();

    auto stackedWifi = new QStackedLayout;
    fdIsWifi = new QRadioButton;
    connect(fdIsWifi, &QRadioButton::toggled, this, [stackedWifi](bool checked) {
        stackedWifi->setCurrentIndex(checked ? 0 : 1);
    });
    hBox->addWidget(fdIsWifi);
    hBox->addSpacing(50);

    fdIsHotspot = new QRadioButton;
    hBox->addWidget(fdIsHotspot);
    hBox->addStretch();

    vBox->addLayout(stackedWifi);
    {
        auto vvv = new VBox(stackedWifi);
        hBox = new HBox(vvv);

        lbWifiName = new QLabel;
        lbWifiName->setMinimumWidth(80);
        hBox->addWidget(lbWifiName);

        fdWifiName = new QComboBox;
        fdWifiName->setEditable(true);
        fdWifiName->setMinimumWidth(200);
        fdWifiName->setSizeAdjustPolicy(QComboBox::AdjustToContents);
        hBox->addWidget(fdWifiName);

        btnScan = new QPushButton;
        btnScan->setMinimumWidth(60);
        btnScan->setProperty("ssType", "progManageTool");
        connect(btnScan, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetWifiList");
            json.insert("_type", "GetWifiList");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("GetWifiList")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                    Def_CtrlSingleGetReply
                    waitingDlg->success();
                    auto wifis = json["wifiList"].toArray();
                    auto cur = fdWifiName->currentText();
                    fdWifiName->clear();
                    foreach(QJsonValue wifi, wifis) fdWifiName->addItem(QIcon(":/res/signal-"+QString::number((wifi["signal"].toInt()+19)/20)+".png"), wifi["ssid"].toString());
                    if(! cur.isEmpty()) fdWifiName->setCurrentText(cur);
                });
            }
        });
        hBox->addWidget(btnScan);
        hBox->addStretch();

        hBox = new HBox(vvv);

        lbWifiPassword = new QLabel;
        lbWifiPassword->setMinimumWidth(80);
        hBox->addWidget(lbWifiPassword);

        fdWifiPassword = new QLineEdit;
        fdWifiPassword->setFixedWidth(200);
        fdWifiPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit);
        hBox->addWidget(fdWifiPassword);
        hBox->addStretch();

        vvv->addStretch();

        vvv = new VBox(stackedWifi);
        hBox = new HBox(vvv);

        lbHotspotName = new QLabel;
        lbHotspotName->setMinimumWidth(80);
        hBox->addWidget(lbHotspotName);

        fdHotspotName = new QLineEdit;
        fdHotspotName->setFixedWidth(200);
        hBox->addWidget(fdHotspotName);
        hBox->addStretch();

        hBox = new HBox(vvv);

        lbHotspotPassword = new QLabel;
        lbHotspotPassword->setMinimumWidth(80);
        hBox->addWidget(lbHotspotPassword);

        fdHotspotPassword = new QLineEdit;
        fdHotspotPassword->setEchoMode(QLineEdit::PasswordEchoOnEdit);
        fdHotspotPassword->setFixedWidth(200);
        hBox->addWidget(fdHotspotPassword);
        hBox->addStretch();

        vvv->addStretch();
    }
    fdIsWifi->setChecked(true);

    hBox = new HBox(vBox);
    hBox->addStretch();

    btnWiFiSet = new QPushButton;
    btnWiFiSet->setMinimumSize(QSize(60, 30));
    btnWiFiSet->setProperty("ssType", "progManageTool");
    connect(btnWiFiSet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        if(fdIsWifi->isChecked()) {
            QJsonObject json;
            json.insert("_id", "ConfigurationWiFi");
            json.insert("_type", "ConfigurationWiFi");
            json.insert("ssid", fdWifiName->currentText());
            json.insert("password", fdWifiPassword->text());
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("ConfigurationWiFi")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("ConfigurationWiFi"))
                }
            }
        } else if(fdIsHotspot->isChecked()) {
            QJsonObject json;
            json.insert("_id", "ConfigurationHotSpot");
            json.insert("_type", "ConfigurationHotSpot");
            json.insert("apName", fdHotspotName->text());
            json.insert("password", fdHotspotPassword->text());
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("ConfigurationHotSpot")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("ConfigurationHotSpot"))
                }
            }
        }
    });
    hBox->addWidget(btnWiFiSet);
    hBox->addSpacing(50);

    btnWiFiGet = new QPushButton;
    btnWiFiGet->setMinimumSize(QSize(60, 30));
    btnWiFiGet->setProperty("ssType", "progManageTool");
    connect(btnWiFiGet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "IsPortableHotSpot");
        json.insert("_type", "IsPortableHotSpot");
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("IsPortableHotSpot")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                Def_CtrlSingleGetReply
                waitingDlg->success();
                fdWifiName->setCurrentText(json["wifi"].toString());
                auto hotSpots = json["hotSpots"].toString();
                fdHotspotName->setText(hotSpots);
                if(hotSpots.isEmpty()) fdIsWifi->setChecked(true);
                else fdIsHotspot->setChecked(true);
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                auto cardId = card->m_strCardId;
                connect(reply, &QNetworkReply::finished, this, [reply, cardId] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    if(err.isEmpty()) {
                        err = tr("success");
                        auto wifi = json["wifi"].toString();
                        if(! wifi.isEmpty()) err += " "+tr("WifiName")+":"+wifi;
                        auto hotSpots = json["hotSpots"].toString();
                        if(! hotSpots.isEmpty()) err += " "+tr("ApName")+":"+hotSpots;
                    }
                    gFdResInfo->append(cardId+" "+tr("IsPortableHotSpot")+" "+err);
                });
            }
        }
    });
    hBox->addWidget(btnWiFiGet);

    hBox->addStretch();


    line_3 = new QFrame;
    line_3->setFrameShape(QFrame::HLine);
    line_3->setFrameShadow(QFrame::Sunken);

    vBox->addWidget(line_3);

    lbCellularConfig = new QLabel;
    lbCellularConfig->setFont(font);

    vBox->addWidget(lbCellularConfig, 0, Qt::AlignHCenter);

    hBox = new HBox(vBox);

    fdEnableCellular = new QCheckBox;
    fdEnableCellular->setChecked(true);
    connect(fdEnableCellular, &QCheckBox::toggled, this, [=](bool checked) {
        groupApn->setEnabled(checked);
        fdMcc->setEnabled(checked);
        fdCarrierName->setEnabled(checked);

        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "SetSwitchSimData");
        json.insert("_type", "SetSwitchSimData");
        json.insert("enable", checked);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetSwitchSimData")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("SetSwitchSimData"))
            }
        }
    });
    hBox->addWidget(fdEnableCellular);

    btnSIMStatusGet = new QPushButton;
    btnSIMStatusGet->setMinimumHeight(30);
    btnSIMStatusGet->setProperty("ssType", "progManageTool");
    connect(btnSIMStatusGet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "GetSIMStatus");
        json.insert("_type", "GetSIMStatus");
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("GetSIMStatus")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                Def_CtrlSingleGetReply
                waitingDlg->close();
                QString str4GStatus = tr("状态:");
                auto state = json["state"].toInt();
                if(state<2) str4GStatus += tr("未知");
                else if(state==2) str4GStatus += tr("锁定状态，需要用户的PIN码解锁");
                else if(state==3) str4GStatus += tr("锁定状态，需要用户的PUK码解锁");
                else if(state==4) str4GStatus += tr("锁定状态，需要网络的PIN码解锁");
                else if(state==5) str4GStatus += tr("就绪");
                auto imsi = json["imsi"].toString();
                if(imsi.isEmpty()) str4GStatus += "\n"+tr("no checked sim card");
                else {
                    str4GStatus += "\nIMSI: "+imsi+"\n";
                    fdMcc->setCurrentText(imsi.left(3));
                    str4GStatus += tr("国家码:") + json["countryCode"].toString() + "(" + imsi.left(3) + ")\n";
                    str4GStatus += tr("号码:") + json["phoneNumber"].toString() + "\n";
                    str4GStatus += tr("用户:") + json["user"].toString() + "\n";
                    str4GStatus += tr("信号:");
                    switch(json["serviceState"].toInt()) {
                        case 0:                    str4GStatus+=tr("信号正常")+"\r\n";                    break;
                        case 1:                    str4GStatus+=tr("不在服务区")+"\r\n";                    break;
                        case 2:                    str4GStatus+=tr("仅限紧急呼叫")+"\r\n";                    break;
                        case 3:                    str4GStatus+=tr("射频已经关闭")+"\r\n";                    break;
                    }
                    str4GStatus += tr("网络:");
                    switch(json["networkType"].toInt()) {
                        case 0:                    str4GStatus+=tr("网络类型未知")+"\r\n";                    break;
                        case 1:                    str4GStatus+=tr("GPRS网络")+"\r\n";                    break;
                        case 2:                    str4GStatus+=tr("EDGE网络")+"\r\n";                    break;
                        case 3:                    str4GStatus+=tr("UMTS网络")+"\r\n";                    break;
                        case 4:                    str4GStatus+=tr("CDMA网络,IS95A 或 IS95B.")+"\r\n";                    break;
                        case 5:                    str4GStatus+=tr("EVDO网络, revision 0.")+"\r\n";                    break;
                        case 6:                    str4GStatus+=tr("EVDO网络, revision A.")+"\r\n";                    break;
                        case 7:                    str4GStatus+=tr("1xRTT网络")+"\r\n";                    break;
                        case 8:                    str4GStatus+=tr("HSDPA网络")+"\r\n";                    break;
                        case 9:                    str4GStatus+=tr("HSUPA网络")+"\r\n";                    break;
                        case 10:                    str4GStatus+=tr("HSPA网络")+"\r\n";                    break;
                    }
                    str4GStatus += tr("漫游:") + (json["roaming"].toBool() ? tr("Yes") : tr("No")) + "\n";
                    str4GStatus += tr("数据连接状态:");
                    switch(json["dataState"].toInt()) {
                        case 0:                    str4GStatus+=tr("断开")+"\r\n";                    break;
                        case 1:                    str4GStatus+=tr("正在连接")+"\r\n";                    break;
                        case 2:                    str4GStatus+=tr("已连接")+"\r\n";                    break;
                        case 3:                    str4GStatus+=tr("暂停")+"\r\n";                    break;
                    }
                    str4GStatus += tr("数据活动休眠状态:");
                    switch(json["dataActivity"].toInt()) {
                        case 0:                    str4GStatus+=tr("活动，但无数据发送和接收")+"\r\n";                    break;
                        case 1:                    str4GStatus+=tr("活动，正在接收数据")+"\r\n";                    break;
                        case 2:                    str4GStatus+=tr("活动，正在发送数据")+"\r\n";                    break;
                        case 3:                    str4GStatus+=tr("活动，正在接收和发送数据")+"\r\n";                    break;
                        case 4:                    str4GStatus+=tr("休眠状态")+"\r\n";                    break;
                    }
                    str4GStatus += tr("信号强度:") + QString::number(json["signalStrength"].toInt())+"\n";
                }
                QMessageBox::information(gMainWin, tr("Tip"), str4GStatus);
            });
        }
    });
    hBox->addWidget(btnSIMStatusGet);
    hBox->addStretch();

    groupApn = new QGroupBox;
    vBox->addWidget(groupApn);
    auto vvv = new VBox(groupApn);

    lbCheckStatusTip = new QLabel(groupApn);
    lbCheckStatusTip->setWordWrap(true);
    vvv->addWidget(lbCheckStatusTip);

    hBox = new HBox(vvv);

    label_2 = new QLabel(groupApn);
    hBox->addWidget(label_2);

    fdMcc = new QComboBox;
    fdMcc->setMinimumWidth(80);
    fdMcc->setEditable(true);
    connect(fdMcc, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [=](int index) {
        if(index < 1) return;
        fdCarrierName->clear();
        fdCarrierName->addItem("");
        auto apnInfos = fdMcc->itemData(index).toJsonArray();
        foreach(QJsonValue apnInfo, apnInfos) fdCarrierName->addItem(apnInfo["carrier"].toString(), apnInfo);
    });
    hBox->addWidget(fdMcc);

    hBox->addWidget(new QLabel("->"));

    label_3 = new QLabel(groupApn);
    hBox->addWidget(label_3);

    fdCarrierName = new QComboBox;
    fdCarrierName->setMinimumSize(QSize(200, 0));
    fdCarrierName->setEditable(true);
    connect(fdCarrierName, (void(QComboBox::*)(int))&QComboBox::currentIndexChanged, this, [=](int index) {
        if(index < 1) return;
        auto json = fdCarrierName->itemData(index).toJsonObject();
        fdCus_Name->setText(json["carrier"].toString());
        fdCus_apn->setText(json["apn"].toString());
        fdCus_User->setText(json["user"].toString());
        fdCus_pwd->setText(json["password"].toString());
        fdCus_type->setText(json["type"].toString());
        fdCus_server->setText(json["server"].toString());
        fdCus_proxy->setText(json["proxy"].toString());
        fdCus_port->setText(json["port"].toString());
        fdCus_mmsc->setText(json["mmsc"].toString());
        fdCus_mmsProxy->setText(json["mmsproxy"].toString());
        fdCus_mmsPort->setText(json["mmsport"].toString());
    });
    hBox->addWidget(fdCarrierName);

    hBox->addStretch();

    hBox = new HBox(vvv);
    hBox->addStretch();

    auto grid = new QGridLayout();
    hBox->addLayout(grid);

    auto label = new QLabel("APN");
    label->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(label, 0, 0);
    grid->addWidget(lbCus_Name = new QLabel, 1, 0);
    lbCus_Name->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_User = new QLabel, 2, 0);
    lbCus_User->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_pwd = new QLabel, 3, 0);
    lbCus_pwd->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_type = new QLabel, 4, 0);
    lbCus_type->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_server = new QLabel, 5, 0);
    lbCus_server->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_port = new QLabel, 0, 2);
    lbCus_port->setMinimumWidth(80);
    lbCus_port->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_proxy = new QLabel, 1, 2);
    lbCus_proxy->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(label = new QLabel("mmsc"), 2, 2);
    label->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_mmsPort = new QLabel, 3, 2);
    lbCus_mmsPort->setAlignment((Qt::Alignment)AlignRight);
    grid->addWidget(lbCus_mmsProxy = new QLabel, 4, 2);
    lbCus_mmsProxy->setAlignment((Qt::Alignment)AlignRight);

    fdCus_apn = new QLineEdit;
    fdCus_Name = new QLineEdit;
    fdCus_User = new QLineEdit;
    fdCus_pwd = new QLineEdit;
    fdCus_type = new QLineEdit;
    fdCus_server = new QLineEdit;
    fdCus_port = new QLineEdit;
    fdCus_proxy = new QLineEdit;
    fdCus_mmsc = new QLineEdit;
    fdCus_mmsPort = new QLineEdit;
    fdCus_mmsProxy = new QLineEdit;

    fdCus_apn->setMinimumWidth(260);
    fdCus_port->setMinimumWidth(260);
    grid->addWidget(fdCus_apn, 0, 1);
    grid->addWidget(fdCus_Name, 1, 1);
    grid->addWidget(fdCus_User, 2, 1);
    grid->addWidget(fdCus_pwd, 3, 1);
    grid->addWidget(fdCus_type, 4, 1);
    grid->addWidget(fdCus_server, 5, 1);
    grid->addWidget(fdCus_port, 0, 3);
    grid->addWidget(fdCus_proxy, 1, 3);
    grid->addWidget(fdCus_mmsc, 2, 3);
    grid->addWidget(fdCus_mmsPort, 3, 3);
    grid->addWidget(fdCus_mmsProxy, 4, 3);

    auto hhhh = new HBox;
    btnAPNCusSet = new QPushButton;
    btnAPNCusSet->setMinimumSize(QSize(60, 30));
    btnAPNCusSet->setProperty("ssType", "progManageTool");
    connect(btnAPNCusSet, &QPushButton::clicked, this, [=] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "SetAPN");
        json.insert("_type", "SetAPN");
        json.insert("carrier", fdCus_Name->text());
        json.insert("apn", fdCus_apn->text());
        json.insert("user", fdCus_User->text());
        json.insert("password", fdCus_pwd->text());
        json.insert("type", fdCus_type->text());
        json.insert("server", fdCus_server->text());
        json.insert("proxy", fdCus_proxy->text());
        json.insert("port", fdCus_port->text());
        json.insert("mmsc", fdCus_mmsc->text());
        json.insert("mmsproxy", fdCus_mmsProxy->text());
        json.insert("mmsport", fdCus_mmsPort->text());

        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetAPN")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [=] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("SetAPN"))
            }
        }
    });
    hhhh->addWidget(btnAPNCusSet);
    hhhh->addStretch();

    btnAPNCusGet = new QPushButton;
    btnAPNCusGet->setMinimumSize(QSize(60, 30));
    btnAPNCusGet->setProperty("ssType", "progManageTool");
    connect(btnAPNCusGet, &QPushButton::clicked, this, [=] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "GetCurrentAPN");
        json.insert("_type", "GetCurrentAPN");
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("GetCurrentAPN")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [=] {
                Def_CtrlSingleGetReply
                waitingDlg->success();
                fdCus_Name->setText(json["carrier"].toString());
                fdCus_apn->setText(json["apn"].toString());
                fdCus_User->setText(json["user"].toString());
                fdCus_pwd->setText(json["password"].toString());
                fdCus_type->setText(json["type"].toString());
                fdCus_server->setText(json["server"].toString());
                fdCus_proxy->setText(json["proxy"].toString());
                fdCus_port->setText(json["port"].toString());
                fdCus_mmsc->setText(json["mmsc"].toString());
                fdCus_mmsProxy->setText(json["mmsproxy"].toString());
                fdCus_mmsPort->setText(json["mmsport"].toString());
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                auto cardId = card->m_strCardId;
                connect(reply, &QNetworkReply::finished, this, [reply, cardId] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    if(err.isEmpty()) {
                        err = json["apn"].toString();
                        auto user = json["user"].toString();
                        if(! user.isEmpty()) err += ", User:"+user+", Password:"+json["password"].toString();
                    }
                    gFdResInfo->append(cardId+" "+tr("GetCurrentAPN")+" "+err);
                });
            }
        }
    });
    hhhh->addWidget(btnAPNCusGet);

    grid->addLayout(hhhh, 5, 3);

    hBox->addStretch();


    vBox->addSpacing(20);

    hBox = new HBox(vBox);
    hBox->setContentsMargins(-1, 0, 10, -1);
    label_10 = new QLabel;

    hBox->addWidget(label_10);

    fdFightModel = new SwitchControl;
    fdFightModel->setMinimumSize(QSize(80, 35));
    fdFightModel->setSliderColor(QColor(0, 0, 0),QColor(0, 160, 230));
    fdFightModel->setBgColor(QColor(200,200,200),QColor(0,200,0));
    fdFightModel->setTextColor(QColor(100,100,100),QColor(0, 160, 230));
    fdFightModel->setText(tr("OFF"), tr("ON"));
    connect(fdFightModel, &SwitchControl::checkedChanged, this, [=](bool checked) {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "ContrFlightMode");
        json.insert("_type", "ContrFlightMode");
        json.insert("state", checked);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("ContrFlightMode")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("ContrFlightMode"))
            }
        }
    });
    hBox->addWidget(fdFightModel);

    btnFlightModelGet = new QPushButton;
    btnFlightModelGet->setMinimumSize(QSize(0, 30));
    btnFlightModelGet->setProperty("ssType", "progManageTool");
    connect(btnFlightModelGet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "GetFlightModeState");
        json.insert("_type", "GetFlightModeState");
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("GetFlightModeState")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                Def_CtrlSingleGetReply
                waitingDlg->success();
                fdFightModel->setCheckedStatus(json["result"].toBool());
                fdFightModel->update();
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                auto cardId = card->m_strCardId;
                connect(reply, &QNetworkReply::finished, this, [reply, cardId] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    if(err.isEmpty()) err = json["result"].toBool() ? "true" : "false";
                    gFdResInfo->append(cardId+" "+tr("GetFlightModeState")+" "+err);
                });
            }
        }
    });
    hBox->addWidget(btnFlightModelGet);
    hBox->addStretch();

    vBox->addStretch();

    connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] {
        if(isVisible()) init();
    });
    transUi();
}

void CtrlNetworkPanel::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    init();
}
void CtrlNetworkPanel::init() {
    bool isSingle = gSelCards->count()==1;
    btnScan->setEnabled(isSingle);

    if(! isSingle) return;
    auto card = gSelCards->at(0);

    QJsonObject json;
    json.insert("_id", "GetEthernet");
    json.insert("_type", "GetEthernet");
    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [this, reply] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;

        if(json["dhcp"].toBool()) {
            fdDhcp->setChecked(true);
            gBoxSpecifyIp->setVisible(false);
        } else {
            fdSpecifyIp->setChecked(true);
            gBoxSpecifyIp->setVisible(true);
        }
        fdIP->setText(json["ipAddr"].toString());
        fdGateWay->setText(json["gateWay"].toString());
        fdMask->setText(json["netMask"].toString());
        fdDns->setText(json["dnsAddr"].toString());
    });

    json = QJsonObject();
    json.insert("_id", "GetWifiList");
    json.insert("_type", "GetWifiList");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        auto wifis = json["wifiList"].toArray();
        fdWifiName->clear();
        foreach(QJsonValue wifi, wifis) fdWifiName->addItem(QIcon(":/res/signal-"+QString::number((wifi["signal"].toInt()+19)/20)+".png"), wifi["ssid"].toString());
        {
            QJsonObject json;
            json.insert("_id", "IsPortableHotSpot");
            json.insert("_type", "IsPortableHotSpot");
            auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
            connect(reply, &QNetworkReply::finished, this, [this, reply] {
                QJsonDocument json;
                QString err = checkReplyForJson(reply, &json);
                if(! err.isEmpty()) return;
                auto wifi = json["wifi"].toString();
                fdWifiName->setCurrentText(wifi);
                auto hotSpots = json["hotSpots"].toString();
                fdHotspotName->setText(hotSpots);
                if(hotSpots.isEmpty()) fdIsWifi->setChecked(true);
                else fdIsHotspot->setChecked(true);
            });
        }
    });

    json = QJsonObject();
    json.insert("_id", "GetSwitchSimData");
    json.insert("_type", "GetSwitchSimData");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        bool b = json["enable"].toBool();
        fdEnableCellular->setChecked(b);
        fdMcc->setEnabled(b);
        fdCarrierName->setEnabled(b);
    });

    json = QJsonObject();
    json.insert("_id", "GetAPNList");
    json.insert("_type", "GetAPNList");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        fdMcc->clear();
        fdMcc->addItem("");
        auto apns = json["apns"].toArray();
        foreach(QJsonValue apn, apns) {
            QString mcc = apn["mcc"].toString();
            for(int i=0; i<fdMcc->count(); i++) if(mcc==fdMcc->itemText(i)) {
                auto var = fdMcc->itemData(i);
                fdMcc->setItemData(i, QVariant());
                ((QJsonArray *)var.data())->append(apn);
                fdMcc->setItemData(i, var);
                goto end;
            }
            fdMcc->addItem(mcc, QJsonArray{apn});
            end:;
        }
    });

    getCurrentAPN(card->m_strCardIp);

    json = QJsonObject();
    json.insert("_id", "GetFlightModeState");
    json.insert("_type", "GetFlightModeState");
    reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        fdFightModel->setCheckedStatus(json["result"].toBool());
        fdFightModel->update();
    });
}

void CtrlNetworkPanel::changeEvent(QEvent *event) {
    QWidget::changeEvent(event);
    if(event->type() == QEvent::LanguageChange) transUi();
}
void CtrlNetworkPanel::transUi() {
    lbLanCfg->setText(tr("Wire Enther(RJ45) Configuration"));
    fdDhcp->setText(tr("DHCP"));
    fdSpecifyIp->setText(tr("Specify IP"));
    lbHotspotName->setText(tr("AP name"));
    labelGateway->setText(tr("Gateway"));
    lbWifiName->setText(tr("WiFi name"));
    labelIpAddress->setText(tr("IP Address"));
    lbHotspotPassword->setText(tr("Password"));
    labelDnsAddress->setText(tr("DNS Address"));
    labelMaskAddress->setText(tr("Subnet mask"));
    lbWifiPassword->setText(tr("Password"));
    btnScan->setText(tr("Scan"));
    btnWiFiSet->setText(tr("Set"));
    btnLanSet->setText(tr("Set"));
    btnWiFiGet->setText(tr("Readback"));
    btnLanGet->setText(tr("Readback"));
    fdIsWifi->setText(tr("WiFi Mode"));
    fdIsHotspot->setText(tr("Ap Mode"));
    label_5->setText(tr("WIFI Configuration"));
    fdHotspotPassword->setPlaceholderText(tr("Input password"));
    fdWifiPassword->setPlaceholderText(tr("Input password"));
    fdHotspotName->setPlaceholderText(tr("Input ap name"));
    lbCellularConfig->setText(tr("Cellular Config"));
    lbCheckStatusTip->setText(tr("Through the check status button"));
    fdEnableCellular->setText(tr("Enable Cellular Data"));

    groupApn->setTitle(tr("Set APN Info"));
    label_2->setText(tr("Country ID(mcc):"));
    label_3->setText(tr("Carrier Name"));
    fdCus_apn->setPlaceholderText(tr("APN(Required)"));
    btnFlightModelGet->setText(tr("Readback"));
    btnSIMStatusGet->setText(tr("Get cellular network status information"));
    label_10->setText(tr("Flight Mode"));

    lbCus_Name->setText(tr("Carrier Name"));
    lbCus_User->setText(tr("User"));
    lbCus_pwd->setText(tr("Password"));
    lbCus_type->setText(tr("Type"));
    lbCus_server->setText(tr("Server"));
    lbCus_port->setText(tr("Port"));
    lbCus_proxy->setText(tr("Proxy"));
    lbCus_mmsPort->setText(tr("MMS Port"));
    lbCus_mmsProxy->setText(tr("MMS Proxy"));
    btnAPNCusSet->setText(tr("Set"));
    btnAPNCusGet->setText(tr("Readback"));
}

void CtrlNetworkPanel::getCurrentAPN(QString &ip) {
    QJsonObject json;
    json.insert("_id", "GetCurrentAPN");
    json.insert("_type", "GetCurrentAPN");
    auto reply = Tools::netManager().post(reqForJson("http://"+ip+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        fdCus_Name->setText(json["carrier"].toString());
        fdCus_apn->setText(json["apn"].toString());
        fdCus_User->setText(json["user"].toString());
        fdCus_pwd->setText(json["password"].toString());
        fdCus_type->setText(json["type"].toString());
        fdCus_server->setText(json["server"].toString());
        fdCus_proxy->setText(json["proxy"].toString());
        fdCus_port->setText(json["port"].toString());
        fdCus_mmsc->setText(json["mmsc"].toString());
        fdCus_mmsProxy->setText(json["mmsproxy"].toString());
        fdCus_mmsPort->setText(json["mmsport"].toString());
    });
}
