
#include "tipdialog.h"
#include "ui_tipdialog.h"
#include "globaldefine.h"
#include <LoQClass/loqtreewidget.h>
#include <QProgressBar>
#include <QFileDialog>
#include <QHeaderView>
#include <LoUIClass/x_uimsgboxok.h>
#include <loappconfig.h>

#include <wProgramManager/wexportprogramitem.h>
TipDialog::TipDialog(QWidget *parent) :
    LoQDialog(parent),
    ui(new Ui::TipDialog)
{
    ui->setupUi(this);
}
TipDialog::TipDialog(QWidget *parent,int iTipDlgType):
    LoQDialog(parent),
    ui(new Ui::TipDialog)
{
    ui->setupUi(this);

    connect(this, SIGNAL(accepted()), this, SLOT(onAccepted()));
    m_iTipDlgType=iTipDlgType;
    switch(iTipDlgType)
    {
        case ENUM_IMPORT_DLG://Import对话框
        {
/*            ui->bnOK->setEnabled(false);
            ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;");
            ui->label->setText(tr("Import"));
            QLabel *pLablePaht = new QLabel(this);
            pTextPath = new QLineEdit(this);
            //QSpacerItem Q1 = new QSpacerItem();
            pLablePaht->setText(tr("Path")+tr(":"));
            QPushButton *pSelectButton = new QPushButton(this);
            //ui->verticalSpacer->changeSize(20, 20, QSizePolicy::Preferred, QSizePolicy::Expanding);

            QRect rect;
            rect = pLablePaht->geometry();
            rect.setX(rect.x()+rect.width());
            rect.setWidth(this->width()-8-pLablePaht->width()-pSelectButton->width());
            pTextPath->setGeometry(rect);
            pSelectButton->setText(tr("browse"));
            pSelectButton->adjustSize();
            ui->horizontalLayout_content->setSpacing(2);
            ui->horizontalLayout_content->addWidget(pLablePaht);
            ui->horizontalLayout_content->setSpacing(2);
            ui->horizontalLayout_content->addWidget(pTextPath);
            ui->horizontalLayout_content->setSpacing(2);
            ui->horizontalLayout_content->addWidget(pSelectButton);
            connect(pSelectButton,SIGNAL(clicked()),this,SLOT(OnSelectDir()));
            connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(OnImportPro));
            connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(reject()));
 */
            //
        ui->bnOK->setEnabled(false);
        ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;");
        this->resize(600,400);
        setMinimumHeight(400);
        ui->bnOK->setText(tr("Import"));
        ui->bnCancel->setText(tr("Done"));
        ui->label->setText(tr("Import"));
        QLabel *pLablePaht = new QLabel(this);
        pTextPath = new QLineEdit(this);
        pLablePaht->setText(tr("Path")+tr(":"));
        QPushButton *pSelectButton = new QPushButton(this);
        //ui->verticalSpacer->changeSize(20, 20, QSizePolicy::Preferred, QSizePolicy::Expanding);

        QRect rect;
        rect = pLablePaht->geometry();
        rect.setX(rect.x()+rect.width());
        rect.setWidth(this->width()-8-pLablePaht->width()-pSelectButton->width());
        pTextPath->setGeometry(rect);
        pSelectButton->setText(tr("browse"));
        pSelectButton->adjustSize();

        //创建一个水平布局，水平布局里左右留12个0空格，中间放入页部件
        m_pLayoutSelectDirPath = new QHBoxLayout();
        m_pLayoutSelectDirPath->setSpacing(2);
        m_pLayoutSelectDirPath->addWidget(pLablePaht);
        m_pLayoutSelectDirPath->setSpacing(2);
        m_pLayoutSelectDirPath->addWidget(pTextPath);
        m_pLayoutSelectDirPath->setSpacing(2);
        m_pLayoutSelectDirPath->addWidget(pSelectButton);
        connect(pSelectButton,SIGNAL(clicked()),this,SLOT(OnSelectDir()));
        //创建一个垂直布局
        QVBoxLayout *pVLayout = new QVBoxLayout();
        pVLayout->addLayout(m_pLayoutSelectDirPath, 0);//增加路径选择区到垂直布局的0区
        pVLayout->setSpacing(0);
        pVLayout->addSpacing(10);
        //增加列表选型到垂直布局的1区
        //创建列表控件
         ctrlProgramList = new QTableWidget(this);
         ctrlProgramList->setColumnCount(2);
         ctrlProgramList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
         ctrlProgramList->verticalHeader()->hide();
         QStringList starr;
         starr.append(tr("Solution Name"));
         starr.append(tr("Progress"));
         ctrlProgramList->setHorizontalHeaderLabels(starr);
         //根据节目主窗口选中的节目check选型，初始化Tree控件
        //把垂直布局的内容填充到内容区
        pVLayout->addWidget(ctrlProgramList,1);
        ctrlProgramList->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
        ui->horizontalLayout_content->addLayout(pVLayout);
        connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(OnImportPro()));
        connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(accept()));
        }
        break;
        case ENUM_DELETE_DLG:
        {
            ui->label->setText(tr("Delete"));
            QLabel *pLablePaht = new QLabel(this);
            pLablePaht->setText(tr("You will delete the selected solution(s),are you sure?"));
            ui->horizontalLayout_content->addWidget(pLablePaht);
            connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(accept()));
            connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(reject()));
        }
        break;
        case ENUM_SAVEAS_DLG:
        {
            setFixedWidth(300);
            ui->label->setText(tr("Save as"));
            QLabel *pLablePaht = new QLabel(this);
            pTextPath = new QLineEdit(this);
            //QSpacerItem Q1 = new QSpacerItem();
            pLablePaht->setText(tr("Save as")+tr(":"));

            QRect rect;
            rect = pLablePaht->geometry();
            rect.setX(rect.x()+rect.width());
            rect.setWidth(this->width()-8-pLablePaht->width());
            pTextPath->setGeometry(rect);
            ui->horizontalLayout_content->setSpacing(2);
            ui->horizontalLayout_content->addWidget(pLablePaht);
            ui->horizontalLayout_content->setSpacing(2);
            ui->horizontalLayout_content->addWidget(pTextPath);
            connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(accept()));
            connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(reject()));
        }
        break;
        default:
        break;

    }


}
TipDialog::TipDialog(QWidget *parent,int iTipDlgType,QStringList *listProgramName,int iTipType):
    LoQDialog(parent),
    ui(new Ui::TipDialog)
{
    ui->setupUi(this);

    connect(this, SIGNAL(accepted()), this, SLOT(onAccepted()));
    m_iTipDlgType=iTipDlgType;
    switch(iTipDlgType)
    {
        case ENUM_EXPORT_DLG:
        {
            ui->bnOK->setEnabled(false);
            ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;");
            this->resize(600,400);
            setMinimumHeight(400);
            ui->bnOK->setText(tr("Export"));
            ui->bnCancel->setText(tr("Done"));
            ui->label->setText(tr("Export"));
            QLabel *pLablePaht = new QLabel(this);
            pTextPath = new QLineEdit(this);
            pLablePaht->setText(tr("Path")+tr(":"));
            QPushButton *pSelectButton = new QPushButton(this);
            //ui->verticalSpacer->changeSize(20, 20, QSizePolicy::Preferred, QSizePolicy::Expanding);

            QRect rect;
            rect = pLablePaht->geometry();
            rect.setX(rect.x()+rect.width());
            rect.setWidth(this->width()-8-pLablePaht->width()-pSelectButton->width());
            pTextPath->setGeometry(rect);
            pSelectButton->setText(tr("browse"));
            pSelectButton->adjustSize();

            //创建一个水平布局，水平布局里左右留12个0空格，中间放入页部件
            QHBoxLayout *pLayoutSelectDirPath = new QHBoxLayout();
            pLayoutSelectDirPath->setSpacing(2);
            pLayoutSelectDirPath->addWidget(pLablePaht);
            pLayoutSelectDirPath->setSpacing(2);
            pLayoutSelectDirPath->addWidget(pTextPath);
            pLayoutSelectDirPath->setSpacing(2);
            pLayoutSelectDirPath->addWidget(pSelectButton);
            connect(pSelectButton,SIGNAL(clicked()),this,SLOT(OnSelectDir()));
            //创建一个垂直布局
            QVBoxLayout *pVLayout = new QVBoxLayout();
            pVLayout->addLayout(pLayoutSelectDirPath, 0);//增加路径选择区到垂直布局的0区
            pVLayout->setSpacing(0);
            pVLayout->addSpacing(10);
            //增加列表选型到垂直布局的1区
            //创建列表控件
             ctrlProgramList = new QTableWidget(this);
             ctrlProgramList->setRowCount(listProgramName->count());
             ctrlProgramList->setColumnCount(2);
             ctrlProgramList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
             ctrlProgramList->verticalHeader()->hide();

             QStringList starr;
             starr.append(tr("Solution Name"));
             starr.append(tr("Progress"));
             ctrlProgramList->setHorizontalHeaderLabels(starr);
             //根据节目主窗口选中的节目check选型，初始化Tree控件
             for (int i = 0; i < listProgramName->count(); i++)
             {
                 //progresss.append(progress);
                 wExportProgramItem *topLevelItem = new wExportProgramItem(ctrlProgramList,listProgramName->at(i),i);     //创建一个 TreeItem 容器用于后来装载控件
                 ctrlProgramList->setItem(i,0,topLevelItem);
             }
            //把垂直布局的内容填充到内容区
            pVLayout->addWidget(ctrlProgramList,1);
            ctrlProgramList->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
            ui->horizontalLayout_content->addLayout(pVLayout);
            connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(OnExportButton()));
            connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(accept()));
        }
        break;
        case ENUM_SELECT_NETWORK:
        {
            setMinimumHeight(400);
            ui->bnOK->setText(tr("OK"));
            ui->bnCancel->setText(tr("Cancel"));
            ui->label->setText(tr("Select the network to connect to the device"));

            //创建一个垂直布局
            QVBoxLayout *pVLayout = new QVBoxLayout();
            //增加列表选型到垂直布局的1区
            //创建列表控件
            QTableWidget *ctrlNetworkList = new QTableWidget(this);
            ctrlNetworkList->setRowCount(listProgramName->count());
            ctrlNetworkList->setColumnCount(1);
            ctrlNetworkList->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
            ctrlNetworkList->verticalHeader()->hide();

            QStringList starr;
            starr.append(tr("Network name"));
  //          starr.append(tr("hardware"));
            ctrlNetworkList->setHorizontalHeaderLabels(starr);
            //根据节目主窗口选中的节目check选型，初始化Tree控件
            for (int i = 0; i < listProgramName->count(); i++)
            {
                QTableWidgetItem *topLevelItem = new QTableWidgetItem();     //创建一个 TreeItem 容器用于后来装载控件
                topLevelItem->setData(0,listProgramName->at(i));
                //topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsEditable);
                topLevelItem->setFlags(topLevelItem->flags() &  ~Qt::ItemIsEditable);

                //topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);
                /*上面用到的两个枚举中：~Qt::ItemIsEnabled可以保证单击该Item时不会被选中，但是在启用Ctrl + A时，全选操作会导致Item被选中。
                  * ~Qt::ItemIsSelectable的使用可以保证全选状态下也不会被选中，但是在单独使用时出现了虚线框，没有真正实现“不存在”的效果。所以必须两个同用。*/
                ctrlNetworkList->setItem(i,0,topLevelItem);

            }
            //把垂直布局的内容填充到内容区
            pVLayout->addWidget(ctrlNetworkList,0);
            ctrlNetworkList->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
            ui->horizontalLayout_content->addLayout(pVLayout);
            ui->label_2->setWordWrap(true);
            ui->label_2->setAlignment(Qt::AlignTop);
            if(iTipType==0)
                ui->label_2->setText(tr("This operation will only set cable network to static IP,are you sure?"));
            else if(iTipType==1)
                ui->label_2->setText(tr("Do you want set IP of cable network to DHCP")+"?");
            ui->label_2->setText(tr("This operation will only set cable network to static IP,are you sure?"));
            connect(ctrlNetworkList,SIGNAL(itemSelectionChanged()),this,SLOT(OnNetworkListSelectChanged()));
            connect( ui->bnOK,SIGNAL(clicked()),this,SLOT(accept()));
            connect( ui->bnCancel,SIGNAL(clicked()),this,SLOT(reject()));
        }
        break;
        default:
        break;

    }


}
TipDialog::~TipDialog()
{
    if(ctrlProgramList!=nullptr)
        delete ctrlProgramList;
    delete ui;
}
void TipDialog::onAccepted()
{
    switch(m_iTipDlgType)
    {
        case ENUM_IMPORT_DLG://Import对话框
        {
            if(iImportAtLeastOneSuccessFlag)
            {
                emit sigAcceptData(pTextPath->text(),"");

            }
            else {
                emit sigAcceptData("","");

            }
        }
        break;
        case ENUM_EXPORT_DLG:
        {
         emit sigAcceptData(pTextPath->text(),"");
        }
        break;
        case ENUM_DELETE_DLG:
        {
          emit sigAcceptData("","");
        }
        break;
        case ENUM_SAVEAS_DLG:
        {
            m_strLineEditText=pTextPath->text();
            emit sigAcceptData(m_strLineEditText,"");
        }
        break;
        case ENUM_SELECT_NETWORK:
        {
            if(m_strLineEditText.isEmpty())
            {

               X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("Please select the network to connect to the Led controller"),this,0);
               dlg->exec();
            }
            else {
                emit sigAcceptData(m_strLineEditText,"");
            }
        }
        break;
        default:
        break;
    }
}

void TipDialog::OnSelectDir()
{

    QString strDir = QFileDialog::getExistingDirectory(this, tr("Choose Directory"),
                                                    "/home",
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);

    pTextPath->setText(strDir);
    if(!strDir.isEmpty())
    {
        if(m_iTipDlgType==ENUM_IMPORT_DLG)
        {
                QDir root_dir(strDir);
                QStringList pro_list = root_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
                QStringList listProgramName;
                foreach(QString pro_name, pro_list) {
                    QDir pro_dir(strDir + MACRO_FENGEFU + pro_name);
                    if(pro_dir.exists("pro.json")) {
                        QFile fPro(pro_dir.path() + MACRO_FENGEFU+"pro.json");
                        fPro.open(QIODevice::ReadOnly);
                        QJsonDocument pro = QJsonDocument::fromJson(fPro.readAll());
                        fPro.close();
                        QString strProgramName=pro["name"].toString();
                        listProgramName.append(strProgramName);
                    }
                }
                ctrlProgramList->setRowCount(listProgramName.count());
                for(int i=0;i<listProgramName.count();i++)
                {
                    wExportProgramItem *topLevelItem = new wExportProgramItem(ctrlProgramList,listProgramName.at(i),i);
                    ctrlProgramList->setItem(i,0,topLevelItem);

                }

        }

        ui->bnOK->setEnabled(true);

        ui->bnOK->setStyleSheet("background-color:rgba(28,154,210);");

    }
    else {
        ui->bnOK->setEnabled(false);
        ui->bnOK->setStyleSheet("background-color:#8d8d8d;color:#fdfdfd;");

    }

}
void TipDialog::OnExportButton()
{
    QString strDestPath=pTextPath->text();
    if(!strDestPath.isEmpty())
    {
        QDir qDirDest(pTextPath->text());
        if(qDirDest.exists())
        {
            LoAppConfig *cfg = LoAppConfig::getInstance();
            QString doc_path = cfg->DocumentsLocation();
            if(!doc_path.isEmpty()) {
                QString app_path  = doc_path + MACRO_FENGEFU + cfg->ApplicationName();
                QString strSourceDir = app_path + MACRO_FENGEFU+"NPrograms";
                for(int i=0;i<ctrlProgramList->rowCount();i++)
                {
                    wExportProgramItem *pItem= static_cast<wExportProgramItem*>(ctrlProgramList->item(i,0));
                    pItem->ExportPro(strDestPath,strSourceDir);
                    qDebug()<<strDestPath+","+strSourceDir;
                }
            }
        }
    }
    else {
        X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("Please select the network to connect to the Led controller"),this,0);
        dlg->exec();

    }

}
void TipDialog::OnImportPro()
{
    QString strSourcePath=pTextPath->text();
    if(!strSourcePath.isEmpty())
    {
        //查找当前目录下发现的导出节目项,加入到列表，
        LoAppConfig *cfg = LoAppConfig::getInstance();
        QString doc_path = cfg->DocumentsLocation();
        QString app_path  = doc_path + MACRO_FENGEFU + cfg->ApplicationName();
        QString strDestPath = app_path + MACRO_FENGEFU+"NPrograms";
        strSourcePath.replace(MACRO_DANYINFANXIEGAN, MACRO_DANYINXIEGAN);
        strDestPath.replace(MACRO_DANYINFANXIEGAN, MACRO_DANYINXIEGAN);
        if(strSourcePath.contains(strDestPath,Qt::CaseInsensitive))
        {
            X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("The imported directory is already in the working directory, so there is no need to import it again!"),this,0);
            dlg->exec();

            return;
        }


        if(ctrlProgramList->rowCount()>0)//如果列表大于0，说明有符合的项目
        {
            if(!doc_path.isEmpty()) {
                QDir qDirDest(strDestPath);

                if(qDirDest.exists())
                {

                    for(int i=0;i<ctrlProgramList->rowCount();i++)
                    {
                        wExportProgramItem *pItem= static_cast<wExportProgramItem*>(ctrlProgramList->item(i,0));
                        if(pItem->ExportPro(strDestPath,strSourcePath))
                        {
                            iImportAtLeastOneSuccessFlag=true;
                            ui->bnClose->setVisible(false);
                        }
                        //qDebug()<<strDestPath+","+strSourcePath;
                    }
                }

            }
        }
        else {
            X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("no find program can be imported"),this,0);
            dlg->exec();

        }

    }
    else
    {
        X_UIMsgBoxOk *dlg=new X_UIMsgBoxOk(tr("Tip"),tr("Please select the network to connect to the Led controller"),this,0);
        dlg->exec();

    }
}

void TipDialog::OnNetworkListSelectChanged()
{
    QTableWidget *pl = findChild<QTableWidget*>();
    m_strLineEditText=pl->selectedItems()[0]->text();
}
