#include "ctrladvancedpanel.h"
#include "deviceitem.h"
#include "globaldefine.h"
#include "base/waitingdlg.h"
#include "base/changepasswordform.h"
#include "base/updateledset3dialog.h"
#include "passwordindlg.h"
#include "tools.h"
#include "wProgramManager/ephoto.h"
#include "upgradeapkdialog.h"
#include "base/table.h"
#include <QBoxLayout>
#include <QComboBox>
#include <QFileDialog>
#include <QJsonArray>
#include <QJsonObject>
#include <QKeyEvent>
#include <QMap>
#include <QMessageBox>
#include <QMetaEnum>
#include <QProcess>
#include <QSettings>
#include <QTextCodec>
#include <QUuid>
#include <QHeaderView>
#include <QColorDialog>
#include "tcpsocket.h"

CtrlAdvancedPanel::CtrlAdvancedPanel(QWidget *parent,QList<LedCard *> *list) : QWidget(parent), m_pLedlist(list) {
    m_pLedlist = gSelCards;
    setFocusPolicy(Qt::StrongFocus);
    auto vBox = new QVBoxLayout(this);

    lbTitle = new QLabel;
    lbTitle->setAlignment(Qt::AlignCenter);
    vBox->addWidget(lbTitle);

    auto hBox = new QHBoxLayout;

    lbScreenWidth = new QLabel;
    hBox->addWidget(lbScreenWidth);

    fdScreenWidth = new QLineEdit;
    fdScreenWidth->setMaximumWidth(60);
    hBox->addWidget(fdScreenWidth);

    lbScreenHeight = new QLabel;
    hBox->addWidget(lbScreenHeight);

    fdScreenHeight = new QLineEdit;
    fdScreenHeight->setMaximumWidth(60);
    hBox->addWidget(fdScreenHeight);

    btnScreenSet = new QPushButton;
    btnScreenSet->setProperty("ssType", "progManageTool");
    connect(btnScreenSet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        auto width = fdScreenWidth->text();
        if(width.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("InputWidthTip"));
            fdScreenWidth->setFocus();
            return;
        }
        auto height = fdScreenHeight->text();
        if(height.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("InputHeightTip"));
            fdScreenHeight->setFocus();
            return;
        }
        QJsonObject json;
        json.insert("_id", "SetScreenSize");
        json.insert("_type", "SetScreenSize");
        json.insert("width", width.toInt());
        json.insert("height", height.toInt());
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetScreenSize"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("SetScreenSize"))
            }
        }
    });
    hBox->addWidget(btnScreenSet);

    hBox->addSpacing(20);

    lbAlias = new QLabel;
    hBox->addWidget(lbAlias);

    fdAlias = new QLineEdit;
    fdAlias->setMaximumWidth(200);
    hBox->addWidget(fdAlias);

    btnAliasSet = new QPushButton;
    btnAliasSet->setProperty("ssType", "progManageTool");
    connect(btnAliasSet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        auto alias = fdAlias->text();
        if(alias.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("InputAliasTip"));
            fdAlias->setFocus();
            return;
        }
        QJsonObject json;
        json.insert("_id", "SetCardAlias");
        json.insert("_type", "SetCardAlias");
        json.insert("alias", QString::fromLatin1(alias.toUtf8().toBase64()));
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetCardAlias"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("SetCardAlias"))
            }
        }
    });
    hBox->addWidget(btnAliasSet);

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

    hBox = new QHBoxLayout();

    labelWebServer = new QLabel;
    hBox->addWidget(labelWebServer);

    fdWebServerAddr = new QComboBox;
    fdWebServerAddr->addItem(tr("www.m2mled.net"));
    fdWebServerAddr->addItem(tr("www.ledaips.com"));
    fdWebServerAddr->addItem(tr("https://www.taxihub.cn:2340"));
    fdWebServerAddr->addItem(tr("https://www.ledaips.com:2340"));
    fdWebServerAddr->addItem(tr("https://www.36taxi.com:2340"));
    fdWebServerAddr->addItem(tr("www.tlzxled.com"));
    fdWebServerAddr->setMinimumWidth(260);
    fdWebServerAddr->setEditable(true);
    hBox->addWidget(fdWebServerAddr);

    lbCompanyId = new QLabel;
    hBox->addWidget(lbCompanyId);

    fdCompanyId = new QLineEdit;
    fdCompanyId->setFixedWidth(100);
    hBox->addWidget(fdCompanyId);

    btnWebServerSet = new QPushButton;
    btnWebServerSet->setProperty("ssType", "progManageTool");
    connect(btnWebServerSet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }

        QString serverAddr = fdWebServerAddr->currentText();
        if(serverAddr.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("InputWebServerAddressTip"));
            fdWebServerAddr->setFocus();
            return;
        }
        auto companyId = fdCompanyId->text();
        if(companyId.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("InputCompanyIdTip"));
            fdCompanyId->setFocus();
            return;
        }
        auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Do you want to modify webserveraddress and companyId?"));
        if(res != QMessageBox::Yes) return;
        QJsonObject json;
        json.insert("_id", "SetOnlineAddr");
        json.insert("_type", "SetOnlineAddr");
        json.insert("server", serverAddr);
        json.insert("companyID", companyId);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetOnlineAddr"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("SetOnlineAddr"))
            }
        }
    });
    hBox->addWidget(btnWebServerSet);

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

    hBox = new QHBoxLayout();

    label = new QLabel;
    hBox->addWidget(label);

    comboBox_realtimeServer = new QComboBox;
    comboBox_realtimeServer->addItem(tr("www.ledokcloud.com/realtime"));
    comboBox_realtimeServer->setMinimumWidth(260);
    comboBox_realtimeServer->setEditable(true);
    hBox->addWidget(comboBox_realtimeServer);

    pushButtonSetREaltimeServer = new QPushButton;
    hBox->addWidget(pushButtonSetREaltimeServer);

    pushButtonClearRealtimerAddress = new QPushButton;
    hBox->addWidget(pushButtonClearRealtimerAddress);

    hBox->addStretch();

    vBox->addLayout(hBox);

    hBox = new QHBoxLayout();

    btnApkCheck = new QPushButton;
    btnApkCheck->setProperty("ssType", "progManageTool");
    connect(btnApkCheck, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "CheckSoftVersions");
        json.insert("_type", "CheckSoftVersions");
        if(gSelCards->count() != 1) return;
        auto waitingDlg = new WaitingDlg(this, tr("Check Apk Version"));
        Def_CtrlReqPre
        connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
            Def_CtrlSingleGetReply
            waitingDlg->close();
            fdPkg->clear();
            auto apps = json["apps"].toArray();
            auto infoDlg = new QDialog(this);
            infoDlg->setWindowFlag(Qt::WindowContextHelpButtonHint, false);
            infoDlg->resize(500, 500);
            infoDlg->setWindowTitle(tr("Software Version Info"));
            auto vBox = new QVBoxLayout(infoDlg);
            vBox->setContentsMargins(0, 0, 0, 0);
            auto table = new Table{
                {"apk", "Apk"},
                {"ver", tr("Version")},
                {"pkg", tr("Package")}
            };
            table->setDefs();
            table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
            table->setRowCount(apps.size());
            vBox->addWidget(table);
            for(int i=0; i<apps.size(); i++) {
                auto app = apps.at(i);
                QString packageName = app["packageName"].toString();
                table->setItem(i, "apk", new QTableWidgetItem{app["appName"].toString()});
                table->setItem(i, "ver", new QTableWidgetItem{app["versionName"].toString()});
                table->setItem(i, "pkg", new QTableWidgetItem{packageName});
                if(! (packageName.endsWith(".cardsystem") || packageName.endsWith(".systemcore") || packageName.endsWith(".update"))) fdPkg->addItem(packageName);
            }
            infoDlg->show();
        });
    });
    hBox->addWidget(btnApkCheck);

    btnApkUpgrade = new QPushButton;
    btnApkUpgrade->setProperty("ssType", "progManageTool");
    connect(btnApkUpgrade, &QPushButton::clicked, this, [this] {
        if(m_pLedlist==0) return;
        if(m_pLedlist->count()==0 || (m_pLedlist->count()==1 && m_pLedCard==nullptr)) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        if(m_pLedlist->count() != 1) return;
        if(m_pLedCard->bPassword && m_pLedCard->m_bLockStatus && m_lockFlag) {
            QMessageBox::information(gMainWin, tr("Tip"),tr("This screen is encrypted,Please decrypt and upgrade APK!"));
            return;
        }
        QString url = "http://"+m_pLedCard->m_strCardIp+":2016/upload?type=software";
        m_strUpgradeApkFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("apk package (*.apk *.zip)"));
        QFileInfo file1(m_strUpgradeApkFile);
        QFile file(m_strUpgradeApkFile);
        QMap<QString,QString> params_send; //上传的普通参数 在本程序中 需要上传一个普通参数为"username"
        params_send.insert("username","10005");
        UpLoadForm(url, params_send, file1.fileName(), &file, 0);
    });
    hBox->addWidget(btnApkUpgrade);

    fdPkg = new QComboBox;
    fdPkg->setEditable(true);
    fdPkg->setMinimumWidth(200);
    hBox->addWidget(fdPkg);

    fdUnload = new QPushButton;
    connect(fdUnload, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        auto pkg = fdPkg->currentText();
        if(pkg.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("Package name is null"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "UninstallSoftware");
        json.insert("_type", "UninstallSoftware");
        json.insert("packageName", pkg);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("UninstallSoftware"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSetReqAfter
            });
        } else {
            foreach(auto card, *gSelCards) {
                Def_CtrlSetMulti(tr("UninstallSoftware"))
            }
        }
    });
    hBox->addWidget(fdUnload);

    btnRunningCheck = new QPushButton;
    connect(btnRunningCheck, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        auto pkg = fdPkg->currentText();
        if(pkg.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("Package name is null"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "IsSoftwareRunning");
        json.insert("_type", "IsSoftwareRunning");
        json.insert("packageName", pkg);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("IsSoftwareRunning"));
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                Def_CtrlSingleGetReply
                waitingDlg->close();
                QMessageBox::information(gMainWin, tr("Tip"), json["running"].toBool() ? tr("running") : tr("no running"));
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                connect(reply, &QNetworkReply::finished, this, [reply, card] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    gFdResInfo->append(card->m_strCardId+" "+tr("IsSoftwareRunning")+" "+(err.isEmpty() ? (json["running"].toBool() ? tr("running") : tr("no running")) : err));
                });
            }
        }
    });
    hBox->addWidget(btnRunningCheck);

    hBox->addStretch();

    vBox->addLayout(hBox);

    hBox = new QHBoxLayout();

    pushButtonFpgaUpgrade = new QPushButton;
    hBox->addWidget(pushButtonFpgaUpgrade);

    pushButtonFpgaVerCheck = new QPushButton;
    hBox->addWidget(pushButtonFpgaVerCheck);

    pushButtonSyncFpgaVer = new QPushButton;
    hBox->addWidget(pushButtonSyncFpgaVer);

    pushButtonRestart = new QPushButton;
    hBox->addWidget(pushButtonRestart);

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

    hBox = new QHBoxLayout();

    btnClearProg = new QPushButton;
    btnClearProg->setProperty("ssType", "progManageTool");
    connect(btnClearProg, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("Clearing Program")+" ...");
            waitingDlg->show();
            auto card = gSelCards->at(0);
            auto tcp = new QTcpSocket();
            auto timer = new QTimer(tcp);
            timer->setSingleShot(true);
            connect(timer, &QTimer::timeout, tcp, [tcp] {
                tcp->close();
                QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear Program")+" "+tr("Timeout"));
            });
            connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater);
            connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] {
                timer->stop();
                tcp->write("{\"_type\":\"DelPrograms\",\"_id\":\"DelPrograms\",\"zVer\":\"xixun1\"}");
                timer->start(10000);
            });
            connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, waitingDlg] {
                timer->stop();
                QByteArray resp = tcp->readAll();
                tcp->close();
                QJsonParseError parseErr;
                QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr);
                if(parseErr.error != QJsonParseError::NoError) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Tip"), parseErr.errorString());
                }
                else if(! json["success"].toBool()) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear Program")+" "+tr("Failed"));
                } else waitingDlg->success();
            });
            connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, waitingDlg](QAbstractSocket::SocketError err) {
                timer->stop();
                tcp->close();
                waitingDlg->close();
                QMessageBox::critical(gMainWin, tr("Tip"), QString(socketErrKey(err))+" ("+QString::number(err)+") "+tcp->errorString());
            });
            tcp->connectToHost(card->m_strCardIp, 3333);
            timer->start(10000);
        } else {
            foreach(auto card, *gSelCards) {
                auto tcp = new QTcpSocket();
                auto timer = new QTimer(tcp);
                timer->setSingleShot(true);
                connect(timer, &QTimer::timeout, tcp, [tcp, card] {
                    tcp->close();
                    gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+tr("Timeout"));
                });
                connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater);
                connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] {
                    timer->stop();
                    tcp->write("{\"_type\":\"DelPrograms\",\"_id\":\"DelPrograms\",\"zVer\":\"xixun1\"}");
                    timer->start(10000);
                });
                connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, card] {
                    timer->stop();
                    QByteArray resp = tcp->readAll();
                    tcp->close();
                    QJsonParseError parseErr;
                    QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr);
                    if(parseErr.error != QJsonParseError::NoError) gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+parseErr.errorString());
                    else if(! json["success"].toBool()) gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+tr("Failed"));
                    else gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+tr("Success"));
                });
                connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, card](QAbstractSocket::SocketError err) {
                    timer->stop();
                    tcp->close();
                    gFdResInfo->append(card->m_strCardId+" "+tr("Clear Program")+" "+QMetaEnum::fromType<QAbstractSocket::SocketError>().valueToKey(err)+" ("+QString::number(err)+") "+tcp->errorString());
                });
                tcp->connectToHost(card->m_strCardIp, 3333);
                timer->start(10000);
            }
        }
    });

    hBox->addWidget(btnClearProg);

    btnGetLog = new QPushButton;
    btnGetLog->setProperty("ssType", "progManageTool");
    connect(btnGetLog, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("Getting Log")+" ...");
            waitingDlg->show();
            auto card = gSelCards->at(0);
            auto reply = Tools::netManager().get(netReq("http://"+card->m_strCardIp+":2016/download?file=logs"));
            connect(reply, &QNetworkReply::finished, this, [this, reply, waitingDlg] {
                waitingDlg->close();
                QString err = parseReplyJson(reply);
                if(! err.isEmpty()) {
                    QMessageBox::critical(gMainWin, tr("Error"), err);
                    return;
                }
                QString logFile = QApplication::applicationDirPath()+"/log_"+m_pLedCard->m_strCardId+".txt";
                QFile file(logFile);
                if(! file.open(QIODevice::WriteOnly)) {
                    QMessageBox::critical(gMainWin, tr("Error"), "Open for Write Fail");
                    return;
                }
                file.write(reply->readAll());
                file.close();
                QProcess::execute("notepad", {logFile});
            });
        }
    });
    hBox->addWidget(btnGetLog);

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

    groupM80 = new QGroupBox;
    hBox = new QHBoxLayout(groupM80);

    fdM80 = new QComboBox();
    fdM80->setMinimumWidth(160);
    fdM80->setEditable(true);
    mM80Map.insert("576×3840","625×3960");
    mM80Map.insert("640×3840","660×3960");
    mM80Map.insert("720×3200","750×3300");
    mM80Map.insert("864×2672","900×2750");
    mM80Map.insert("1080×1920","1125×2200");
    mM80Map.insert("1280×1760","1320×1850");
    mM80Map.insert("1472×1536","1500×1650");
    mM80Map.insert("1536×1472","1650×1500");
    mM80Map.insert("1760×1280","1850×1320");
    mM80Map.insert("1920×1080","2200×1125");
    mM80Map.insert("2672×864","2750×900");
    mM80Map.insert("3200×760","3300×825");
    mM80Map.insert("3200×720","3300×750");
    mM80Map.insert("3840×640","3960×660");
    mM80Map.insert("3840×576","3960×625");
    mM80Map.insert("4096×480","4500×550");
    fdM80->addItems(mM80Map.keys());
    hBox->addWidget(fdM80);

    btnM80Set = new QPushButton();
    hBox->addWidget(btnM80Set);

    btnM80Refresh = new QPushButton();
    hBox->addWidget(btnM80Refresh);

    btnM80Restore = new QPushButton();
    hBox->addWidget(btnM80Restore);

    hBox->addStretch();

    vBox->addWidget(groupM80);

    hBox = new QHBoxLayout();

    btnLedSet3 = new QPushButton;
    btnLedSet3->setMinimumHeight(34);
    btnLedSet3->setProperty("ssType", "progManageTool");
    connect(btnLedSet3, SIGNAL(clicked()),this,SLOT(OnStartConfigLedScreenSoft()));
    hBox->addWidget(btnLedSet3);

    btnLedSet4 = new QPushButton;
    btnLedSet4->setMinimumHeight(34);
    btnLedSet4->setProperty("ssType", "progManageTool");
    connect(btnLedSet4, &QPushButton::clicked, btnLedSet4, [] {
        QFileInfo file("LedSet4.0/LedSet4.0.exe");
        if(file.exists()) QProcess::startDetached(file.absoluteFilePath(), QStringList());
    });
    hBox->addWidget(btnLedSet4);

    vBox->addLayout(hBox);

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

    hBox = new QHBoxLayout();
    btnBindTaxiIc = new QPushButton;
    btnBindTaxiIc->setProperty("ssType", "progManageTool");
    connect(btnBindTaxiIc, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QString icFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("indentity voucher (*.ic)"));
        if(icFile.isEmpty()) return;
        QFile file(icFile);
        if(! file.open(QIODevice::ReadOnly)) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("Open file Failed"));
            return;
        }
        auto data = file.readAll();
        file.close();
        QJsonParseError jsonErr;
        QJsonDocument icJson = QJsonDocument::fromJson(data, &jsonErr);
        if(jsonErr.error != QJsonParseError::NoError) {
            QMessageBox::information(gMainWin, tr("Tip"), "JsonError "+jsonErr.errorString()+"\n"+data);
            return;
        }
        QJsonObject jsonCommand;
        jsonCommand.insert("action", "BindAccount");
        jsonCommand.insert("accountIdToken", icJson["account_id_token"]);
        jsonCommand.insert("server", icJson["taxiServerURL"]);
        jsonCommand.insert("tlsServer", icJson["taxiServerTLSURL"]);
        QJsonObject json;
        json.insert("action", "InvokeTaxiAppFunction");
        json.insert("jsonCommand", jsonCommand);
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("InvokeTaxiAppFunction"));
            waitingDlg->show();
            auto reply = Tools::netManager().post(reqForJson("http://"+gSelCards->at(0)->m_strCardIp+":3000"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
            connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                QString err = parseReplyJson(reply);
                if(! err.isEmpty()) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Error"), err);
                    return;
                }
                auto data = reply->readAll();
                QJsonParseError jsonErr;
                QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr);
                if(jsonErr.error != QJsonParseError::NoError) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Error"), "JsonError "+jsonErr.errorString()+"\n"+data);
                    return;
                }
                if(json["result"].toString() != "true") {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Error"), data);
                    return;
                }
                waitingDlg->success();
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":3000"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                connect(reply, &QNetworkReply::finished, this, [reply, card] {
                    QString err = parseReplyJson(reply);
                    if(! err.isEmpty()) {
                        gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" "+err);
                        return;
                    }
                    auto data = reply->readAll();
                    QJsonParseError jsonErr;
                    QJsonDocument json = QJsonDocument::fromJson(data, &jsonErr);
                    if(jsonErr.error != QJsonParseError::NoError) {
                        gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" JsonError "+jsonErr.errorString()+"\n"+data);
                        return;
                    }
                    if(json["result"].toString() != "true") {
                        gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+tr("Error")+" "+data);
                        return;
                    }
                    gFdResInfo->append(card->m_strCardId+" "+tr("InvokeTaxiAppFunction")+" "+QCoreApplication::translate("Def","Success"));
                });
            }
        }
    });
    hBox->addWidget(btnBindTaxiIc);
    hBox->addStretch();

    vBox->addLayout(hBox);

    groupTopLevel = new QGroupBox();
    hBox = new QHBoxLayout(groupTopLevel);

    fdTopLevelHL = new QRadioButton(groupTopLevel);
    fdTopLevelHL->setChecked(true);
    hBox->addWidget(fdTopLevelHL);

    fdTopLevelLH = new QRadioButton(groupTopLevel);
    hBox->addWidget(fdTopLevelLH);

    btnSetTopLevel = new QPushButton(groupTopLevel);
    hBox->addWidget(btnSetTopLevel);

    btnGetTopLevel = new QPushButton(groupTopLevel);
    hBox->addWidget(btnGetTopLevel);

    hBox->addStretch();

    vBox->addWidget(groupTopLevel);

    groupBoxRotate = new QGroupBox();
    hBox = new QHBoxLayout(groupBoxRotate);

    radioButton0degrees = new QRadioButton(groupBoxRotate);
    hBox->addWidget(radioButton0degrees);

    radioButton90degrees = new QRadioButton(groupBoxRotate);
    hBox->addWidget(radioButton90degrees);

    radioButton180degrees = new QRadioButton(groupBoxRotate);
    hBox->addWidget(radioButton180degrees);

    radioButton270degrees = new QRadioButton(groupBoxRotate);
    hBox->addWidget(radioButton270degrees);

    hBox->addStretch();

    vBox->addWidget(groupBoxRotate);

    groupBoxMinMaxBrightness = new QGroupBox();
    hBox = new QHBoxLayout(groupBoxMinMaxBrightness);

    lbMinBright = new QLabel();
    hBox->addWidget(lbMinBright);

    fdMinBright = new QLineEdit("1");
    fdMinBright->setMaximumWidth(50);
    hBox->addWidget(fdMinBright);

    lbMinBrightTip = new QLabel();
    hBox->addWidget(lbMinBrightTip);

    btnMinBrightGet = new QPushButton();
    hBox->addWidget(btnMinBrightGet);

    btnMinBrightSet = new QPushButton();
    hBox->addWidget(btnMinBrightSet);

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

    lineEdit_4 = new QLineEdit("255");
    lineEdit_4->setMaximumWidth(50);
    hBox->addWidget(lineEdit_4);

    label_5 = new QLabel();
    hBox->addWidget(label_5);

    pushButtonReadbackMaxBrightess = new QPushButton();
    hBox->addWidget(pushButtonReadbackMaxBrightess);

    pushButtonSendMaxBrightness = new QPushButton();
    hBox->addWidget(pushButtonSendMaxBrightness);

    hBox->addStretch();
    vBox->addWidget(groupBoxMinMaxBrightness);

    vBox->addSpacing(20);

    grpBoxHiddenSettings = new QGroupBox;
    grpBoxHiddenSettings->setVisible(false);
    {
        auto vBox = new QVBoxLayout(grpBoxHiddenSettings);
        vBox->setContentsMargins(6,6,6,6);

        hBox = new QHBoxLayout;

        btnSetBack = new QPushButton;
        btnSetBack->setProperty("ssType", "progManageTool");
        connect(btnSetBack, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QColorDialog colorDlg(this);
            colorDlg.setOption(QColorDialog::DontUseNativeDialog);

            if(colorDlg.exec() != QColorDialog::Accepted) return;
            QColor color = colorDlg.selectedColor();
            if(! color.isValid()) return;
            QJsonObject json;
            json.insert("_id", "SetWallpaper");
            json.insert("_type", "SetWallpaper");
            json.insert("rgb", color.name());
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("Setting Wallpaper")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("Set Wallpaper"))
                }
            }
        });
        hBox->addWidget(btnSetBack);

        btnSysUpd = new QPushButton;
        btnSysUpd->setProperty("ssType", "progManageTool");
        connect(btnSysUpd, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "SystemUpdate");
            json.insert("_type", "SystemUpdate");
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("System Updating")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("System Update"))
                }
            }
        });
        hBox->addWidget(btnSysUpd);

        hBox->addSpacing(20);

        btnPlayerBackSet = new QPushButton;
        btnPlayerBackSet->setProperty("ssType", "progManageTool");
        connect(btnPlayerBackSet, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QString file = QFileDialog::getOpenFileName(gMainWin, tr("Select File"), gFileHome, EPhoto::filters());
            if(file.isEmpty()) return;
            QFileInfo info(file);
            if(! info.isFile()) return;
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("Setting player background")+" ...");
                waitingDlg->show();
                auto thread = new PlayerBackSendThread(file, gSelCards->at(0)->m_strCardIp);
                connect(thread, &PlayerBackSendThread::emErr, this, [waitingDlg](QString err) {
                    if(err.isEmpty()) waitingDlg->success();
                    else {
                        waitingDlg->close();
                        QMessageBox::critical(gMainWin, tr("Error"), err);
                    }
                });
                thread->start();
            } else {
                foreach(auto card, *gSelCards) {
                    auto thread = new PlayerBackSendThread(file, card->m_strCardIp);
                    connect(thread, &PlayerBackSendThread::emErr, this, [card](QString err) {
                        gFdResInfo->append(card->m_strCardId+" "+tr("Set player background")+" "+(err.isEmpty() ? tr("Success") : err));
                    });
                    thread->start();
                }
            }
        });
        hBox->addWidget(btnPlayerBackSet);

        btnPlayerBackClear = new QPushButton;
        btnPlayerBackClear->setProperty("ssType", "progManageTool");
        connect(btnPlayerBackClear, &QPushButton::clicked, this, [this] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("Clearing player background")+" ...");
                waitingDlg->show();
                auto card = gSelCards->at(0);
                auto tcp = new QTcpSocket();
                auto timer = new QTimer(tcp);
                timer->setSingleShot(true);
                connect(timer, &QTimer::timeout, tcp, [tcp, waitingDlg] {
                    tcp->close();
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear player background")+" "+tr("Timeout"));
                });
                connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater);
                connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] {
                    timer->stop();
                    tcp->write("{\"_type\":\"DelBackImg\",\"_id\":\"DelBackImg\",\"zVer\":\"xixun1\"}");
                    timer->start(10000);
                });
                connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, waitingDlg] {
                    timer->stop();
                    QByteArray resp = tcp->readAll();
                    tcp->close();
                    QJsonParseError parseErr;
                    QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr);
                    if(parseErr.error != QJsonParseError::NoError) {
                        waitingDlg->close();
                        QMessageBox::critical(gMainWin, tr("Tip"), parseErr.errorString());
                    } else if(! json["success"].toBool()) {
                        waitingDlg->close();
                        QMessageBox::critical(gMainWin, tr("Tip"), tr("Clear player background")+" "+tr("Failed"));
                    } else waitingDlg->success();
                });
                connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, waitingDlg](QAbstractSocket::SocketError err) {
                    timer->stop();
                    tcp->close();
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Tip"), QString(socketErrKey(err))+" ("+QString::number(err)+") "+tcp->errorString());
                });
                tcp->connectToHost(card->m_strCardIp, 3333);
                timer->start(10000);
            } else {
                foreach(auto card, *gSelCards) {
                    auto tcp = new QTcpSocket();
                    auto timer = new QTimer(tcp);
                    timer->setSingleShot(true);
                    connect(timer, &QTimer::timeout, tcp, [tcp, card] {
                        tcp->close();
                        gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+tr("Timeout"));
                    });
                    connect(tcp, &QTcpSocket::disconnected, tcp, &QTcpSocket::deleteLater);
                    connect(tcp, &QTcpSocket::connected, tcp, [tcp, timer] {
                        timer->stop();
                        tcp->write("{\"_type\":\"DelBackImg\",\"_id\":\"DelBackImg\",\"zVer\":\"xixun1\"}");
                        timer->start(10000);
                    });
                    connect(tcp, &QTcpSocket::readyRead, tcp, [tcp, timer, card] {
                        timer->stop();
                        QByteArray resp = tcp->readAll();
                        tcp->close();
                        QJsonParseError parseErr;
                        QJsonDocument json = QJsonDocument::fromJson(resp, &parseErr);
                        if(parseErr.error != QJsonParseError::NoError) gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+parseErr.errorString());
                        else if(! json["success"].toBool()) gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+tr("Failed"));
                        else gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+tr("Success"));
                    });
                    connect(tcp, &QTcpSocket::errorOccurred, tcp, [tcp, timer, card](QAbstractSocket::SocketError err) {
                        timer->stop();
                        tcp->close();
                        gFdResInfo->append(card->m_strCardId+" "+tr("Clear player background")+" "+QMetaEnum::fromType<QAbstractSocket::SocketError>().valueToKey(err)+" ("+QString::number(err)+") "+tcp->errorString());
                    });
                    tcp->connectToHost(card->m_strCardIp, 3333);
                    timer->start(10000);
                }
            }
        });
        hBox->addWidget(btnPlayerBackClear);

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

        lbBaudCfg = new QLabel;
        vBox->addWidget(lbBaudCfg);

        hBox = new QHBoxLayout;

        lbBaudModel = new QLabel;
        hBox->addWidget(lbBaudModel);

        auto fdBaudDevMod = new QComboBox;
        fdBaudDevMod->addItems({
            "M5x/M6x",
            "M7x/Y7x",
            "E2x/Y6x",
            "L20"
        });
        hBox->addWidget(fdBaudDevMod);

        lbUart = new QLabel;
        hBox->addWidget(lbUart);

        auto fdUart = new QComboBox;
        fdUart->setEditable(true);
        fdUart->setMinimumWidth(140);
        fdUart->setSizeAdjustPolicy(QComboBox::AdjustToContents);
        fdUart->addItems({
            "/dev/ttyS3",
            "/dev/ttyS4",
            "/dev/ttyS5"
        });
        hBox->addWidget(fdUart);

        connect(fdBaudDevMod, &QComboBox::currentTextChanged, fdUart, [fdUart](const QString &text) {
            fdUart->clear();
            if(text.startsWith("M5x")) fdUart->addItems({
                "/dev/ttyS3",
                "/dev/ttyS4",
                "/dev/ttyS5"
            });
            else if(text.startsWith("M7x")) fdUart->addItem("/dev/ttyS4");
            else if(text.startsWith("E2x")) fdUart->addItems({
                "/dev/ttysWK0",
                "/dev/ttysWK1",
                "/dev/ttysWK2",
                "/dev/ttysWK3",
                "/dev/tty232",
                "/dev/tty485",
                "/dev/ttyTTL"
            });
            else if(text.startsWith("L20")) fdUart->addItems({
                "/dev/ttyS0",
                "/dev/ttyS1",
                "/dev/ttyS4"
            });
        });

        lbBaud = new QLabel;
        hBox->addWidget(lbBaud);

        auto fdBaud = new QLineEdit;
        fdBaud->setMaximumWidth(70);
        hBox->addWidget(fdBaud);

        btnBaudSet = new QPushButton;
        btnBaudSet->setProperty("ssType", "progManageTool");
        connect(btnBaudSet, &QPushButton::clicked, this, [this, fdUart, fdBaud] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "SetBaudRateByCardType");
            json.insert("_type", "SetBaudRateByCardType");
            json.insert("uartName", fdUart->currentText());
            json.insert("baud", fdBaud->text().toInt());
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("Setting Baud Rate")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, waitingDlg] {
                    Def_CtrlSetReqAfter
                });
            } else {
                foreach(auto card, *gSelCards) {
                    Def_CtrlSetMulti(tr("Set Baud Rate"))
                }
            }
        });
        hBox->addWidget(btnBaudSet);

        btnBaudGet = new QPushButton;
        btnBaudGet->setProperty("ssType", "progManageTool");
        connect(btnBaudGet, &QPushButton::clicked, this, [this, fdUart, fdBaud] {
            if(gSelCards->isEmpty()) {
                QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
                return;
            }
            QJsonObject json;
            json.insert("_id", "GetBaudRateByCardType");
            json.insert("_type", "GetBaudRateByCardType");
            json.insert("uartName", fdUart->currentText());
            if(gSelCards->count() == 1) {
                auto waitingDlg = new WaitingDlg(this, tr("Getting Baud Rate")+" ...");
                Def_CtrlReqPre
                connect(reply, &QNetworkReply::finished, this, [reply, fdBaud, waitingDlg] {
                    Def_CtrlSingleGetReply
                    waitingDlg->success();
                    fdBaud->setText(QString::number(json["baud"].toInt()));
                });
            } else {
                foreach(auto card, *gSelCards) {
                    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                    connect(reply, &QNetworkReply::finished, this, [reply, card] {
                        QJsonDocument json;
                        QString err = checkReplyForJson(reply, &json);
                        gFdResInfo->append(card->m_strCardId+" "+tr("Get Baud Rate")+" "+(err.isEmpty()?QString::number(json["baud"].toInt()):err));
                    });
                }
            }
        });
        hBox->addWidget(btnBaudGet);

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


        fdIsOpenADB = new QCheckBox;
        vBox->addWidget(fdIsOpenADB);

        hBox = new QHBoxLayout();

        lbCustomJson = new QLabel;
        hBox->addWidget(lbCustomJson);

        hBox->addSpacing(40);

        btnSendCustomJson = new QPushButton;
        hBox->addWidget(btnSendCustomJson);

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

        fdCustomJson = new QTextEdit;
        fdCustomJson->setMinimumHeight(120);
        vBox->addWidget(fdCustomJson);
    }
    vBox->addWidget(grpBoxHiddenSettings);
    vBox->addStretch();

    pushButtonSetREaltimeServer->setProperty("ssType", "progManageTool");
    pushButtonClearRealtimerAddress->setProperty("ssType", "progManageTool");
    pushButtonRestart->setProperty("ssType", "progManageTool");
    fdUnload->setProperty("ssType", "progManageTool");
    btnRunningCheck->setProperty("ssType", "progManageTool");
    pushButtonFpgaUpgrade->setProperty("ssType", "progManageTool");
    pushButtonFpgaVerCheck->setProperty("ssType", "progManageTool");
    pushButtonSyncFpgaVer->setProperty("ssType", "progManageTool");
    btnMinBrightGet->setProperty("ssType", "progManageTool");
    pushButtonReadbackMaxBrightess->setProperty("ssType", "progManageTool");
    btnMinBrightSet->setProperty("ssType", "progManageTool");
    pushButtonSendMaxBrightness->setProperty("ssType", "progManageTool");
    btnM80Set->setProperty("ssType", "progManageTool");
    btnM80Refresh->setProperty("ssType", "progManageTool");
    btnM80Restore->setProperty("ssType", "progManageTool");
    btnGetTopLevel->setProperty("ssType", "progManageTool");
    btnSetTopLevel->setProperty("ssType", "progManageTool");
    btnSendCustomJson->setProperty("ssType", "progManageTool");

    groupBoxRotate->setVisible(false);
    groupBoxMinMaxBrightness->setVisible(false);
    groupTopLevel->setVisible(false);


    connect(pushButtonSetREaltimeServer,SIGNAL(clicked()),this,SLOT(OnSetRealtimeServer()));
    connect(pushButtonClearRealtimerAddress,SIGNAL(clicked()),this,SLOT(OnClearRealtimeServer()));

    connect(pushButtonRestart, SIGNAL(clicked()),this,SLOT(OnRestart()));

    connect(pushButtonFpgaUpgrade,SIGNAL(clicked()),this,SLOT(OnFpgaUpgrade()));
    connect(pushButtonFpgaVerCheck,SIGNAL(clicked()),this,SLOT(OnFpgaVerCheck()));
    connect(pushButtonSyncFpgaVer,SIGNAL(clicked()),this,SLOT(OnSyncFpgaVer()));

    connect(radioButton0degrees,SIGNAL(clicked()),this,SLOT(On0degrees()));
    connect(radioButton90degrees,SIGNAL(clicked()),this,SLOT(On90degrees()));
    connect(radioButton180degrees,SIGNAL(clicked()),this,SLOT(On180degrees()));
    connect(radioButton270degrees,SIGNAL(clicked()),this,SLOT(On270degrees()));

    connect(btnMinBrightSet,SIGNAL(clicked()),this,SLOT(OnSendMinBrightness()));
    connect(pushButtonSendMaxBrightness,SIGNAL(clicked()),this,SLOT(OnSendMaxBrightness()));
    connect(btnMinBrightGet,SIGNAL(clicked()),this,SLOT(OnGetMinBrightness()));

    connect(pushButtonReadbackMaxBrightess,SIGNAL(clicked()),this,SLOT(OnGetMaxBrightness()));
    connect(btnSendCustomJson,SIGNAL(clicked()),this,SLOT(OnSendCustomJson()));

    pHpptClient = new HpptClient(this);
    connect(pHpptClient, &HpptClient::httpPostRspReady, this, &CtrlAdvancedPanel::OnProHttpResponse);
    pHpptClientAll = new HpptClient(this);
    connect(pHpptClientAll,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this, SLOT(OnProHttpResponseAll(QString , QString , QByteArray)));
    m_pGetAskTimer = new QTimer(this);
    connect(this, SIGNAL(sigSend(QJsonObject &,QString)), parent->parent(), SLOT(OnControlSendJson(QJsonObject &,QString)));

    connect(pHpptClient,SIGNAL(httpGetRspReady(QString , QByteArray )),this,SLOT(OnProHttpGetResponse(QString , QByteArray)));

    connect(btnM80Set,SIGNAL(clicked()),this,SLOT(OnM80Set()));
    connect(btnM80Refresh,SIGNAL(clicked()),this,SLOT(OnM80Refresh()));
    connect(btnM80Restore,SIGNAL(clicked()),this,SLOT(OnM80Restore()));
    connect(btnSetTopLevel,SIGNAL(clicked()),this,SLOT(OnSetTaxiTopScreen()));
    connect(btnGetTopLevel,SIGNAL(clicked()),this,SLOT(OnReadbackTaxiTopScreen()));
    connect(fdIsOpenADB,SIGNAL(clicked()),this,SLOT(OnOpenAdb()));

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

CtrlAdvancedPanel::~CtrlAdvancedPanel(){
    if(pHpptClient != nullptr){
        delete pHpptClient;
        pHpptClient=nullptr;
    }
    if(pHpptClientAll != nullptr){
        delete pHpptClientAll;
        pHpptClientAll=nullptr;
    }
}
void CtrlAdvancedPanel::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    init();
}
void CtrlAdvancedPanel::init() {
    m_pLedCard = gSelCards->at(0);
    if(! m_passwordOk) {
        hide();
        PasswordInChDlg dlg(gMainWin);
        connect(dlg.btnBox, &QDialogButtonBox::accepted, &dlg, [&dlg]() {
            QString passRaw = QSettings().value("advUiPs").toString();
            QString password = passRaw.isEmpty() ? "888" : QTextCodec::codecForName("GBK")->toUnicode(QByteArray::fromBase64(passRaw.toLocal8Bit()));
            if(dlg.fdPassword->text() == password) dlg.accept();
            else QMessageBox::critical(&dlg, tr("Tip"),tr("Password is error"));
        });
        if(dlg.exec()==QDialog::Accepted) {
            if(m_pLedlist->count()==1) btnScreenSet->setEnabled(true);
            m_passwordOk = true;
            show();
        } else return;
    }

    bool isSingle = gSelCards->count()==1;
    btnApkUpgrade->setEnabled(isSingle);
    btnApkCheck->setEnabled(isSingle);
    pushButtonFpgaUpgrade->setEnabled(isSingle);
    pushButtonFpgaVerCheck->setEnabled(isSingle);
    pushButtonSyncFpgaVer->setEnabled(isSingle);
    pushButtonRestart->setEnabled(isSingle);
    btnGetLog->setEnabled(isSingle);
    if(isSingle) groupM80->setVisible(m_pLedCard->m_strCardId.startsWith("M8", Qt::CaseInsensitive));
    else groupM80->setVisible(true);

    if(! isSingle) return;
    m_strUrl = "http://"+m_pLedCard->m_strCardIp+":2016/settings";

    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetScreenSize");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json);

    QJsonObject json1;
    json1.insert("_id", getRandomString(10));
    json1.insert("_type", "GetOnlineAddr");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json1);

    QJsonObject json2;
    json2.insert("_id", getRandomString(10));
    json2.insert("_type", "GetRealtimeServer");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json2);

    QJsonObject json3;
    json3.insert("_id", getRandomString(10));
    json3.insert("_type", "GetCardAlias");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json3);

    if(m_pLedCard->m_strCardId.startsWith("M8", Qt::CaseInsensitive)) {
        QJsonObject json3;
        json3.insert("_id", getRandomString(10));
        json3.insert("_type", "GetAllScreenSizeM80");
        qDebug()<<"GetAllScreenSizeM80 send";
        HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json3);
    }
}
void CtrlAdvancedPanel::changeEvent(QEvent *event) {
    QWidget::changeEvent(event);
    if(event->type() == QEvent::LanguageChange) transUi();
}
void CtrlAdvancedPanel::transUi() {
    btnBindTaxiIc->setText(tr("Binding *.ic account indentity voucher"));
    btnGetTopLevel->setText(tr("Readback"));
    btnLedSet3->setText(tr("Start LedSet3.0 configure LED module"));
    btnLedSet4->setText(tr("Start LedSet4"));
    btnM80Refresh->setText(tr("Refresh"));
    btnM80Restore->setText(tr("Restore to default"));
    btnM80Set->setText(tr("Set"));
    btnAliasSet->setText(tr("Set"));
    btnScreenSet->setText(tr("Set"));
    btnSetTopLevel->setText(tr("Set"));
    fdScreenHeight->setPlaceholderText(tr("Height"));
    fdScreenWidth->setPlaceholderText(tr("Width"));
    fdTopLevelHL->setText(tr("Service:High  Out of service:Low"));
    fdTopLevelLH->setText(tr("Service:Low  Out of service:High"));
    groupBoxRotate->setTitle(tr("Rotate"));

    grpBoxHiddenSettings->setTitle(tr("Hidden Settings")+" ("+tr("Click right button to hide")+")");
    btnSysUpd->setText(tr("System Update"));
    lbBaudCfg->setText(tr("Baud Config"));
    lbBaudModel->setText(tr("Model"));
    lbUart->setText(tr("Uart"));
    lbBaud->setText(tr("Baud"));
    btnBaudSet->setText(tr("Set"));
    btnBaudGet->setText(tr("Get"));
    fdIsOpenADB->setText(tr("Open ADB"));
    lbCustomJson->setText(tr("Post Custom JSON"));
    btnSendCustomJson->setText(tr("Send"));

    groupM80->setTitle(tr("M80 configuration"));
    groupTopLevel->setTitle(tr("Taxi top screen configuration"));
    label->setText(tr("Realtimer Server Address:"));
    lbTitle->setText(tr("Advanced parameters"));
    lbCompanyId->setText(tr("Compant ID:"));
    labelWebServer->setText(tr("Web Server Address:"));
    lbMinBright->setText(tr("Min brightness"));
    label_3->setText(tr("Max brightness "));
    lbMinBrightTip->setText(tr("(min:1)"));
    label_5->setText(tr("(max:255)"));
    lbAlias->setText(tr("Alias"));
    lbScreenHeight->setText(tr("Height"));
    lbScreenWidth->setText(tr("Screen Width(pixel)"));
    fdCompanyId->setPlaceholderText(tr("Compant ID"));
    btnApkCheck->setText(tr("Check Apk"));
    btnApkUpgrade->setText(tr("Apk upgrade"));
    btnGetLog->setText(tr("Check Log"));
    btnSetBack->setText(tr("Set Wallpaper"));
    btnClearProg->setText(tr("Clear Program"));
    btnPlayerBackSet->setText(tr("Set player background"));
    btnPlayerBackClear->setText(tr("Clear player background"));

    pushButtonClearRealtimerAddress->setText(tr("Clear"));
    pushButtonFpgaUpgrade->setText(tr("FPGA Upgrade"));
    pushButtonFpgaVerCheck->setText(tr("FPGA version check"));
    btnMinBrightGet->setText(tr("Readback"));
    pushButtonReadbackMaxBrightess->setText(tr("Readback"));
    pushButtonRestart->setText(tr("Restart led controller system"));
    btnRunningCheck->setText(tr("Running check"));
    pushButtonSendMaxBrightness->setText(tr("Send"));
    btnMinBrightSet->setText(tr("Send"));
    pushButtonSetREaltimeServer->setText(tr("Set"));
    btnWebServerSet->setText(tr("Set"));
    pushButtonSyncFpgaVer->setText(tr("Sync FPGA version"));
    fdUnload->setText(tr("Uninstall"));
    radioButton0degrees->setText(tr("0 degrees"));
    radioButton180degrees->setText(tr("180 degrees"));
    radioButton270degrees->setText(tr("270 degrees"));
    radioButton90degrees->setText(tr("90 degrees"));
}

void CtrlAdvancedPanel::OnClearRealtimeServer(){
    CHECK_CARD_SELECTED
    comboBox_realtimeServer->clearEditText();
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetRealtimeServer");
    json.insert("server", "");
    MACRO_DEFINE_TIPDLG_FUCN(tr("ClearRealtimeServer"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnSetRealtimeServer(){
    CHECK_CARD_SELECTED
    if(comboBox_realtimeServer->currentText().isEmpty()) {
        QMessageBox::information(gMainWin, tr("Tip"),tr("InputRealTimeAddressTip"));
        comboBox_realtimeServer->setFocus();
        return;
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetRealtimeServer");
    json.insert("server", comboBox_realtimeServer->currentText());
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetRealtimeServer"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnStartConfigLedScreenSoft() {
    QString strLedSetFile = QApplication::applicationDirPath()+"/LedSet/LedSet3.0.exe";
    QFileInfo cc22(strLedSetFile);
    if(cc22.exists()) {
        QProcess::startDetached(strLedSetFile,QStringList());
        return;
    }
    QSettings reg("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\sysolution\\LedSet3.0", QSettings::NativeFormat);
    QString strLedsetPath = reg.value("Program_path").toString();
    if(!strLedsetPath.isEmpty()) {
        QFileInfo cc(strLedsetPath);
         if(cc.exists()) QProcess::startDetached(strLedsetPath,QStringList());
         else {
            auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath);
            if(res == QMessageBox::Yes) {
                UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this);
                pDlg->exec();
            }
        }
        return;
    }
    QSettings reg1("HKEY_LOCAL_MACHINE\\SOFTWARE\\sysolution\\LedSet3.0", QSettings::NativeFormat);
    strLedsetPath = reg1.value("Program_path").toString();
    QFileInfo cc(strLedsetPath);
    if(!strLedsetPath.isEmpty()) {
        if(cc.exists()) QProcess::startDetached(strLedsetPath,QStringList());
        else {
            QString str1="C:/Program Files/sysolution/LedSet3.0/LedSet3.0.exe";
            QFileInfo cc1(str1);
            if(cc1.exists()) QProcess::startDetached(str1,QStringList());
            else {
                QString str2="C:/Program Files (x86)/sysolution/LedSet3.0/LedSet3.0.exe";
                QFileInfo cc2(str1);
                if(cc2.exists()) QProcess::startDetached(str2,QStringList());
                else {
                    auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath);
                    if(res == QMessageBox::Yes) {
                        UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this);
                        pDlg->exec();
                    }
                }
            }
        }
    } else {
        QString str1="C:/Program Files/sysolution/LedSet3.0/LedSet3.0.exe";
        QFileInfo cc1(str1);
        if(cc1.exists()) QProcess::startDetached(str1,QStringList());
        else {
            QString str2="C:/Program Files (x86)/sysolution/LedSet3.0/LedSet3.0.exe";
            QFileInfo cc2(str1);
            if(cc2.exists())QProcess::startDetached(str2,QStringList());
            else {
                auto res = QMessageBox::question(gMainWin, tr("Tip Info"), tr("Can not find LedSet3.0.exe,down you need download and install it")+strLedsetPath);
                if(res == QMessageBox::Yes) {
                    UpdateLedset3Dialog *pDlg=new UpdateLedset3Dialog(this);
                    pDlg->exec();
                }
            }
        }
    }
}
void CtrlAdvancedPanel::OnRestart(){
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "RestartAndroid");
    MACRO_DEFINE_TIPDLG_FUCN(tr("RestartAndroid"),tr("Success"),tr("failed"))
}

//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void CtrlAdvancedPanel::OnProHttpResponse(QString url, QString, QByteArray data){
    if(url == m_strUrl) {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(parseJsonErr.error != QJsonParseError::NoError){
            if(data.size()!=0) qDebug()<<tr("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true){
            if(strType == "SetRealtimeServer"){
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "RestartAndroid"){
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK

            }
            else if(strType == "GetScreenshotFull"){
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK

            }
            else if(strType == "AliIotSetting")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetOnlineAddr"){
            fdWebServerAddr->setCurrentText(jsonObject["server"].toString());
            fdCompanyId->setText(jsonObject["companuID"].toString());
            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetRealtimeServer"){
                comboBox_realtimeServer->setCurrentText(jsonObject["server"].toString());
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetCardAlias")
            {
                fdAlias->setText(QString::fromUtf8(QByteArray::fromBase64(jsonObject["alias"].toString().toLatin1())));
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType =="UpgradeSoftware")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
                        QMessageBox::information(gMainWin, tr("Tip"),tr("UpgradeSoftware")+tr("Success"));
            }
            else if(strType == "SynchronousHardwareVersion"){

                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
                        QMessageBox::information(gMainWin, tr("Tip"),tr("SynchronousHardwareVersion")+" "+tr("Success"));
            }
            else if(strType == "DelPrograms")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK

            }
            else if(strType == "SetScreenRotation")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK

            }
            else if(strType == "SetMinBrightness")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "SetMaxBrightness")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetMinBrightness")
            {

                fdMinBright->setText(QString::number(jsonObject["brightness"].toInt()));
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetMaxBrightness")
            {
                lineEdit_4->setText(QString::number(jsonObject["brightness"].toInt()));
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetSpecialResolution")
            {

                QString strCurDisplayResolution = jsonObject["displayResolution"].toString();
                fdM80->setCurrentText(strCurDisplayResolution);
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }

            else if(strType == "CheckHardwareVersions"){
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
                QString strtempVer="";
                int itempVerCount=0;
                foreach(QJsonValue value, jsonObject["versions"].toArray()) {
                    QString strtempIcount=QString::number(itempVerCount);
                    strtempVer += "[card"+strtempIcount+"]:"+value.toString()+"\r\n";
                    itempVerCount++;

                }
                QMessageBox::information(gMainWin, tr("FPGA Version"),strtempVer);
            }
            else if (strType == "SetHighForBusy") {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK

            }
            else if(strType == "OpenAdb")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if (strType == "GetStateForBusy") {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
                if(jsonObject["result"].toInt()==0)
                {
                    fdTopLevelLH->setChecked(true);
                    fdTopLevelHL->setChecked(false);
                }
                else {
                    fdTopLevelLH->setChecked(false);
                    fdTopLevelHL->setChecked(true);

                }
            }
        }else {
            if(strType =="UpgradeSoftware"){
                qDebug()<<"slotUploadFinished failed ack";
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
        }
    }
    if(url == m_strStartUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        if(jsonObject["result"].toString()=="true")
        {
            if(jsonObject["data"].toString()=="true")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
                        QJsonObject json1;
                        json1.insert("_id", getRandomString(10));
                        json1.insert("_type", "GetOnlineAddr");
                        HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json1);
            }
        }
    }
}

//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void CtrlAdvancedPanel::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "GetScreenSize")
            {
                fdScreenWidth->setText(QString::number(jsonObject["width"].toInt()));
                fdScreenHeight->setText(QString::number(jsonObject["height"].toInt()));
            }

            else if(strType == "GetCardAlias")
            {
                fdAlias->setText(QString::fromUtf8(QByteArray::fromBase64(jsonObject["alias"].toString().toLatin1())));

            }
            else if(strType == "GetOnlineAddr")
            {
                fdWebServerAddr->setCurrentText(jsonObject["server"].toString());
                fdCompanyId->setText(jsonObject["companuID"].toString());
            }
            else if(strType == "GetRealtimeServer")
            {
                qDebug()<<"GetRealtimeServer ack"<<jsonObject["server"].toString();
                comboBox_realtimeServer->setCurrentText(jsonObject["server"].toString());
            }
            else if(strType == "GetAllScreenSizeM80")
            {
                mM80Map=jsonObject["result"].toObject();
                QStringList strlist=mM80Map.keys();
                fdM80->clear();
                fdM80->addItems(strlist);
                 comboBox_realtimeServer->setCurrentText(jsonObject["server"].toString());
            }

        }

    }
}
void CtrlAdvancedPanel::OnFpgaUpgrade()
{
    QString url="http://"+m_pLedCard->m_strCardIp+":2016/upload?type=hardware";
    QFileDialog dlg;
    m_strUpgradeFpgaFile = QFileDialog::getOpenFileName(this, "open file dialog", "", tr("apk package (*.rpd)"));
    QFileInfo file1(m_strUpgradeFpgaFile);
    QFile file(m_strUpgradeFpgaFile);
    QMap<QString,QString> params_send; //上传的普通参数 在本程序中 需要上传一个普通参数为"username"
    params_send.insert("username","10005");
    UpLoadForm(url, params_send, file1.fileName(), &file, 1);
}
void CtrlAdvancedPanel::OnFpgaVerCheck()
{
    CHECK_CARD_SELECTED
             QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "CheckHardwareVersions");
            MACRO_DEFINE_TIPDLG_FUCN(tr("CheckHardwareVersions"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnSyncFpgaVer()
{
    CHECK_CARD_SELECTED
             QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "SynchronousHardwareVersion");
            MACRO_DEFINE_TIPDLG_FUCN(tr("SynchronousHardwareVersion"),tr("Check Screen untile fpga update finished"),tr("failed"))
}
void CtrlAdvancedPanel::slotUploadFpgaFinished()
{
    QFileInfo file(m_strUpgradeApkFile);
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SynchronousHardwareVersion");
    HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
    emit sigSetTipTextContent(tr("SynchronousHardwareVersion"));
    qDebug()<<"slotUploadFinished";

}
void CtrlAdvancedPanel::slotUploadFinished()
{
    QFileInfo file(m_strUpgradeApkFile);
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "UpgradeSoftware");
    json.insert("fileName", file.fileName());
    json.insert("isCustom", true);
    HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
    emit sigSetTipTextContent(tr("install start..."));
    MACRO_ASKTIME_STOP
    m_pGetAskTimer->start(50000);

    qDebug()<<"slotUploadFinished";

}
void CtrlAdvancedPanel::slotUploadProgress(qint64 A,qint64 B)
{
    if(B!=0)
    {
        QString strbaifenbi=tr("Uploadding")+":"+QString("%1%").arg(A*100/B);
        emit sigSetTipTextContent(strbaifenbi);
        m_pGetAskTimer->stop();
        m_pGetAskTimer->start(30000);
    }
}

void CtrlAdvancedPanel::UpLoadForm(QString Path, QMap<QString,QString> params, QString fileName, QFile *uploadFile, int iType) {
    auto boundary = QUuid::createUuid().toByteArray();
    QByteArray data;
    for(QMap<QString,QString>::iterator t=params.begin(); t!=params.end(); t++) {
        data.append("--").append(boundary).append("\r\n");
        data.append("Content-Disposition: form-data;name=\"").append(t.key().toUtf8()).append("\"\r\n");
        data.append("\r\n");
        data.append(t.value().toUtf8()).append("\r\n");
    }
    //上传文件的头部
    data.append("--").append(boundary).append("\r\n");
    data.append("Content-Disposition: form-data;name=\"").append(fileName.toUtf8()).append("\";filename=\"").append(fileName.toUtf8()).append("\"\r\n");
    data.append("\r\n");
    //上传文件内容
    if(!uploadFile->open(QIODevice::ReadOnly)) return;
    data.append(uploadFile->readAll());
    uploadFile->close();
    data.append("\r\n");
    data.append("--").append(boundary).append("\r\n");

   //编辑HTTP头部
    QNetworkRequest request = netReq(Path, 15000, "multipart/form-data;boundary="+boundary);
    request.setHeader(QNetworkRequest::ContentLengthHeader, data.length());
    //执行post请求
    if(m_PostingDlg==nullptr)
    {
        m_PostingDlg = new LoEmptyDialog();
        connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg()));
        connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock()));
        m_PostingDlg->lock(tr("UpgradeSoftware"),tr("Success"),tr("UpgradeSoftware")+tr("failed"));
        m_pGetAskTimer->start(60000);
        QNetworkReply * m_netReply = Tools::netManager().post(request, data);
        connect(m_netReply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
        connect(this, SIGNAL(sigSetTipTextContent ( QString )), m_PostingDlg, SLOT( SetTipTextContent(QString)));
        if(iType==0)//apk
        {
            connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFinished()));

        }
        else if(iType==1)//fpga.rpd
        {
            connect(m_netReply, SIGNAL(finished()), this, SLOT(slotUploadFpgaFinished()));

        }
        m_PostingDlg->exec();
     }
}
void messageHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) {
    auto cur = QDateTime::currentDateTime();
    QFile file("D:/LedOK-advanced-"+cur.toString("yy-MM-dd")+".log");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    file.write(cur.toString("yy-MM-dd hh:mm:ss ").toUtf8());
    if(type==QtDebugMsg)        file.write("   Debug: ");
    else if(type==QtWarningMsg) file.write(" Warning: ");
    else if(type==QtCriticalMsg)file.write("Critical: ");
    else if(type==QtFatalMsg)   file.write("   Fatal: ");
    else if(type==QtInfoMsg)    file.write("    Info: ");
    else if(type==QtSystemMsg)  file.write("  System: ");
    file.write(msg.toUtf8());
    file.close();
}
void CtrlAdvancedPanel::keyReleaseEvent(QKeyEvent *event) {
    auto key = event->key();
    if(key == Qt::Key_F3) m_lockFlag = false;
    else if(key == Qt::Key_F5) groupBoxRotate->setVisible(! groupBoxRotate->isVisible());
    else if(key == Qt::Key_F6) groupBoxMinMaxBrightness->setVisible(! groupBoxMinMaxBrightness->isVisible());
    else if(key == Qt::Key_F8) groupTopLevel->setVisible(! groupTopLevel->isVisible());
    else if(key == Qt::Key_F12) qInstallMessageHandler(messageHandler);
    QWidget::keyPressEvent(event);
}
void CtrlAdvancedPanel::mouseReleaseEvent(QMouseEvent *event){
    if(event->button()==Qt::RightButton) grpBoxHiddenSettings->setVisible(! grpBoxHiddenSettings->isVisible());
}
void CtrlAdvancedPanel::On0degrees()
{
    CHECK_CARD_SELECTED
            QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "SetScreenRotation");
            json.insert("rotation", 0);
            MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed"))
}

void CtrlAdvancedPanel::On90degrees()
{
    CHECK_CARD_SELECTED
            QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "SetScreenRotation");
            json.insert("rotation", 1);
            MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::On180degrees()
{
    CHECK_CARD_SELECTED
            QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "SetScreenRotation");
            json.insert("rotation", 2);
            MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::On270degrees()
{
    CHECK_CARD_SELECTED
            QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "SetScreenRotation");
            json.insert("rotation", 3);
            MACRO_DEFINE_TIPDLG_FUCN(tr("SetScreenRotation"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnSendMinBrightness()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetMinBrightness");
    json.insert("brightness", fdMinBright->text().toInt());
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetMinBrightness"),tr("Success"),tr("failed"))


}
void CtrlAdvancedPanel::OnSendMaxBrightness()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetMaxBrightness");
    json.insert("brightness", lineEdit_4->text().toInt());
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetMaxBrightness"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnGetMinBrightness()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetMinBrightness");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetMinBrightness"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnGetMaxBrightness()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetMaxBrightness");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetMaxBrightness"),tr("Success"),tr("failed"))
}

void CtrlAdvancedPanel::OnM80Set()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetSpecialResolution");
    json.insert("displayResolution",fdM80->currentText()),	//显示分辨率
    json.insert("totalResolution",mM80Map[fdM80->currentText()].toString() );	//显示分辨率
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetSpecialResolution"),tr("Success"),tr("failed"))
}

void CtrlAdvancedPanel::OnM80Refresh()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetSpecialResolution");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetSpecialResolution"),tr("Success"),tr("failed"))
}

void CtrlAdvancedPanel::OnM80Restore()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "CleanDisplayScreenSize");
    MACRO_DEFINE_TIPDLG_FUCN(tr("CleanDisplayScreenSize"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnSetTaxiTopScreen()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetHighForBusy");
    if(fdTopLevelLH->isChecked())
        json.insert("busyState", 0);
    else if(fdTopLevelHL->isChecked())
        json.insert("busyState", 1);
    else {
        json.insert("busyState", 1);
    }

    MACRO_DEFINE_TIPDLG_FUCN(tr("SetHighForBusy"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::OnReadbackTaxiTopScreen()
{
    CHECK_CARD_SELECTED
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetStateForBusy");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetStateForBusy"),tr("Success"),tr("failed"))
}

void CtrlAdvancedPanel::OnOpenAdb()
{

    CHECK_CARD_SELECTED
             QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "OpenAdb");
            if(fdIsOpenADB->isChecked())
            {
                json.insert("open", true);
            }
            else {
                json.insert("open", false);
            }
            MACRO_DEFINE_TIPDLG_FUCN(tr("OpenAdb"),tr("Success"),tr("failed"))
}
void CtrlAdvancedPanel::DeletePostingDlg()
{
    if(m_PostingDlg!=nullptr)
    {
        delete m_PostingDlg;
        m_PostingDlg=nullptr;
    }
}
void CtrlAdvancedPanel::OnSendCustomJson(){//ok

        CHECK_CARD_SELECTED
                m_strStartUrl="http://"+m_pLedCard->m_strCardIp+":3000";

        QJsonObject json;

            QJsonParseError l_err;
            QJsonDocument l_doc = QJsonDocument::fromJson(fdCustomJson->toPlainText().toUtf8(), &l_err);
            if (l_err.error == QJsonParseError::NoError)
            {
                if (l_doc.isObject())
                {
                    json = l_doc.object();
                }
            }

        if(json.count()<=0)
        {
            QMessageBox::information(gMainWin, tr("Tip"),tr("Json format is error!"));
            return;
        }
        if(m_pLedlist==nullptr)
            return;
        if(m_pLedlist->count()<=1)
        {
            if(m_pLedCard!=nullptr)
            {
                HttpPostByTypeJsonObject(pHpptClient,m_strStartUrl,json);
                if(m_PostingDlg==nullptr)
                {
                    m_PostingDlg = new LoEmptyDialog(this);
                    connect(m_PostingDlg,SIGNAL(sigClose()),this,SLOT(DeletePostingDlg()));
                    connect(m_pGetAskTimer,SIGNAL(timeout()),m_PostingDlg,SLOT(TimerOutUnlock()));
                    m_PostingDlg->lock(tr("AliIotSetting"),tr("Success"),tr("failed"));
                    m_pGetAskTimer->start(5000);
                    m_PostingDlg->exec();

                }
            }
        }
        else {
            emit sigSend(json,tr("AliIotSetting"));
        }
}

PlayerBackSendThread::PlayerBackSendThread(const QString &file, const QString &ip) : file(file), ip(ip) {
    connect(this, &QThread::finished, this, &QThread::deleteLater);
}
void PlayerBackSendThread::run() {
    TcpSocket tcp;
    tcp.connectToHost(ip, 3333);
    if(! tcp.waitForConnected()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForConnected");
        tcp.close();
        return;
    }
    QFileInfo info(file);
    auto baseName = info.baseName();
    auto remain = info.size();

    auto req = QJsonObject();
    req.insert("_type", "proStart");
    req.insert("proName", "program");
    req.insert("proSize", remain);
    req.insert("zVer","xixun1");
    auto resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact));
    if(resNum == -1 || ! tcp.waitForBytesWritten()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proStart'");
        tcp.close();
        return;
    }
    req = QJsonObject();
    req.insert("_type", "imgFileStart");
    req.insert("id", baseName);
    req.insert("size", remain);
    req.insert("zVer","xixun1");
    resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact));
    if(resNum == -1 || ! tcp.waitForBytesWritten()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'imgFileStart'");
        tcp.close();
        return;
    }
    auto file = new QFile(info.filePath());
    if(! file->open(QFile::ReadOnly)) {
        emit emErr(tr("Open file failed")+" "+file->errorString());
        tcp.close();
        return;
    }
    while(remain > 0) {
        auto readed = file->read(qMin(4096LL, remain));
        if(readed.isEmpty()) {
            emit emErr(tr("Read file failed")+" "+file->errorString());
            tcp.close();
            file->close();
            return;
        }
        resNum = tcp.write(readed);
        if(resNum == -1) {
            emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write file: "+file->fileName());
            tcp.close();
            file->close();
            return;
        }
        if(! tcp.waitForBytesWritten()) {
            emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForWritten file: "+file->fileName());
            tcp.close();
            file->close();
            return;
        }
        remain -= resNum;
    }
    file->close();
    req = QJsonObject();
    req.insert("_type", "imgFileEnd");
    req.insert("id", baseName);
    req.insert("zVer","xixun1");
    resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact));
    if(resNum == -1 || ! tcp.waitForBytesWritten()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'fileEnd'");
        tcp.close();
        return;
    }
    req = QJsonObject();
    req.insert("_type", "proEnd");
    req.insert("proName", "program");
    req.insert("zVer","xixun1");
    resNum = tcp.write(QJsonDocument(req).toJson(QJsonDocument::Compact));
    if(resNum == -1 || ! tcp.waitForBytesWritten()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when write 'proEnd'");
        tcp.close();
        return;
    };
    if(! tcp.waitForReadyRead()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when waitForRead 'proEnd'");
        tcp.close();
        return;
    }
    auto resp = tcp.readAll();
    if(resp.isEmpty()) {
        emit emErr(QString(socketErrKey(tcp.error()))+" ("+QString::number(tcp.error())+") when read 'proEnd'");
        tcp.close();
        return;
    }
    tcp.close();
    emit emErr("");
}
