#include "upgradeapkdialog.h"
#include "gutil/qcore.h"
#include "gutil/qgui.h"
#include "gutil/qnetwork.h"
#include "base/waitingdlg.h"
#include "tools.h"
#include <QAction>
#include <QFileDialog>
#include <QLineEdit>
#include <QMessageBox>
#include <QHeaderView>
#include <QKeyEvent>
#include <QJsonArray>
#include <QHttpMultiPart>

UpgradeApkDialog::UpgradeApkDialog(QWidget *parent) : QDialog(parent) {
    resize(1280, 720);
    setWindowFlag(Qt::WindowMaximizeButtonHint);
    setWindowState(Qt::WindowMaximized);

    setWindowTitle(tr("Update APK"));

    auto vBox = new VBox(this);
    auto hBox = new HBox(vBox);

    auto btnSelectOnlineApk = new QPushButton(tr("Select Online APK"));
    btnSelectOnlineApk->setMinimumSize(QSize(100, 30));
    btnSelectOnlineApk->setProperty("ssType", "progManageTool");
    hBox->addWidget(btnSelectOnlineApk);

    auto btnSelectApk = new QPushButton(tr("Select apk"));
    btnSelectApk->setMinimumSize(QSize(100, 30));
    btnSelectApk->setProperty("ssType", "progManageTool");
    hBox->addWidget(btnSelectApk);

    auto btnSelectFpga = new QPushButton(tr("Select Fpga"));
    btnSelectFpga->setMinimumSize(QSize(100, 30));
    btnSelectFpga->setProperty("ssType", "progManageTool");
    hBox->addWidget(btnSelectFpga);

    auto fdFileName = new QLabel;
    fdFileName->setMinimumSize(200, 30);
    fdFileName->setStyleSheet("background-color: #fff;");
    hBox->addWidget(fdFileName);

    connect(btnSelectApk, &QPushButton::clicked, this, [=] {
        filePath = QFileDialog::getOpenFileName(this, "Open file", QString(), "apk package (*.apk *.zip)");
        if(filePath.isEmpty()) return;
        fileId = "";
        fdFileName->setText(QFileInfo(filePath).fileName());
    });
    connect(btnSelectFpga, &QPushButton::clicked, this, [=] {
        filePath = QFileDialog::getOpenFileName(this, "Open File", QString(), "rpd package (*.rpd)");
        if(filePath.isEmpty()) return;
        fileId = "";
        fdFileName->setText(QFileInfo(filePath).fileName());
    });
    connect(btnSelectOnlineApk, &QPushButton::clicked, this, [=] {
        NetReq req("https://www.ledokcloud.com/aips4/screen/upgrade/getGeneric?type=0&page=1&limit=10");
        req.setRawHeader("token","e183653f716cb150ebf3b4f8a83c95e7");
        auto reply = req.timeout(60000).post("");
        connect(reply, &QNetworkReply::finished, this, [=] {
            QJsonDocument json;
            auto err = errStrWithData(reply, &json);
            if(! err.isEmpty()) {
                QMessageBox::critical(this, "Error", err);
                return;
            }
            if(json["code"].toInt()) {
                QMessageBox::critical(this, "Error", json["msg"].toString());
                return;
            }
            auto files = json["page"]["list"].toArray();
            if(files.isEmpty()) {
                QMessageBox::critical(this, "Error", tr("No Files"));
                return;
            }
            QDialog dlg(this);
            dlg.setWindowFlag(Qt::WindowContextHelpButtonHint, false);
            dlg.setWindowTitle(tr("Select Online APK"));
            dlg.resize(800, 500);

            auto vBox = new VBox(&dlg);
            vBox->setContentsMargins(0,0,0,0);

            auto table = new Table{
                {"name", tr("Name"), 200, QHeaderView::Stretch},
                {"size", tr("Size"), 80},
                {"createTime", tr("Create Time"), 150}
            };
            table->setDefs();
            table->setSelectionMode(QAbstractItemView::SingleSelection);
            foreach(QJsonValue file, files) {
                auto rr = table->appendRow();
                table->setText(rr, "name", file["fileName"].toString()+"."+file["suffix"].toString());
                table->setText(rr, "size", byteSizeStr(file["fileSize"].toInt()))->setTextAlignment(AlignRight);
                table->setText(rr, "createTime", file["createTime"].toString());
                table->setData(rr, 0, file["fileId"].toString());
            }
            connect(table, &Table::cellDoubleClicked, &dlg, [=, &dlg](int row) {
                fdFileName->setText(table->text(row, "name"));
                fileId = table->data(row, 0).toString();
                filePath = "";
                dlg.accept();
            });
            vBox->addWidget(table);

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

            auto btnOk = new QPushButton("确定");
            btnOk->setMinimumWidth(80);
            connect(btnOk, &QPushButton::clicked, &dlg, [=, &dlg] {
                auto sels = table->selectedRanges();
                if(sels.isEmpty()) {
                    QMessageBox::warning(&dlg, "Warning", "请选择文件");
                    return;
                }
                auto row = sels[0].topRow();
                fdFileName->setText(table->text(row, "name"));
                fileId = table->data(row, 0).toString();
                filePath = "";
                dlg.accept();
            });
            hBox->addWidget(btnOk);
            hBox->addStretch();

            auto btnClose = new QPushButton("关闭");
            btnClose->setMinimumWidth(80);
            connect(btnClose, &QPushButton::clicked, &dlg, &QDialog::reject);
            hBox->addWidget(btnClose);
            hBox->addStretch();

            dlg.exec();
        });
    });

    auto btnUpgread = new QPushButton(tr("Upgrade"));
    btnUpgread->setMinimumSize(QSize(80, 30));
    btnUpgread->setProperty("ssType", "progManageTool");
    connect(btnUpgread, &QPushButton::clicked, this, [=] {
        auto fileName = fdFileName->text();
        if(fileName.length() < 3) return;
        int cnt = table->topLevelItemCount();
        QList<wUpgradeApkItem *> items;
        for(int i=0; i<cnt; i++) if(table->topLevelItem(i)->checkState(0) == Qt::Checked) {
            auto item = static_cast<wUpgradeApkItem *>(table->topLevelItem(i));
            if(item->isUpdating) {
                QMessageBox::information(this, tr("Tip"), tr("Is upgrading now. Please wait"));
                return;
            }
            if(item->mCard->bPassword && item->mCard->m_bLockStatus && item->m_lockFlag) {
                item->setResult(tr("This screen is encrypted"), Qt::red);
                return;
            }
            items.append(item);
        }
        if(items.isEmpty()) {
            QMessageBox::information(this, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        QByteArray fileData;
        if(! filePath.isEmpty()) {
            QFile file(filePath);
            if(! file.exists()) return;
            if(! file.open(QIODevice::ReadOnly)) return;
            fileData = file.readAll();
            file.close();
        } else if(! fileId.isEmpty()) {
            auto waitingDlg = new WaitingDlg(this, tr("Downloading Online File")+" ...");
            waitingDlg->show();
            auto reply = NetReq("https://www.ledokcloud.com/aips4/sys/file/download/"+fileId).timeout(120000).get();
            QEventLoop loop;
            connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
            connect(reply, &QNetworkReply::downloadProgress, waitingDlg, [=](qint64 bytesReceived, qint64 bytesTotal) {
                waitingDlg->fdText->setText(tr("Downloading Online File")+" "+QString::number(bytesReceived*100/bytesTotal)+" %");
            });
            loop.exec(QEventLoop::ExcludeUserInputEvents);
            waitingDlg->close();
            auto err = errStr(reply);
            fileData = reply->readAll();
            if(! err.isEmpty()) {
                if(! fileData.isEmpty()) err += "\n"+fileData;
                QMessageBox::critical(this, tr("Error"), err);
                return;
            }
            if(fileData.isEmpty()) {
                QMessageBox::critical(this, tr("Error"), tr("Online file is empty"));
                return;
            }
        }
        auto nameBytes = fileName.toUtf8();
        auto Boundary = "----QtLedOK_.oOo._"+QUuid::createUuid().toByteArray(QUuid::WithoutBraces);
        QByteArray data;
        data.append("--").append(Boundary).append("\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\n10005\r\n");
        data.append("--").append(Boundary).append("\r\nContent-Disposition: form-data; name=\"").append(nameBytes).append("\"; filename=\"").append(nameBytes).append("\"\r\n\r\n").append(fileData).append("\r\n");
        data.append("--").append(Boundary).append("--\r\n");
        bool isApk = ! fileName.endsWith(".rpd", Qt::CaseInsensitive);
        foreach(auto item, items) {
            item->setResult(tr("Uploading")+" ...");
            item->mProgress->setValue(0);
            item->isUpdating = true;
            NetReq req("http://"+item->mCard->m_strCardIp+":2016/upload?type="+(isApk ? "software":"hardware"));
            auto reply = req.timeout(120000).type("multipart/form-data; boundary="+Boundary).post(data);
            connect(reply, &QNetworkReply::uploadProgress, item, [item](qint64 bytesSent, qint64 bytesTotal) {
                if(bytesTotal<=0) return;
                item->mProgress->setValue(bytesSent*100/bytesTotal);
            });
            connect(reply, &QNetworkReply::finished, item, [=] {
                QString err = errStrWithData(reply);
                if(! err.isEmpty()) {
                    item->setResult(tr("Upload error")+": "+err, Qt::red);
                    item->isUpdating = false;
                    return;
                }
                item->mProgress->setValue(100);
                item->setResult(tr("Installing")+" ...");
                QJsonObject json;
                if(isApk) {
                    json.insert("_id", "UpgradeSoftware");
                    json.insert("_type", "UpgradeSoftware");
                    json.insert("fileName", fileName);
                    json.insert("isCustom", true);
                } else {
                    json.insert("_id", "SynchronousHardwareVersion");
                    json.insert("_type", "SynchronousHardwareVersion");
                }
                auto reply = NetReq("http://"+item->mCard->m_strCardIp+":2016/settings").timeout(120000).post(json);
                connect(reply, &QNetworkReply::finished, item, [=] {
                    item->isUpdating = false;
                    QString err = errStrWithData(reply);
                    if(! err.isEmpty()) {
                        item->setResult(tr("Install error")+": "+err, Qt::red);
                        return;
                    }
                    item->setResult(tr("Install success"), Qt::darkGreen);
                    if(isApk) item->OnCheckSoftVersions();
                    else item->OnCheckFpgaVersions();
                });
            });
        }
    });
    hBox->addWidget(btnUpgread);
    hBox->addStretch();

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

    auto fdApk = new QComboBox;
    fdApk->setMinimumWidth(200);
    fdApk->setEditable(true);
    fdApk->addItem("com.xixun.xixunplayer");
    fdApk->addItem("com.xixun.joey.cardsystem");
    fdApk->addItem("com.xixun.joey.systemcore");
    fdApk->addItem("net.sysolution.taxiapp");
    fdApk->addItem("net.sysolution.starter");
    fdApk->addItem("com.xixun.display");
    fdApk->addItem("com.xixun.xy.conn");
    fdApk->addItem("com.xixun.xy.update");
    fdApk->addItem("net.sysolution.basicapp");
    hBox->addWidget(fdApk);

    auto btnUninstall = new QPushButton(tr("Uninstall"));
    btnUninstall->setMinimumSize(80, 30);
    btnUninstall->setProperty("ssType", "progManageTool");
    connect(btnUninstall, &QPushButton::clicked, this, [this, fdApk] {
        auto strApkName = fdApk->currentText();
        if(strApkName.isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), "APK is Empty");
            return;
        }
        if(! strApkName.endsWith(".xixunplayer") && ! strApkName.endsWith(".taxiapp") && QMessageBox::warning(gMainWin, tr("Reminder"), tr("Reminder: Uninstalling this program may cause the device to offline, cannot be found, lost configs and have a black screen. Please uninstall with caution!")+"\n"+tr("Do you want to continue?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) return;
        int cnt = table->topLevelItemCount();
        for(int i=0; i<cnt; i++) if(table->topLevelItem(i)->checkState(0) == Qt::Checked) {
            auto item = static_cast<wUpgradeApkItem *>(table->topLevelItem(i));
            item->setResult(tr("Uninstalling")+" ...");
            QJsonObject json;
            json.insert("_id", "UninstallSoftware");
            json.insert("_type", "UninstallSoftware");
            json.insert("packageName", strApkName);
            auto reply = NetReq("http://"+item->mCard->m_strCardIp+":2016/settings").timeout(120000).post(json);
            connect(reply, &QNetworkReply::finished, this, [reply, item, strApkName] {
                QString err = errStrWithData(reply);
                if(! err.isEmpty()) {
                    item->setResult(tr("Uninstall error")+": "+err, Qt::red);
                    return;
                }
                item->setResult(tr("Uninstall success"), Qt::darkGreen);
            });
        }
    });
    hBox->addWidget(btnUninstall);

    auto btnCheck = new QPushButton(tr("check running state"));
    btnCheck->setMinimumSize(QSize(140, 30));
    btnCheck->setProperty("ssType", "progManageTool");
    connect(btnCheck, &QPushButton::clicked, this, [this, fdApk] {
        QString strApkName = fdApk->currentText();
        int cnt = table->topLevelItemCount();
        for(int i=0; i<cnt; i++) if(table->topLevelItem(i)->checkState(0) == Qt::Checked) {
            auto item = static_cast<wUpgradeApkItem *>(table->topLevelItem(i));
            item->setResult(tr("Check apk running status"));
            QJsonObject json;
            json.insert("_id", "IsSoftwareRunning");
            json.insert("_type", "IsSoftwareRunning");
            json.insert("packageName", strApkName);
            auto reply = NetReq("http://"+item->mCard->m_strCardIp+":2016/settings").timeout(120000).post(json);
            connect(reply, &QNetworkReply::finished, this, [reply, item, strApkName] {
                QJsonDocument json;
                QString err = errStrWithData(reply, &json);
                if(! err.isEmpty()) {
                    item->setResult(tr("Check error")+": "+err, Qt::red);
                    return;
                }
                if(json["running"].toBool()) item->setResult(tr("Running"), Qt::darkGreen);
                else item->setResult(tr("Not running"), Qt::red);
            });
        }
    });
    hBox->addWidget(btnCheck);


    hBox = new HBox(vBox);
    auto label = new QLabel;
    hBox->addWidget(label);

    hBox->addStretch();

    auto btnRefresh = new QPushButton(tr("Refresh"));
    btnRefresh->setMinimumSize(QSize(0, 30));
    btnRefresh->setProperty("ssType", "progManageTool");
    connect(btnRefresh, &QPushButton::clicked, this, [this, label] {
        table->clear();
        table->onCheckAll(false);
        int iCount = gDevicePanel->mLedCards.count();
        for(int i=0;i<iCount;i++) onAddLedCard(gDevicePanel->mLedCards.at(i));
        label->setText(tr("All")+":"+QString::number(iCount));
    });
    hBox->addWidget(btnRefresh);

    auto txtSearch = new QLineEdit();
    txtSearch->setClearButtonEnabled(true);
    txtSearch->setMaximumWidth(200);
    txtSearch->addAction(new QAction(QIcon(":/res/program/bnSearch.png"), ""), QLineEdit::LeadingPosition);
    connect(txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &)));
    hBox->addWidget(txtSearch);


    table = new LoQTreeWidget();
    table->setProperty("ssType", "topList");
    vBox->addWidget(table);

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

    auto pushButtonCancel = new QPushButton(tr("Cancel"));
    pushButtonCancel->setMinimumSize(QSize(0, 30));
    pushButtonCancel->setProperty("ssType", "progManageTool");
    connect(pushButtonCancel, &QPushButton::clicked, this, &UpgradeApkDialog::reject);
    hBox->addWidget(pushButtonCancel);


    m_headerItem = new QTreeWidgetItem();
    for(int i=1; i<Upgrade_END; i++) if(i!=Upgrade_Remark) m_headerItem->setTextAlignment(i, Qt::AlignCenter);
    m_headerItem->setText(Upgrade_Check, "");
    m_headerItem->setText(Upgrade_SCREEN_ID, tr("Screen ID"));
    m_headerItem->setText(Upgrade_ONLINE, tr("Online"));
    m_headerItem->setText(Upgrade_SCREEN_IP, tr("Screen IP"));
    m_headerItem->setText(Upgrade_ENCRYPT, tr("Security"));
    m_headerItem->setText(Upgrade_REMARK_NAME, tr("Remark Name"));
    m_headerItem->setText(Upgrade_PROGRESS, tr("Progress"));
    m_headerItem->setText(Upgrade_Remark, tr("State"));
    m_headerItem->setText(Upgrade_XIXUNPLAYER_VERSION, tr("xixunplayer"));
    m_headerItem->setText(Upgrade_CARDSYSTEM_VERSION, tr("cardsystem"));
    m_headerItem->setText(Upgrade_STARTER_VERSION, tr("starter"));
    m_headerItem->setText(Upgrade_TAXIAPP_VERSION, tr("taxiapp"));
    m_headerItem->setText(Upgrade_DISPLAYER_VERSION, tr("displayer"));
    m_headerItem->setText(Upgrade_FPAG_VERSION, tr("FPGA"));
    m_headerItem->setText(Upgrade_CONNECTION_VERSION, tr("connection"));
    m_headerItem->setText(Upgrade_UPDATE_VERSION, tr("update"));

    table->setHeaderItem(m_headerItem);
    table->header()->setSectionResizeMode(Upgrade_Check, QHeaderView::Fixed);
    table->setColumnWidth(Upgrade_Check, 40);
    table->header()->setSectionResizeMode(Upgrade_SCREEN_ID, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_ONLINE, QHeaderView::Fixed);
    table->setColumnWidth(Upgrade_ONLINE, 40);
    table->header()->setSectionResizeMode(Upgrade_SCREEN_IP, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_ENCRYPT, QHeaderView::Fixed);
    table->setColumnWidth(Upgrade_ENCRYPT, 40);
    table->header()->setSectionResizeMode(Upgrade_PROGRESS, QHeaderView::Fixed);
    table->setColumnWidth(Upgrade_PROGRESS, 100);
    table->header()->setSectionResizeMode(Upgrade_XIXUNPLAYER_VERSION, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_CARDSYSTEM_VERSION, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_STARTER_VERSION, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_TAXIAPP_VERSION, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_DISPLAYER_VERSION, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_FPAG_VERSION, QHeaderView::Fixed);
    table->setColumnWidth(Upgrade_FPAG_VERSION, 100);
    table->header()->setSectionResizeMode(Upgrade_Remark, QHeaderView::Stretch);
    table->header()->setSectionResizeMode(Upgrade_REMARK_NAME, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_CONNECTION_VERSION, QHeaderView::ResizeToContents);
    table->header()->setSectionResizeMode(Upgrade_UPDATE_VERSION, QHeaderView::ResizeToContents);

    int iCount = gDevicePanel->mLedCards.count();
    for(int i=0; i<iCount; i++) onAddLedCard(gDevicePanel->mLedCards.at(i));
    label->setText(tr("All")+":"+QString::number(iCount));
}

void UpgradeApkDialog::onAddLedCard(LedCard *card) {
     int iExistFlg=0;
     int cnt = table->topLevelItemCount();
     for(int i=0; i<cnt; i++) {
         QString strTempCardId=static_cast<wUpgradeApkItem*>(table->topLevelItem(i))->mCard->m_strCardId;
         if(strTempCardId == card->m_strCardId) {
             iExistFlg=1;
             static_cast<wUpgradeApkItem*>(table->topLevelItem(i))->SetItemParam(card);
             break;
         }
     }
     if(iExistFlg==0) new wUpgradeApkItem(card, table, this);
}

void UpgradeApkDialog::keyPressEvent(QKeyEvent *ev) {
    if(ev->key() == Qt::Key_F3) {
         QMessageBox::warning(this, "Tip", tr("The encrypted control card can be upgraded directly"));
         int cnt = table->topLevelItemCount();
         for(int i=0; i<cnt; i++) static_cast<wUpgradeApkItem *>(table->topLevelItem(i))->m_lockFlag = false;
    }
}
void UpgradeApkDialog::FilterProgram(const QString &strtemp)
{
    if (strtemp.isEmpty())	//显示全部
    {
        for (int i = 0; i< table->topLevelItemCount(); ++i)
        {
            QTreeWidgetItem* topItem = table->topLevelItem(i);
            table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);
        }
    }
    else
    {
        QList<QTreeWidgetItem*> resultList = table->findItems(strtemp, Qt::MatchContains,Upgrade_SCREEN_ID);	//搜索结果
        if (resultList.size() > 0)
        {
            //QMessageBox::warning(this, "Export", QString(resultList.size()));
            for (int i = 0; i< table->topLevelItemCount(); ++i)
            {
                QTreeWidgetItem* topItem = table->topLevelItem(i);
                if (resultList.contains(topItem))
                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                else
                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
            }
        }
        else {

            QList<QTreeWidgetItem*> resultList6 = table->findItems(strtemp, Qt::MatchContains,Upgrade_REMARK_NAME);	//搜索结果
            if (resultList6.size() > 0)
            {
                //QMessageBox::warning(this, "Export", QString(resultList.size()));
                for (int i = 0; i< table->topLevelItemCount(); ++i)
                {
                    QTreeWidgetItem* topItem = table->topLevelItem(i);
                    if (resultList6.contains(topItem))
                        table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                    else
                        table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                }
            }
            else {


                //QMessageBox::warning(this, "Export", "FilterProgram");
                QList<QTreeWidgetItem*> resultList1 = table->findItems(strtemp, Qt::MatchContains,Upgrade_XIXUNPLAYER_VERSION);	//搜索结果
                if (resultList1.size() > 0)
                {
                    //QMessageBox::warning(this, "Export", QString(resultList.size()));
                    for (int i = 0; i< table->topLevelItemCount(); ++i)
                    {
                        QTreeWidgetItem* topItem = table->topLevelItem(i);
                        if (resultList1.contains(topItem))
                            table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                        else
                            table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                    }
                }
                else {
                    QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_SCREEN_IP);	//搜索结果
                    if (resultList2.size() > 0)
                    {
                        //QMessageBox::warning(this, "Export", QString(resultList.size()));
                        for (int i = 0; i< table->topLevelItemCount(); ++i)
                        {
                            QTreeWidgetItem* topItem = table->topLevelItem(i);
                            if (resultList2.contains(topItem))
                                table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                            else
                                table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                        }
                    }
                    else {
                        QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_XIXUNPLAYER_VERSION);	//搜索结果
                        if (resultList2.size() > 0)
                        {
                            //QMessageBox::warning(this, "Export", QString(resultList.size()));
                            for (int i = 0; i< table->topLevelItemCount(); ++i)
                            {
                                QTreeWidgetItem* topItem = table->topLevelItem(i);
                                if (resultList2.contains(topItem))
                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                else
                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                            }
                        }
                        else {
                            QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_CARDSYSTEM_VERSION);	//搜索结果
                            if (resultList2.size() > 0)
                            {
                                //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                for (int i = 0; i< table->topLevelItemCount(); ++i)
                                {
                                    QTreeWidgetItem* topItem = table->topLevelItem(i);
                                    if (resultList2.contains(topItem))
                                        table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                    else
                                        table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                }
                            }
                            else {
                                QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_TAXIAPP_VERSION);	//搜索结果
                                if (resultList2.size() > 0)
                                {
                                    //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                    for (int i = 0; i< table->topLevelItemCount(); ++i)
                                    {
                                        QTreeWidgetItem* topItem = table->topLevelItem(i);
                                        if (resultList2.contains(topItem))
                                            table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                        else
                                            table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                    }
                                }
                                else {
                                    QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_DISPLAYER_VERSION);	//搜索结果
                                    if (resultList2.size() > 0)
                                    {
                                        //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                        for (int i = 0; i< table->topLevelItemCount(); ++i)
                                        {
                                            QTreeWidgetItem* topItem = table->topLevelItem(i);
                                            if (resultList2.contains(topItem))
                                                table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                            else
                                                table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                        }
                                    }
                                    else {
                                        QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_STARTER_VERSION);	//搜索结果
                                        if (resultList2.size() > 0)
                                        {
                                            //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                            for (int i = 0; i< table->topLevelItemCount(); ++i)
                                            {
                                                QTreeWidgetItem* topItem = table->topLevelItem(i);
                                                if (resultList2.contains(topItem))
                                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                                else
                                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                            }
                                        }
                                        else {
                                            QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_CONNECTION_VERSION);	//搜索结果
                                            if (resultList2.size() > 0)
                                            {
                                                //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                                for (int i = 0; i< table->topLevelItemCount(); ++i)
                                                {
                                                    QTreeWidgetItem* topItem = table->topLevelItem(i);
                                                    if (resultList2.contains(topItem))
                                                        table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                                    else
                                                        table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                                }
                                            }
                                            else {
                                                QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_UPDATE_VERSION);	//搜索结果
                                                if (resultList2.size() > 0)
                                                {
                                                    //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                                    for (int i = 0; i< table->topLevelItemCount(); ++i)
                                                    {
                                                        QTreeWidgetItem* topItem = table->topLevelItem(i);
                                                        if (resultList2.contains(topItem))
                                                            table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                                        else
                                                            table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                                    }
                                                }
                                                else {
                                                    QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_FPAG_VERSION);	//搜索结果
                                                    if (resultList2.size() > 0)
                                                    {
                                                        //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                                        for (int i = 0; i< table->topLevelItemCount(); ++i)
                                                        {
                                                            QTreeWidgetItem* topItem = table->topLevelItem(i);
                                                            if (resultList2.contains(topItem))
                                                                table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                                            else
                                                                table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                                        }
                                                    }
                                                    else {
                                                        QList<QTreeWidgetItem*> resultList2 = table->findItems(strtemp, Qt::MatchContains,Upgrade_Remark);	//搜索结果
                                                        if (resultList2.size() > 0)
                                                        {
                                                            //QMessageBox::warning(this, "Export", QString(resultList.size()));
                                                            for (int i = 0; i< table->topLevelItemCount(); ++i)
                                                            {
                                                                QTreeWidgetItem* topItem = table->topLevelItem(i);
                                                                if (resultList2.contains(topItem))
                                                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                                                                else
                                                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                                            }
                                                        }
                                                        else {
                                                            for (int i = 0; i< table->topLevelItemCount(); ++i)
                                                            {
                                                                QTreeWidgetItem* topItem = table->topLevelItem(i);
                                                                    table->setRowHidden(i,table->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
