#include "mprogrammanager.h"
#include "ui_mprogrammanager.h"

#include "tipdialog.h"
#include "globaldefine.h"
#include <QMessageBox>
#include <LoUIClass/x_uimsgboxok.h>
#include <LoUIClass/x_uimsgboxokcancel.h>
#include <QSettings>
mProgramManager::mProgramManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mProgramManager),
    m_strProgramItemPath("")
{
    setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);

    LoAppConfig *cfg = LoAppConfig::getInstance();
    QString doc_path = cfg->DocumentsLocation();;
    if(!doc_path.isEmpty()) {
        QString app_path  = doc_path + MACRO_FENGEFU + cfg->ApplicationName();
        QString pRoot = app_path + MACRO_FENGEFU+"NPrograms";
        QDir root_dir = QDir(pRoot);
        if(!root_dir.exists()) {
            QDir app_dir(app_path);
            app_dir.mkdir("NPrograms");
            app_dir.mkdir("ApkStore");
        }
        m_strProgramItemPath = pRoot;
    }

    m_headerItem = new QTreeWidgetItem();
    QAction *search = new QAction(ui->txtSearch);
    search->setIcon(QIcon(":/res/ProgramManager/bnSearch.png"));
    ui->txtSearch->addAction(search, QLineEdit::LeadingPosition);
    ui->txtSearch->setClearButtonEnabled(true);
    ui->txtSearch->setProperty("ssType", "progManageTool");
    ui->txtSearch->setProperty("ssName", "searchProg");
    ui->bnEdit  ->setProperty("ssType", "progManageTool");
    ui->bnDelete->setProperty("ssType", "progManageTool");
    ui->bnImport->setProperty("ssType", "progManageTool");
    ui->bnExport->setProperty("ssType", "progManageTool");
    ui->bnSend  ->setProperty("ssType", "progManageTool");
    ui->bnNew   ->setProperty("ssName", "newProg");
    ui->bnNew   ->setProperty("ssType", "progManageTool");
    ui->bnEdit->setEnabled(false);
    ui->bnDelete->setEnabled(false);
    ui->bnExport->setEnabled(false);
    ui->bnSend->setEnabled(false);
    ui->bnSend->hide();
    //refreshLable();

     for(int i=1; i<ENUM_PROGRAMLISTHEADERITEM_END; i++) {
        m_headerItem->setTextAlignment(i, Qt::AlignCenter);
    }

    ui->wProgramList->setHeaderItem(m_headerItem);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_CHECK, QHeaderView::Fixed);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_NAME, QHeaderView::Stretch);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_RESOLUTION, QHeaderView::Stretch);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_SIZE, QHeaderView::Stretch);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_LASTTIME, QHeaderView::Stretch);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_USB_EXPORT, QHeaderView::Fixed);
    ui->wProgramList->header()->setSectionResizeMode(ENUM_PROGRAMLISTHEADERITEM_SEND, QHeaderView::Fixed);
    ui->wProgramList->header()->setStretchLastSection(false);
    ui->wProgramList->setColumnWidth(ENUM_PROGRAMLISTHEADERITEM_CHECK, 66);
    ui->wProgramList->setColumnWidth(ENUM_PROGRAMLISTHEADERITEM_USB_EXPORT, 100);
    ui->wProgramList->setColumnWidth(ENUM_PROGRAMLISTHEADERITEM_SEND, 72);

    connect(ui->bnNew,    SIGNAL(clicked(bool)), this, SLOT(onNewClicked(bool)));
    connect(ui->bnEdit,   SIGNAL(clicked(bool)), this, SLOT(onEditClicked(bool)));
    connect(ui->bnDelete, SIGNAL(clicked(bool)), this, SLOT(onDeleteClicked(bool)));
    connect(ui->bnImport, SIGNAL(clicked(bool)), this, SLOT(onImportClicked(bool)));
    connect(ui->bnExport, SIGNAL(clicked(bool)), this, SLOT(onExportClicked(bool)));

    connect(ui->wProgramList, SIGNAL(sigCheckStateChanged(int)), this, SLOT(onCheckStateChanged(int)));

    connect(ui->txtSearch,SIGNAL(textChanged(const QString &)),this,SLOT(FilterProgram(const QString &)));

    //connect(search, SIGNAL(triggered(bool)), this, SLOT(FilterProgram()));
    //查找根路径下的项目文件夹，查找文件夹下的节目pro.json信息，包括节目名称，大小，像素，备注等信息
    if(!m_strProgramItemPath.isEmpty()) {
        QDir root_dir(m_strProgramItemPath);
        QStringList pro_list = root_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
        foreach(QString pro_name, pro_list) {
            QDir pro_dir(m_strProgramItemPath + 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();
                onRestoreProgram(pro);
            }
        }
    }
    readSettings();

//    ui->wProgramList->setSortingEnabled( false ); //不使能QT的自动排序
//    ui->wProgramList->header()->setSortIndicatorShown( true ); // 设置三角标识符可见
//    ui->wProgramList->header()->setSectionsClickable( true ); // 设置标题栏单击响应使能
//    connect( ui->wProgramList->header(), SIGNAL( sectionClicked(int) ), this, SLOT( OnClickColumn(int) ) );
}
void mProgramManager::OnClickColumn(int iColumn)
{
    if(iColumn!=ENUM_PROGRAMLISTHEADERITEM_CHECK||iColumn!=ENUM_PROGRAMLISTHEADERITEM_SEND)
        ui->wProgramList->sortByColumn(iColumn,ui->wProgramList->header()->sortIndicatorOrder());

}
mProgramManager::~mProgramManager()
{
    writeSettings();
    delete ui;
}
void mProgramManager::writeSettings()
{
    LoAppConfig *cfg = LoAppConfig::getInstance();
    QSettings *settings = new QSettings(cfg->OrganizationName(), cfg->ApplicationName());
    settings->setValue("ProgramListSortColumn", ui->wProgramList->sortColumn());

    settings->setValue("ProgramListSortOrder", ui->wProgramList->header()->sortIndicatorOrder());
}
void mProgramManager::readSettings()
{
    LoAppConfig *cfg = LoAppConfig::getInstance();
    QSettings *settings = new QSettings(cfg->OrganizationName(), cfg->ApplicationName());
    if(settings->value("ProgramListSortOrder").toInt()==0)
    {
        ui->wProgramList->sortByColumn(settings->value("ProgramListSortColumn").toInt(),Qt::SortOrder::AscendingOrder);
    }
    else {
        ui->wProgramList->sortByColumn(settings->value("ProgramListSortColumn").toInt(),Qt::SortOrder::DescendingOrder);

    }

}

void mProgramManager::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
//切换语言，实时刷新翻译标签
void mProgramManager::refreshLable()
{
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_CHECK, 0, "");
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_NAME, 0, tr("Name"));
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_RESOLUTION, 0, tr("Resolution"));
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_SIZE, 0, tr("File Size"));
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_LASTTIME, 0, tr("Last Modify"));
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_USB_EXPORT, 0, tr("Usb playback"));
    m_headerItem->setData(ENUM_PROGRAMLISTHEADERITEM_SEND, 0, tr("Publish"));
    ui->bnNew->setText(tr("New"));
    ui->bnEdit->setText(tr("Edit"));
    ui->bnDelete->setText(tr("Delete"));
    ui->bnImport->setText(tr("Import"));
    ui->bnExport->setText(tr("Export"));
    ui->bnSend->setText(tr("Send"));
    for(int i=0;i<m_pwPorgramItemList.count();i++)
        m_pwPorgramItemList.at(i)->refreshLable();
}


void mProgramManager::onCheckStateChanged(int f)
{
    switch (f) {
    case LoQTreeWidget::CheckNone:
        ui->bnEdit  ->setEnabled(false);
        ui->bnDelete->setEnabled(false);
        ui->bnExport->setEnabled(false);
        ui->bnSend  ->setEnabled(false);
        break;

    case LoQTreeWidget::CheckOne:
        ui->bnEdit  ->setEnabled(true);
        ui->bnDelete->setEnabled(true);
        ui->bnExport->setEnabled(true);
        ui->bnSend  ->setEnabled(true);
        break;

    case LoQTreeWidget::CheckMulti:
        ui->bnEdit  ->setEnabled(false);
        ui->bnDelete->setEnabled(true);
        ui->bnExport->setEnabled(true);
        ui->bnSend  ->setEnabled(true);
        break;

    default:
        break;
    }
}

void mProgramManager::onNewClicked(bool f)
{
    Q_UNUSED(f);
    wNewProgram *dlg = new wNewProgram(this);
    connect(dlg, SIGNAL(sigAcceptData(QString,QSize,QString)), this, SLOT(onCreateNewProgram(QString,QSize,QString)));
    dlg->exec();
}

void mProgramManager::onEditClicked(bool f)
{
    Q_UNUSED(f);
//    wProgramItem *item = static_cast<wProgramItem*>(ui->wProgramList->itemChecked());
//    if(nullptr == item) return;
//    QString name    = item->name();
//    QSize   res     = QSize(item->width(), item->height());
//    QString remarks = item->remarks();
//    wNewProgram *dlg = new wNewProgram(name, res, remarks, this);
//    connect(dlg, SIGNAL(sigAcceptData(QString,QSize,QString)), this, SLOT(onEditHead(QString,QSize,QString)));
//    dlg->exec();


    int cnt = ui->wProgramList->topLevelItemCount();
    QList<wProgramItem*> list;
    for(int i=0; i<cnt; i++) {
        if(ui->wProgramList->topLevelItem(i)->checkState(0) == Qt::Checked) {
            wProgramItem *item = static_cast<wProgramItem*>(ui->wProgramList->topLevelItem(i));
            emit item->sigEditProgram();

            break;
        }
    }
}

bool mProgramManager::checkIfNameRepeated(const QString &name, QTreeWidgetItem *skip)
{
    int cnt = ui->wProgramList->topLevelItemCount();
    for(int i=0; i<cnt; i++) {
        wProgramItem *item = static_cast<wProgramItem*>(ui->wProgramList->topLevelItem(i));
        if(item == skip) {
            continue;
        }
        if(name == item->name()) {
            auto *mb = new X_UIMsgBoxOk(tr("Program name conflicted"),"", this,0);
            mb->exec();
            return true;
        }
    }
    return false;
}

void mProgramManager::onEditHead(const QString &name, QSize res, const QString &remarks)
{
    wProgramItem *item = static_cast<wProgramItem*>(ui->wProgramList->itemChecked());
    if(checkIfNameRepeated(name, item)) {
        return;
    }
    item->onAttrChanged(name, res.width(), res.height(), remarks);
}

void mProgramManager::onRestoreProgram(const QJsonDocument &pro)
{
    m_pwPorgramItemList.append(new wProgramItem(m_strProgramItemPath, pro.object(), ui->wProgramList,this));
}

void mProgramManager::onCreateNewProgram(QString name, QSize res, QString remarks)
{
    if(checkIfNameRepeated(name)) {
        return;
    }
    auto item = new wProgramItem(m_strProgramItemPath, name, res.width(), res.height(), remarks, ui->wProgramList,this);
 //   emit item->sigEditProgram();
    item->save();//保存pro.json
    ui->wProgramList->adjustCheckState();
}
void mProgramManager::onCreateNewProgramOnOpenEditProgramWidget(QString name, QSize res, QString remarks)
{
    if(checkIfNameRepeated(name)) {
        return;
    }
    auto item = new wProgramItem(m_strProgramItemPath, name, res.width(), res.height(), remarks, ui->wProgramList,this);
    item->save();//保存pro.json

    ui->wProgramList->adjustCheckState();
}
void mProgramManager::onDeleteClicked(bool f)
{
    Q_UNUSED(f);
    X_UIMsgBoxOkCancel *dlg = new X_UIMsgBoxOkCancel(tr("Tip Info"),tr("You will delete the selected solution(s),are you sure?"), this);

    if(dlg->exec() == QDialog::Accepted)
    {
        int cnt = ui->wProgramList->topLevelItemCount();
        QList<wProgramItem*> list;
        for(int i=0; i<cnt; i++) {
            if(ui->wProgramList->topLevelItem(i)->checkState(0) == Qt::Checked) {
                wProgramItem *item = static_cast<wProgramItem*>(ui->wProgramList->topLevelItem(i));
                list.push_back(item);
            }
        }
        while(!list.isEmpty()) {
            wProgramItem *item = list.takeFirst();
            item->del();
            delete item;
        }
        ui->wProgramList->adjustCheckState();
    }
    else
    {
       // QMessageBox::warning(this, "Title", "Cancel");
    }
}
//void mProgramManager::onDeleteProgram(QString strImportDir,QString strTip1)
//{
//    QMessageBox::warning(this, "Delete", strImportDir + strTip1);

//}
void mProgramManager::onImportClicked(bool f)
{
    Q_UNUSED(f);

    TipDialog *dlg = new TipDialog(this,ENUM_IMPORT_DLG);
    connect(dlg, SIGNAL(sigAcceptData(QString,QString)), this, SLOT(onImportProgram(QString,QString)));
    if(dlg->exec() == QDialog::Accepted)
    {
//        QMessageBox::warning(this, "Title", "Text");
    }
}


void mProgramManager::onImportProgram(QString strImportDir,QString strTip1)
{
    //QMessageBox::warning(this, "Import", strImportDir + strTip1);
//    X_UIMsgBoxOk *mb = new X_UIMsgBoxOk(tr("Tip Info"),tr("Import program successed"), this,0);
//    mb->exec();
    Q_UNUSED(strTip1);
    if(!strImportDir.isEmpty())
    {
        ui->wProgramList->clear();
        //查找根路径下的项目文件夹，查找文件夹下的节目pro.json信息，包括节目名称，大小，像素，备注等信息
        if(!m_strProgramItemPath.isEmpty()) {
            QDir root_dir(m_strProgramItemPath);
            QStringList pro_list = root_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
            foreach(QString pro_name, pro_list) {
                QDir pro_dir(m_strProgramItemPath + 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();
                    onRestoreProgram(pro);
                }
            }
        }
    }



}

void mProgramManager::onExportClicked(bool f)
{
    Q_UNUSED(f);
    int cnt = ui->wProgramList->topLevelItemCount();
    QStringList selectProgramlist;
    for(int i=0; i<cnt; i++) {
        if(ui->wProgramList->topLevelItem(i)->checkState(0) == Qt::Checked) {
            QString string =static_cast<wProgramItem*>(ui->wProgramList->topLevelItem(i))->GetBnName();
            // list.push_back(string);
            selectProgramlist.append(string);
            //selectProgramlist<<string;
        }
    }

    TipDialog *dlg = new TipDialog(this,ENUM_EXPORT_DLG,&selectProgramlist,0);
    //dlg->resize(800,600);//改变窗口大小
    connect(dlg, SIGNAL(sigAcceptData(QString,QString)), this, SLOT(onExportProgram(QString,QString)));
    if(dlg->exec() == QDialog::Accepted)
    {
//        QMessageBox::warning(this, "Title", "Text");
    }
}


void mProgramManager::onExportProgram(QString strImportDir,QString strTip1)
{
   // QMessageBox::warning(this, "Export", strImportDir + strTip1);
    Q_UNUSED(strImportDir);
    Q_UNUSED(strTip1);
}
void mProgramManager::FilterProgram(const QString &strtemp)
{
    if (strtemp.isEmpty())	//显示全部
    {
        for (int i = 0; i< ui->wProgramList->topLevelItemCount(); ++i)
        {
            QTreeWidgetItem* topItem = ui->wProgramList->topLevelItem(i);
            ui->wProgramList->setRowHidden(i,ui->wProgramList->indexFromItem(topItem->parent()),false);
        }
    }
    else
    {
        QList<QTreeWidgetItem*> resultList = ui->wProgramList->findItems(strtemp, Qt::MatchContains,ENUM_PROGRAMLISTHEADERITEM_NAME);	//搜索结果
        if (resultList.size() > 0)
        {
            //QMessageBox::warning(this, "Export", QString(resultList.size()));
            for (int i = 0; i< ui->wProgramList->topLevelItemCount(); ++i)
            {
                QTreeWidgetItem* topItem = ui->wProgramList->topLevelItem(i);
                if (resultList.contains(topItem))
                    ui->wProgramList->setRowHidden(i,ui->wProgramList->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                else
                    ui->wProgramList->setRowHidden(i,ui->wProgramList->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
            }
        }
        else {
            QList<QTreeWidgetItem*> resultList1 = ui->wProgramList->findItems(strtemp, Qt::MatchContains,ENUM_PROGRAMLISTHEADERITEM_RESOLUTION);	//搜索结果
            if (resultList1.size() > 0)
            {
                //QMessageBox::warning(this, "Export", QString(resultList.size()));
                for (int i = 0; i< ui->wProgramList->topLevelItemCount(); ++i)
                {
                    QTreeWidgetItem* topItem = ui->wProgramList->topLevelItem(i);
                    if (resultList1.contains(topItem))
                        ui->wProgramList->setRowHidden(i,ui->wProgramList->indexFromItem(topItem->parent()),false);	//显示匹配的结果
                    else
                        ui->wProgramList->setRowHidden(i,ui->wProgramList->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                }
            }
            else {
                for (int i = 0; i< ui->wProgramList->topLevelItemCount(); ++i)
                {
                    QTreeWidgetItem* topItem = ui->wProgramList->topLevelItem(i);
                    ui->wProgramList->setRowHidden(i,ui->wProgramList->indexFromItem(topItem->parent()),true);	//隐藏不匹配的结果
                }
            }
        }
    }

}

