#include "sendprogramdialog.h"
#include "tools.h"
#include "cfg.h"
#include <QAction>
#include <QLineEdit>
#include <QHeaderView>
#include <QVBoxLayout>

SendProgramDialog::SendProgramDialog(QString progName, QWidget *parent) : QDialog(parent), mProgName(progName) {
    setWindowFlag(Qt::WindowMaximizeButtonHint);
    setWindowTitle(tr("Publish")+" "+mProgName);
    resize(1024, 700);
    auto vBox = new QVBoxLayout(this);
    auto hBox = new QHBoxLayout();

    label = new QLabel(tr("success info"));
    hBox->addWidget(label);

    hBox->addStretch();

    auto pushButtonRefresh = new QPushButton(tr("Refresh"));
    pushButtonRefresh->setProperty("ssType", "progManageTool");
    connect(pushButtonRefresh, SIGNAL(clicked()),this, SLOT(onRefresh()));
    hBox->addWidget(pushButtonRefresh);

    auto txtSearch = new QLineEdit();
    txtSearch->setFixedWidth(150);
    txtSearch->setClearButtonEnabled(true);
    txtSearch->setStyleSheet("QLineEdit{border: 2px solid #aaaaaa; padding: 2px;}");
    txtSearch->addAction(new QAction(QIcon(":/res/program/bnSearch.png"), QString()), QLineEdit::LeadingPosition);
    connect(txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &)));
    hBox->addWidget(txtSearch);

    vBox->addLayout(hBox);

    wDevicePublishList = new LoQTreeWidget();
    wDevicePublishList->setProperty("ssType", "topList");
    m_headerItem = new QTreeWidgetItem();
    m_headerItem->setTextAlignment(1, Qt::AlignHCenter | Qt::AlignVCenter);
    for(int i=1; i<ENUM_DEVICE_PUBLISH_HEADE_END; i++) m_headerItem->setTextAlignment(i, Qt::AlignCenter);
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 0, "");
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, tr("Screen ID"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 0, tr("Online"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, tr("Screen IP"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, tr("Screen Size"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT,0,tr("Security"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, tr("Remark Name"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 0, tr("Progress"));
    m_headerItem->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, tr("Remarks"));
    wDevicePublishList->setHeaderItem(m_headerItem);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_CHECK, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, QHeaderView::Fixed);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, QHeaderView::Interactive);
    wDevicePublishList->header()->setSectionResizeMode(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, QHeaderView::Stretch);
    wDevicePublishList->header()->setStretchLastSection(false);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_CHECK, 52);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 130);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 130);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 88);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ONLINE, 50);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, 52);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 160);
    wDevicePublishList->setColumnWidth(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, 120);
    vBox->addWidget(wDevicePublishList);

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

    auto btnPublish = new QPushButton(tr("Publish"));
    connect(btnPublish, &QPushButton::clicked, this, [this] {
        if(mWaitCnt > 0) return;
        int cnt = wDevicePublishList->topLevelItemCount();
        int sentCnt{0};
        for(int i=0; i<cnt; i++) {
            auto item = wDevicePublishList->topLevelItem(i);
            if(item->checkState(0) != Qt::Checked) continue;
            auto row = static_cast<wProgramPublishItem*>(item);
            if(row->mIsSending) continue;
            if(row->mLedCard->bPassword && row->mLedCard->m_bLockStatus) {
                row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, tr("This screen is encrypted"));
                row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red);
                continue;
            }
            row->fdProgress->setValue(0);
            if(sentCnt>=5) {
                row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "    等待中 ...");
                row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::black);
                mWaitCnt++;
                continue;
            }
            row->mIsSending = true;
            row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "");
            auto sendProg = new SendProgThread(programsDir()+"/"+mProgName+"_tmp", row->mLedCard->m_strCardIp, 3333);
            connect(sendProg, &SendProgThread::emErr, row, [this, row](QString strTip) {
                row->mIsSending = false;
                if(strTip=="OK") {
                    row->setCheckState(0, Qt::Unchecked);
                    row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "OK");
                    row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::darkGreen);
                } else {
                    row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip);
                    row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red);
                }
                sendNext();
            });
            connect(sendProg, &SendProgThread::emProgress, row->fdProgress, &QProgressBar::setValue);
            connect(this, &SendProgramDialog::stopAllThd, sendProg, &SendProgThread::stop);
            sendProg->start();
            sentCnt++;
        }
    });
    btnPublish->setProperty("ssType", "progManageTool");
    hBox->addWidget(btnPublish);

    auto btnCancel = new QPushButton(tr("Cancel"));
    connect(btnCancel, &QPushButton::clicked, this, &QWidget::close);
    btnCancel->setProperty("ssType", "progManageTool");
    hBox->addWidget(btnCancel);

    vBox->addLayout(hBox);

    onRefresh();

    auto timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &SendProgramDialog::onRefresh);
    timer->start(60000);
}
void SendProgramDialog::closeEvent(QCloseEvent *) {
    emit stopAllThd();
}
void SendProgramDialog::sendNext() {
    if(mWaitCnt <= 0) return;
    int cnt = wDevicePublishList->topLevelItemCount();
    for(int i=0; i<cnt; i++) {
        auto item = wDevicePublishList->topLevelItem(i);
        if(item->checkState(0) != Qt::Checked) continue;
        auto row = static_cast<wProgramPublishItem*>(item);
        if(row->mIsSending) continue;
        if(row->mLedCard->bPassword && row->mLedCard->m_bLockStatus) continue;
        if(! row->data(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0).toString().startsWith("    "))  continue;
        row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "");
        row->fdProgress->setValue(0);
        row->mIsSending = true;
        mWaitCnt--;
        auto sendProg = new SendProgThread(programsDir()+"/"+mProgName+"_tmp", row->mLedCard->m_strCardIp, 3333);
        connect(sendProg, &SendProgThread::emErr, row, [this, row](QString strTip) {
            row->mIsSending = false;
            if(strTip=="OK") {
                row->setCheckState(0, Qt::Unchecked);
                row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, "OK");
                row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::darkGreen);
            } else {
                row->setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip);
                row->setForeground(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::red);
            }
            sendNext();
        });
        connect(sendProg, &SendProgThread::emProgress, row->fdProgress, &QProgressBar::setValue);
        connect(this, &SendProgramDialog::stopAllThd, sendProg, &SendProgThread::stop);
        sendProg->start();
        return;
    }
}

void SendProgramDialog::onRefresh() {
    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 SendProgramDialog::onAddLedCard(LedCard *p) {
     int iExistFlg=0;
     int cnt = wDevicePublishList->topLevelItemCount();
     for(int i=0; i<cnt; i++) {
         QString strTempCardId=static_cast<wProgramPublishItem*>(wDevicePublishList->topLevelItem(i))->mLedCard->m_strCardId;
         if(strTempCardId == p->m_strCardId) {
             iExistFlg=1;
             static_cast<wProgramPublishItem*>(wDevicePublishList->topLevelItem(i))->SetItemParam(p);
             break;
         }
     }
     if(iExistFlg==0) new wProgramPublishItem(p, wDevicePublishList, this, mProgName, programsDir());
}
void SendProgramDialog::FilterProgram(const QString &strtemp)
{
    if (strtemp.isEmpty())	//显示全部
    {
        for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i)
        {
            QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i);
            wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false);
        }
    }
    else
    {
        QList<QTreeWidgetItem*> resultList = wDevicePublishList->findItems(strtemp, Qt::MatchContains,ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID);	//搜索结果
        if (resultList.size() > 0)
        {
            //QMessageBox::warning(this, "Export", QString(resultList.size()));
            for (int i = 0; i< wDevicePublishList->topLevelItemCount(); ++i)
            {
                QTreeWidgetItem* topItem = wDevicePublishList->topLevelItem(i);
                if (resultList.contains(topItem))
                    wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                else
                    wDevicePublishList->setRowHidden(i,wDevicePublishList->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
            }
        }
        else {

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


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