#include "widget.h"
#include <QGroupBox>
#include <QButtonGroup>
#include <QLabel>
#include <QSqlQuery>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QTextCodec>
#include <QMessageBox>
#include <QSqlError>
#include <QMenuBar>
#include <QInputDialog>
#include "../Json/sjson.h"
#include "../common.h"

/*
QSqlDatabase dbWeb = QSqlDatabase::addDatabase("QMYSQL");
dbWeb.setHostName("db.big-bird.co.kr");
dbWeb.setUserName("concepters");
dbWeb.setPassword("con97996655");
dbWeb.setDatabaseName("dbconcepters");
*/

#define D_NOT_SELECT -1

#define SAFE_DELETE(x)       if(x != NULL) { delete x; x = NULL; }
#define SAFE_DELETEARRAY(x)  if(x != NULL) { delete [] x; x = NULL; }
#define SAFE_RELEASE(x)      if(x != NULL) { x->Release(); x = NULL; }

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    if (ReloadColumn() == false)
        return;

    QVBoxLayout *vMainLayout = new QVBoxLayout;
    vMainLayout->setAlignment(Qt::AlignVCenter);
    setMenuWidget();
    //vMainLayout->addWidget(setMenuWidget());
    {
        QVBoxLayout *vlayout = new QVBoxLayout;

        {
            QHBoxLayout *hlayout = new QHBoxLayout;
            if (m_nColumn != -1)
                hlayout->addWidget(setDateWidgets());
            hlayout->addWidget(setCountWidgets());
            //vlayout->addLayout(hlayout);
        }

        vlayout->addWidget(setSearchWidgets());
        vlayout->addWidget(setLengthWidgets());
        vlayout->addWidget(setCounterWidgets());
        vlayout->addWidget(setReplaceWidgets());
        vlayout->setAlignment(Qt::AlignTop);

        {
            QHBoxLayout *hlayout = new QHBoxLayout;
            hlayout->addWidget(setDataWidgets());
            hlayout->addLayout(vlayout);
            //hlayout->addWidget(setFilterWidgets());
            setFilterWidgets();
            vMainLayout->addLayout(hlayout,2);
        }

        m_ptwData = new QTabWidget;
        vMainLayout->addWidget(m_ptwData,7);
        m_ptwData->setTabsClosable(true);
        connect(m_ptwData,SIGNAL(tabCloseRequested(int)),this,SLOT(CloseTab(int)));
        connect(m_ptwData,SIGNAL(tabBarDoubleClicked(int)),this,SLOT(DoubleClickTab(int)));
        m_pProgress = new QProgressBar;
        vMainLayout->addWidget(m_pProgress,1);
    }
    setLayout(vMainLayout);
    DataGroupRefresh();
    FilterGroupRefresh();
    AddTable("Start");
}

Widget::~Widget()
{
}

QTableWidget *Widget::AddTable(QString _str)
{
    STable *pTable = new STable;
    m_ptwData->addTab(pTable,_str);
    return (QTableWidget *)pTable;
}

void Widget::CloseTab(int index)
{
    ((STable*)(m_ptwData->widget(index)))->clear();
    m_ptwData->removeTab(index);
}

void Widget::DoubleClickTab(int index)
{
    bool ok;
    if (index < 0) return;
    QString text = QInputDialog::getText(this,"Tab name change","Name : ", QLineEdit::Normal,m_ptwData->tabText(index), &ok);
    if (ok)
    {
        m_ptwData->setTabText(index,text);
    }
}

QMenuBar *Widget::setMenuWidget()
{
    QMenuBar *pMenuBar = new QMenuBar();
    {
         QMenu *pFile = pMenuBar->addMenu("File");
         connect(pFile->addAction("New"), SIGNAL(triggered()), this, SLOT(FileNew()));
         connect(pFile->addAction("CSV Import"), SIGNAL(triggered()), this, SLOT(FileImport()));
         connect(pFile->addAction("CSV Export"), SIGNAL(triggered()), this, SLOT(FileExport()));
         pFile->addSeparator();
         connect(pFile->addAction("Exit"), SIGNAL(triggered()), this, SLOT(FileExit()));
    }
    return pMenuBar;
}

void Widget::FileNew()
{
    bool ok;
    QString text = QInputDialog::getText(this,"New Row Count","Count :", QLineEdit::Normal,"0", &ok);

    if (ok)
    {
        STable *pTable = (STable*)AddTable("new");
        pTable->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);
        m_ptwData->setCurrentIndex(m_ptwData->count()-1);
        pTable->setRowCount(text.toInt());
    }
}

QGroupBox *Widget::setDataWidgets()
{
    QVBoxLayout *vlayout = new QVBoxLayout;

    QGroupBox *groupBox = new QGroupBox(tr("Data Group"));
    m_plwData = new QListWidget;
    vlayout->addWidget(m_plwData);
    m_plwData->setSelectionMode(QAbstractItemView::SingleSelection);
    QPushButton *ppbRefresh = new QPushButton("Refresh");
    vlayout->addWidget(ppbRefresh);
    connect(ppbRefresh, SIGNAL(released()),this, SLOT(DataGroupRefresh()));
    groupBox->setLayout(vlayout);
    connect(m_plwData,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(DataGroupItemChanged(QListWidgetItem*)));
    return groupBox;
}

QGroupBox *Widget::setDateWidgets()
{
    //m_pcbDateCatalog = new QComboBox;
    m_pdeStart = new QDateEdit(QDate::currentDate());
    m_pdeEnd = new QDateEdit(QDate::currentDate());

    m_pdeStart->setDateRange(QDate(2003, 5, 20),QDate::currentDate());
    m_pdeEnd->setDateRange(QDate(2003, 5, 20),QDate::currentDate());

    m_pcw = new QCalendarWidget();
    m_pdeStart->setCalendarWidget(m_pcw);
    m_pdeStart->setCalendarPopup(true);

    m_pdeEnd->setCalendarWidget(m_pcw);
    m_pdeEnd->setCalendarPopup(true);

    QHBoxLayout *hlayout = new QHBoxLayout();
    //hlayout->addWidget(new QLabel("Catalog:"));
    //hlayout->addWidget(m_pcbDateCatalog);
    hlayout->addWidget(new QLabel("Start:"));
    hlayout->addWidget(m_pdeStart);
    hlayout->addWidget(new QLabel("End:"));
    hlayout->addWidget(m_pdeEnd);

    {
        QPushButton *pbInsert = new QPushButton("Insert");
        connect(pbInsert , SIGNAL(released()),this, SLOT(SearchDate()));
        QPushButton *pbModify = new QPushButton("Modify");
        connect(pbModify , SIGNAL(released()),this, SLOT(SearchDateUpdate()));

        hlayout->addWidget(pbInsert);
        hlayout->addWidget(pbModify);
    }

    hlayout->setAlignment(Qt::AlignLeft|Qt::AlignTop);
    QGroupBox *groupBox = new QGroupBox(tr("Term"));
    groupBox->setAlignment(Qt::AlignLeft|Qt::AlignTop);
    groupBox->setLayout(hlayout);
    //m_pcbDateCatalog->addItems(QStringList() << "body + reply"  << "body" << "reply");

    return groupBox;
}

QGroupBox *Widget::setCountWidgets()
{
    QHBoxLayout *hlayout = new QHBoxLayout();
    m_pcbCountCatalog = new QComboBox;

    hlayout->addWidget(m_pcbCountCatalog);

    foreach(QStringList strList,m_vecColumn)
        m_pcbCountCatalog->addItem(strList.at(E_COLUMN_NAME));

    {
        QPushButton *pbInsert = new QPushButton("Save");
        connect(pbInsert , SIGNAL(released()),this, SLOT(CountSave()));
        hlayout->addWidget(pbInsert);
    }
    QGroupBox *groupBox = new QGroupBox(tr("Count"));
    groupBox->setLayout(hlayout);
    return groupBox;
}

QGroupBox *Widget::setSearchWidgets()
{
    m_pcbCatalog = new QComboBox;
    m_pcbKeyword = new QComboBox;
    m_pcbMethod = new QComboBox;
    m_pleString = new QLineEdit;

    m_pcbKeyword->addItem(QString("Or"));// or
    m_pcbKeyword->addItem(QString("And"));// and
    m_pcbKeyword->addItem(QString("Cell Delete"));
    m_pcbKeyword->addItem(QString("Word Delete"));

    m_pcbMethod->addItem(QString("Sentence"));
    m_pcbMethod->addItem(QString("Space"));

    foreach(QStringList strList,m_vecColumn)
        m_pcbCatalog->addItem(strList.at(E_COLUMN_NAME));

    QVBoxLayout *vlayout = new QVBoxLayout();
    {
        QHBoxLayout *hlayout = new QHBoxLayout();
        hlayout->addWidget(new QLabel("Item:"));
        hlayout->addWidget(m_pcbCatalog);
        hlayout->addWidget(new QLabel("Method:"));
        hlayout->addWidget(m_pcbMethod);
        hlayout->addWidget(new QLabel("keyword:"));
        hlayout->addWidget(m_pcbKeyword);
        vlayout->addLayout(hlayout);
    }

    {
        QHBoxLayout *hlayout = new QHBoxLayout();
        hlayout->addWidget(new QLabel("Search:"));
        hlayout->addWidget(m_pleString);
        vlayout->addLayout(hlayout);
    }

    QHBoxLayout *hlayout = new QHBoxLayout();
    hlayout->addLayout(vlayout);

    {
        QVBoxLayout *vsublayout = new QVBoxLayout();
        QPushButton *pbInsert = new QPushButton("Insert");
        vsublayout->addWidget(pbInsert);
        connect(pbInsert, SIGNAL(released()),this, SLOT(SearchKeyword()));

        QPushButton *pbModify = new QPushButton("Modify");
        connect(pbModify , SIGNAL(released()),this, SLOT(SearchKeywordUpdate()));
        vsublayout->addWidget(pbModify);
        hlayout->addLayout(vsublayout);
    }

    QGroupBox *groupBox = new QGroupBox(tr("Search"));
    groupBox->setLayout(hlayout);    
    return groupBox;
}

QGroupBox *Widget::setLengthWidgets()
{
    QHBoxLayout *hlayout = new QHBoxLayout();
    m_pcbLengthCatalog = new QComboBox;
    m_pcbLengthComp = new QComboBox;
    m_pcbLengthInsDel = new QComboBox;
    m_pleLength = new QLineEdit;

    foreach(QStringList strList,m_vecColumn)
        m_pcbLengthCatalog->addItem(strList.at(E_COLUMN_NAME));

    m_pcbLengthComp->addItem(">",QVariant(E_LENGTH_COMP_GREATER));
    m_pcbLengthComp->addItem("<",QVariant(E_LENGTH_COMP_LESS));
    m_pcbLengthComp->addItem("=",QVariant(E_LENGTH_COMP_EQUAL));

    m_pcbLengthInsDel->addItem("Add",QVariant(0));
    m_pcbLengthInsDel->addItem("Del",QVariant(1));

    hlayout->addWidget(new QLabel("Item:"));
    hlayout->addWidget(m_pcbLengthCatalog);
    hlayout->addWidget(m_pcbLengthComp);
    hlayout->addWidget(new QLabel("Length:"));
    hlayout->addWidget(m_pleLength);
    hlayout->addWidget(m_pcbLengthInsDel);
    {
        QPushButton *pbInsert = new QPushButton("Insert");
        connect(pbInsert , SIGNAL(released()),this, SLOT(SearchLengthInsert()));
        QPushButton *pbModify = new QPushButton("Modify");
        connect(pbModify , SIGNAL(released()),this, SLOT(SearchLengthUpdate()));
        hlayout->addWidget(pbInsert);
        hlayout->addWidget(pbModify);
    }
    QGroupBox *groupBox = new QGroupBox(tr("Length"));
    groupBox->setLayout(hlayout);
    return groupBox;
}


QGroupBox *Widget::setCounterWidgets()
{
    QHBoxLayout *hlayout = new QHBoxLayout();
    m_pcbCounterCatalog = new QComboBox;
    m_pcbCounterComp = new QComboBox;
    m_pcbCounterInsDel = new QComboBox;
    m_pcbCounterCntApl = new QComboBox;
    m_pleCounter = new QLineEdit;

    foreach(QStringList strList,m_vecColumn)
        m_pcbCounterCatalog->addItem(strList.at(E_COLUMN_NAME));

    m_pcbCounterComp->addItem(">",QVariant(E_LENGTH_COMP_GREATER));
    m_pcbCounterComp->addItem("<",QVariant(E_LENGTH_COMP_LESS));
    m_pcbCounterComp->addItem("=",QVariant(E_LENGTH_COMP_EQUAL));

    m_pcbCounterInsDel->addItem("Add",QVariant(0));
    m_pcbCounterInsDel->addItem("Del",QVariant(1));

    m_pcbCounterCntApl->addItem("Count",QVariant(0));
    m_pcbCounterCntApl->addItem("Apply",QVariant(1));

    hlayout->addWidget(new QLabel("Item:"));
    hlayout->addWidget(m_pcbCounterCatalog);
    hlayout->addWidget(m_pcbCounterComp);
    //hlayout->addWidget(m_pcbCounterCntApl);
    hlayout->addWidget(new QLabel("Count:"));
    hlayout->addWidget(m_pleCounter);
    hlayout->addWidget(m_pcbCounterInsDel);
    {
        QPushButton *pbInsert = new QPushButton("Insert");
        connect(pbInsert , SIGNAL(released()),this, SLOT(SearchCounterInsert()));
        QPushButton *pbModify = new QPushButton("Modify");
        connect(pbModify , SIGNAL(released()),this, SLOT(SearchCounterUpdate()));
        hlayout->addWidget(pbInsert);
        hlayout->addWidget(pbModify);
    }

    QGroupBox *groupBox = new QGroupBox(tr("Counter"));
    groupBox->setLayout(hlayout);
    return groupBox;
}



QGroupBox *Widget::setReplaceWidgets()
{
    QHBoxLayout *hlayout = new QHBoxLayout();
    m_pcbReplaceCatalog = new QComboBox;
    m_pcbReplaceFind = new QComboBox;
    m_pcbReplace = new QComboBox;
    m_pleReplaceFind = new QLineEdit;
    m_pleReplace = new QLineEdit;

    foreach(QStringList strList,m_vecColumn)
        m_pcbReplaceCatalog->addItem(strList.at(E_COLUMN_NAME));

    m_pcbReplaceFind->addItem("Sentence",QVariant(E_REPLACE_SENTENCE));
    m_pcbReplaceFind->addItem("Space",QVariant(E_REPLACE_SPACE));

    m_pcbReplace->addItem("0",QVariant(0));
    m_pcbReplace->addItem("1",QVariant(1));
    m_pcbReplace->addItem("2",QVariant(2));

    hlayout->addWidget(m_pcbReplaceCatalog);
    hlayout->addWidget(new QLabel("Find:"));
    hlayout->addWidget(m_pcbReplaceFind);
    hlayout->addWidget(m_pleReplaceFind);
    hlayout->addWidget(new QLabel("Replace:"));
    hlayout->addWidget(m_pcbReplace);
    hlayout->addWidget(m_pleReplace);
    {
        QVBoxLayout *vlayout = new QVBoxLayout();
        QPushButton *pbInsert = new QPushButton("Insert");
        connect(pbInsert , SIGNAL(released()),this, SLOT(SearchReplaceInsert()));
        vlayout->addWidget(pbInsert);
        QPushButton *pbModify = new QPushButton("Modify");
        connect(pbModify , SIGNAL(released()),this, SLOT(SearchReplaceUpdate()));
        vlayout->addWidget(pbModify);
        hlayout->addLayout(vlayout);
    }
    QGroupBox *groupBox = new QGroupBox(tr("Replace"));
    groupBox->setLayout(hlayout);
    return groupBox;
}

QGroupBox *Widget::setFilterWidgets()
{
    QHBoxLayout *hMainlayout = new QHBoxLayout();
    {
        QVBoxLayout *vlayout = new QVBoxLayout();
        m_plwFilterGroup = new QListWidget;
        m_pleFilterGroup = new QLineEdit;
        vlayout->addWidget(m_plwFilterGroup);
        vlayout->addWidget(m_pleFilterGroup);
        {
            QHBoxLayout *hlayout = new QHBoxLayout();
            QPushButton *pbInsert = new QPushButton("Insert");
            connect(pbInsert, SIGNAL(released()),this, SLOT(FilterGroupInsert()));
            QPushButton *pbDelete = new QPushButton("Delete");
            connect(pbDelete, SIGNAL(released()),this, SLOT(FilterGroupDelete()));
            QPushButton *pbModify = new QPushButton("Modfiy");
            connect(pbModify, SIGNAL(released()),this, SLOT(FilterGroupModify()));
            QPushButton *pbCopy_Paste = new QPushButton("Copy&Paste");
            connect(pbCopy_Paste, SIGNAL(released()),this, SLOT(FilterGroupCopyPaste()));
            QPushButton *pbRefresh = new QPushButton("Refresh");
            connect(pbRefresh, SIGNAL(released()),this, SLOT(FilterGroupRefresh()));

            hlayout->addWidget(pbInsert);
            hlayout->addWidget(pbDelete);
            hlayout->addWidget(pbModify);
            hlayout->addWidget(pbCopy_Paste);
            hlayout->addWidget(pbRefresh);
            vlayout->addLayout(hlayout);
        }
        hMainlayout->addLayout(vlayout);
    }
    {
        QVBoxLayout *vlayout = new QVBoxLayout();
        m_plwFilter = new QListWidget;
        vlayout->addWidget(m_plwFilter);
        connect(m_plwFilter,SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),this,SLOT(currentFilterItemChanged(QListWidgetItem*,QListWidgetItem*)));
        QPushButton *pbDelete = new QPushButton("Delete");
        vlayout->addWidget(pbDelete);
        connect(pbDelete, SIGNAL(released()),this, SLOT(FilterDelete()));
        hMainlayout->addLayout(vlayout);
    }
    m_pgbFilter = new QGroupBox(tr("Filter"));
    m_pgbFilter->setCheckable(true);
    m_pgbFilter->setChecked(false);
    m_pgbFilter->setLayout(hMainlayout);

    connect(m_plwFilterGroup,SIGNAL(currentItemChanged(QListWidgetItem *,QListWidgetItem *)),this,SLOT(currentGroupItemChanged(QListWidgetItem *, QListWidgetItem *)));
    return m_pgbFilter;
}


void Widget::DataGroupRefresh()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    m_plwData->clear();
    QSqlQuery query("select id,name,count from datagroup");
    while (query.next())
    {
        QString str = query.value(1).toString();
        str += " ( ";
        str += query.value(0).toString();
        str += " , ";
        str += query.value(2).toString();
        str += " )";
        QListWidgetItem *pItem = new QListWidgetItem(str,m_plwData);
        pItem->setData(Qt::UserRole, QVariant(query.value(0)));
    }
    db.close();
}

void Widget::InsertCopyRow(int _nRow,QTableWidget *_pCurrent,QTableWidget *_pNew)
{
    _pNew->setRowCount(_pNew->rowCount()+1);
    for (int nCount = 0;nCount < _pCurrent->columnCount() ;nCount++ )
    {
        _pNew->setItem(_pNew->rowCount()-1,nCount,new QTableWidgetItem(*_pCurrent->item(_nRow,nCount)));
    }
}

void Widget::SearchDate()
{
    STable *pNew = new STable;
    STable *pCurrent = (STable *)m_ptwData->currentWidget();
    pNew->setArticleSelect(pCurrent->getArticleSelect());
    pNew->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);
    m_pProgress->setRange(0,pCurrent->rowCount()-1);

    int nCurrentFilterGroupID = D_NOT_SELECT;

    if (m_pgbFilter->isChecked())
    {
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
        {
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
            DataBaseTimeFilter(pNew->getArticleSelect(),m_pdeStart->date(),m_pdeEnd->date(),nCurrentFilterGroupID,E_DATABASE_COMMAND_INSERT);
        }
    }

    for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
    {
        bool bFlag = false;
        QString strTime = pCurrent->item(nCount,m_nColumn)->text().trimmed();
        if (strTime.size() >= 10)
        {
            QChar ch = strTime.at(4);
            QString strFormat = QString("yyyy")+ch+QString("MM")+ch+QString("dd");
            QDate date = QDate::fromString(strTime.left(10),strFormat);
            if (m_pdeStart->date() <= date && m_pdeEnd->date() >= date)
                bFlag = true;
        }
        if (bFlag)
            InsertCopyRow(nCount,pCurrent,pNew);
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    //m_ptwData->addTab(pNew,m_ptwData->tabText(m_ptwData->currentIndex())+" d");
    m_ptwData->addTab(pNew,STable::GetArticleType(pCurrent->getArticleSelect()));
    m_ptwData->setCurrentIndex(m_ptwData->count()-1);
    if (nCurrentFilterGroupID != D_NOT_SELECT)
        RefreshFilter(nCurrentFilterGroupID);
}

void Widget::SearchKeyword()
{
    STable *pNew = new STable;
    STable *pCurrent = (STable *)m_ptwData->currentWidget();
    pNew->setArticleSelect(pCurrent->getArticleSelect());
    pNew->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);
    int nCurrentFilterGroupID = D_NOT_SELECT;

    QString strKey = m_pleString->text().replace("\r\n"," ");

    strKey = strKey.replace("\n"," ");
    strKey = strKey.replace("\t"," ");

    QString strTemp;
    foreach(QString str, strKey.split(" "))
    {
        if (str.trimmed().isEmpty() == false)
            strTemp += str.trimmed() + " ";
    }

    strTemp = strTemp.trimmed();
    m_pleString->setText(strTemp);
    strKey = strTemp;

    if (m_pgbFilter->isChecked())
    {
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
        {
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
            DataBaseSearchFilter(pNew->getArticleSelect(),m_pcbCatalog->currentIndex(),m_pcbMethod->currentIndex(),m_pcbKeyword->currentIndex(),strKey,nCurrentFilterGroupID,E_DATABASE_COMMAND_INSERT);
        }
    }

    QStringList strListKeyword = strKey.split(" ");
    if (m_pcbMethod->currentIndex() == 1)
    {
        for (int i = 0 ; i < strListKeyword.size(); i++ )
        {
            strListKeyword[i] = " " + strListKeyword[i] + " ";
        }
    }
    m_pProgress->setRange(0,pCurrent->rowCount()-1);    
    for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
    {
        bool bFlag = false;
        //if (m_pcbCatalog->currentText() == "ALL")
        QString strData = pCurrent->item(nCount,m_pcbCatalog->currentIndex())->text();
        switch(m_pcbKeyword->currentIndex())
        {
            case 0:
            {
                foreach(QString strKey , strListKeyword)
                    if (strData.contains(strKey)){bFlag = true;break;}
                break;
            }
            case 1:
            {
                int nKeyCount = 0;
                foreach(QString strKey , strListKeyword)
                    if (strData.contains(strKey)) nKeyCount++;
                if (nKeyCount == strListKeyword.size())
                    bFlag = true;
                break;
            }
            case 2:
            {
                bFlag = true;
                foreach(QString strKey , strListKeyword)
                    if (strData.contains(strKey)){bFlag = false;break;}
                break;
            }
            case 3: bFlag = true;break;
        }
        if (bFlag) InsertCopyRow(nCount,pCurrent,pNew);
        if (m_pcbKeyword->currentIndex() == 3)
        {
            foreach(QString strKey , strListKeyword)
            {
                strData.replace(strKey,"");
            }
            pNew->item(nCount,m_pcbCatalog->currentIndex())->setText(strData);
        }
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    //m_ptwData->addTab(pNew,m_ptwData->tabText(m_ptwData->currentIndex())+" k");
    m_ptwData->addTab(pNew,STable::GetArticleType(pCurrent->getArticleSelect()));
    m_ptwData->setCurrentIndex(m_ptwData->count()-1);

    if (nCurrentFilterGroupID != D_NOT_SELECT)
        RefreshFilter(nCurrentFilterGroupID);
}

void Widget::SearchCounterInsert()
{
    bool ok;
    m_pleCounter->text().toInt(&ok);
    if(!ok)
        return;

    STable *pCurrent = (STable *)m_ptwData->currentWidget();

    int nCatalog = m_pcbCounterCatalog->currentIndex();
    int nFlag = m_pcbCounterInsDel->currentData().toInt();
    int nComp = m_pcbCounterComp->currentData().toInt();
    //int nCntApl = m_pcbCounterCntApl->currentData().toInt();
    int nCurrentFilterGroupID = D_NOT_SELECT;

    m_pProgress->setRange(0,pCurrent->rowCount()-1);

    QString strKey = m_pcbCounterCatalog->currentText();
    strKey += ",";
    strKey += QString::number(m_pcbCounterComp->currentIndex());
    strKey += ",";
    strKey += m_pleCounter->text();


    if (m_pgbFilter->isChecked())
    {
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
        {
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
            DataBaseCounterFilter(pCurrent->getArticleSelect(), nCatalog, nComp, nFlag, m_pleCounter->text(), nCurrentFilterGroupID, E_DATABASE_COMMAND_INSERT);
        }
    }

    //if(m_pcbCounterCntApl->currentIndex() == 0)
    {
        if(m_mapData.contains(strKey))
            m_mapData[strKey].clear();

        QMap<QString, int> mapData;

        for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
        {
            QString str;
            if (nCatalog == m_nColumn)
            {
                QDateTime date;
                str = date.fromString(pCurrent->item(nCount,nCatalog)->text().trimmed(),"yyyy-MM-dd hh:mm:ss").date().toString("yyyy-MM-dd");
            }
            else
                str = pCurrent->item(nCount,nCatalog)->text().trimmed();


            if(mapData.contains(str))
            {
                mapData[str] += 1;
            }
            else
            {
                mapData.insert(str,1);
            }
            m_pProgress->setValue(nCount);
            m_pProgress->repaint();
        }
        int leCount = m_pleCounter->text().toInt();

        if(m_pcbCounterComp->currentIndex() == 0)
        {
            for(QMap<QString, int>::iterator iterPos = mapData.begin(); iterPos != mapData.end() ;iterPos++)
            {
                if(iterPos.value() > leCount)
                {
                    if(m_mapData.contains(strKey))
                    {
                        m_mapData[strKey].insert(iterPos.key(), iterPos.value());
                    }
                    else
                    {
                        QMap<QString, int> temp;
                        temp.insert(iterPos.key(), iterPos.value());
                        m_mapData.insert(strKey, temp);
                    }
                }
            }
        }
        else if(m_pcbCounterComp->currentIndex() == 1)
        {
            for(QMap<QString, int>::iterator iterPos = mapData.begin(); iterPos != mapData.end() ;iterPos++)
            {
                if(iterPos.value() < leCount)
                {
                    if(m_mapData.contains(strKey))
                    {
                        m_mapData[strKey].insert(iterPos.key(), iterPos.value());
                    }
                    else
                    {
                        QMap<QString, int> temp;
                        temp.insert(iterPos.key(), iterPos.value());
                        m_mapData.insert(strKey, temp);
                    }
                }
            }
        }

        else if(m_pcbCounterComp->currentIndex() == 2)
        {
            for(QMap<QString, int>::iterator iterPos = mapData.begin(); iterPos != mapData.end() ;iterPos++)
            {
                if(iterPos.value() == leCount)
                {
                    if(m_mapData.contains(strKey))
                    {
                        m_mapData[strKey].insert(iterPos.key(), iterPos.value());
                    }
                    else
                    {
                        QMap<QString, int> temp;
                        temp.insert(iterPos.key(), iterPos.value());
                        m_mapData.insert(strKey, temp);
                    }
                }
            }
        }
    }

    //if(m_pcbCounterCntApl->currentIndex() == 1)
    {
        if(!m_mapData.contains(strKey))
            return;

        STable *pNew = new STable;
        pNew->setArticleSelect(pCurrent->getArticleSelect());
        pNew->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);

        m_pProgress->setRange(0,pCurrent->rowCount()-1);

        for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
        {
            bool bFlag = false;
            QString strCurrent = pCurrent->item(nCount,nCatalog)->text().trimmed();
            if(m_mapData[strKey].contains(strCurrent))
                bFlag = true;
            if (nFlag == 1) bFlag = !bFlag;
            if (bFlag) InsertCopyRow(nCount,pCurrent,pNew);
            m_pProgress->setValue(nCount);
            m_pProgress->repaint();
        }

        m_ptwData->addTab(pNew,STable::GetArticleType(pCurrent->getArticleSelect()));
        m_ptwData->setCurrentIndex(m_ptwData->count()-1);
    }
    if (nCurrentFilterGroupID != D_NOT_SELECT)
        RefreshFilter(nCurrentFilterGroupID);
    m_mapData[strKey].clear();
}

void Widget::SearchCounterUpdate()
{
    if (m_pgbFilter->isChecked())
    {
        int nCurrentFilterGroupID = D_NOT_SELECT;
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();

        if (nCurrentFilterGroupID == D_NOT_SELECT) return;

        int nCatalog = m_pcbCounterCatalog->currentIndex();
        int nComp = m_pcbCounterComp->currentData().toInt();
        int nFlag = m_pcbCounterInsDel->currentData().toInt();
        foreach (QListWidgetItem *item,m_plwFilter->selectedItems())
            DataBaseLengthFilter(((STable *)m_ptwData->currentWidget())->getArticleSelect(),nCatalog,nComp,nFlag,m_pleCounter->text(),nCurrentFilterGroupID,E_DATABASE_COMMAND_UPDATE,item->data(Qt::UserRole).toString());
        RefreshFilter(nCurrentFilterGroupID);
    }
}


void Widget::SearchLengthInsert()
{
    STable *pNew = new STable;
    STable *pCurrent = (STable *)m_ptwData->currentWidget();
    pNew->setArticleSelect(pCurrent->getArticleSelect());
    pNew->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);
    m_pProgress->setRange(0,pCurrent->rowCount()-1);
    int nCatalog = m_pcbLengthCatalog->currentIndex();
    int nComp = m_pcbLengthComp->currentData().toInt();
    int nFlag = m_pcbLengthInsDel->currentData().toInt();
    int nLength = m_pleLength->text().toInt();

    int nCurrentFilterGroupID = D_NOT_SELECT;

    if (m_pgbFilter->isChecked())
    {
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
        {
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
            DataBaseLengthFilter(pCurrent->getArticleSelect(),nCatalog,nComp,nFlag,m_pleLength->text(),nCurrentFilterGroupID,E_DATABASE_COMMAND_INSERT);
        }
    }

    for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
    {
        bool bFlag = false;
        int nCurrentLength = pCurrent->item(nCount,nCatalog)->text().trimmed().length();        
        switch(nComp)
        {
        case E_LENGTH_COMP_GREATER:
            if (nCurrentLength > nLength)
                bFlag = true;
            break;
        case E_LENGTH_COMP_LESS:
            if (nCurrentLength < nLength)
                bFlag = true;
            break;
        case E_LENGTH_COMP_EQUAL:
            if (nLength == nCurrentLength)
                bFlag = true;
            break;
        }
        if (nFlag == 1) bFlag = !bFlag;
        if (bFlag) InsertCopyRow(nCount,pCurrent,pNew);
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    //m_ptwData->addTab(pNew,m_ptwData->tabText(m_ptwData->currentIndex())+" c");
    m_ptwData->addTab(pNew,STable::GetArticleType(pCurrent->getArticleSelect()));
    m_ptwData->setCurrentIndex(m_ptwData->count()-1);
    if (nCurrentFilterGroupID != D_NOT_SELECT)
        RefreshFilter(nCurrentFilterGroupID);
}

void Widget::SearchReplaceInsert()
{
    STable *pNew = new STable;
    STable *pCurrent = (STable *)m_ptwData->currentWidget();
    pNew->setArticleSelect(pCurrent->getArticleSelect());
    pNew->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);
    m_pProgress->setRange(0,pCurrent->rowCount()-1);
    int nCatalog = m_pcbReplaceCatalog->currentIndex();    
    QStringList strListKeyword;
    if (m_pcbReplaceFind->currentData().toInt() == E_REPLACE_SPACE)
        strListKeyword = m_pleReplaceFind->text().split(" ");
    else
        strListKeyword.push_back(m_pleReplaceFind->text());

    int nCurrentFilterGroupID = D_NOT_SELECT;
    int nReplace = m_pcbReplace->currentIndex();
    if (m_pgbFilter->isChecked())
    {
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
        {
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
            DataBaseReplaceFilter(pNew->getArticleSelect(),nCatalog,
                                m_pcbReplaceFind->currentData().toInt(),
                                m_pleReplaceFind->text(),m_pleReplace->text(),
                                nCurrentFilterGroupID,E_DATABASE_COMMAND_INSERT);
        }
    }
    pNew->setRowCount(pCurrent->rowCount());
    for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
    {
        for (int nColumnCount = 0;nColumnCount < pCurrent->columnCount() ;nColumnCount++ )
        {
            if (nCatalog == nColumnCount)
            {
                QString strOut = pCurrent->item(nCount,nColumnCount)->text();
                switch(nReplace)
                {
                case 0:
                {
                    foreach(QString str,strListKeyword)
                        strOut = strOut.replace(str,m_pleReplace->text());
                    break;
                }
                case 1:
                {
                    QString strMiddle;
                    foreach(QString strLine,strOut.split("\n"))
                    {
                        foreach(QString strWord,strLine.split(" "))
                        {
                            bool bFlag = false;
                            foreach(QString str,strListKeyword)
                            {
                                if (strWord == str)
                                {
                                    strMiddle += m_pleReplace->text() + " ";
                                    bFlag = true;
                                    break;
                                }
                            }
                            if (bFlag == false)
                                strMiddle += strWord + " ";
                        }
                        strMiddle += "\n";
                    }
                    strOut = strMiddle;
                    break;
                }
                case 2:
                    QString strMiddle;
                    foreach(QString strLine,strOut.split("\n"))
                    {
                        foreach(QString strWord,strLine.split(" "))
                        {
                            bool bFlag = false;
                            foreach(QString str,strListKeyword)
                            {
                                if (strWord.contains(str))
                                {
                                    strMiddle += m_pleReplace->text() + " ";
                                    bFlag = true;
                                    break;
                                }
                            }
                            if (bFlag == false)
                                strMiddle += strWord + " ";
                        }
                        strMiddle += "\n";
                    }
                    strOut = strMiddle;
                    break;
                }
                pNew->setItem(nCount,nColumnCount,new QTableWidgetItem(strOut));
            }
            else
                pNew->setItem(nCount,nColumnCount,new QTableWidgetItem(*pCurrent->item(nCount,nColumnCount)));
        }
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    //m_ptwData->addTab(pNew,m_ptwData->tabText(m_ptwData->currentIndex())+" r");
    m_ptwData->addTab(pNew,STable::GetArticleType(pCurrent->getArticleSelect()));
    m_ptwData->setCurrentIndex(m_ptwData->count()-1);

    if (nCurrentFilterGroupID != D_NOT_SELECT)
        RefreshFilter(nCurrentFilterGroupID);    
}

void Widget::SearchDateUpdate()
{
    if (m_pgbFilter->isChecked())
    {
        int nCurrentFilterGroupID = D_NOT_SELECT;
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();

        if (nCurrentFilterGroupID == D_NOT_SELECT) return;

        foreach (QListWidgetItem *item,m_plwFilter->selectedItems())
            DataBaseTimeFilter(((STable *)m_ptwData->currentWidget())->getArticleSelect(),m_pdeStart->date(),m_pdeEnd->date(),nCurrentFilterGroupID,E_DATABASE_COMMAND_UPDATE,item->data(Qt::UserRole).toString());
        RefreshFilter(nCurrentFilterGroupID);
    }
}

void Widget::SearchKeywordUpdate()
{
    if (m_pgbFilter->isChecked())
    {
        int nCurrentFilterGroupID = D_NOT_SELECT;
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();
        if (nCurrentFilterGroupID == D_NOT_SELECT) return;
        QString strKey = m_pleString->text().replace("\r\n"," ");
        strKey = strKey.replace("\n"," ");
        strKey = strKey.replace("\t"," ");
        QString strTemp;
        foreach(QString str, strKey.split(" "))
        {
            if (str.trimmed().isEmpty() == false)
                strTemp += str.trimmed() + " ";
        }
        strTemp = strTemp.trimmed();
        m_pleString->setText(strTemp);
        strKey = strTemp;
        foreach (QListWidgetItem *item,m_plwFilter->selectedItems())
            DataBaseSearchFilter(((STable *)m_ptwData->currentWidget())->getArticleSelect(),m_pcbCatalog->currentIndex(),m_pcbMethod->currentIndex(),m_pcbKeyword->currentIndex(),strKey,nCurrentFilterGroupID,E_DATABASE_COMMAND_UPDATE,item->data(Qt::UserRole).toString());
        RefreshFilter(nCurrentFilterGroupID);
    }
}

void Widget::SearchLengthUpdate()
{
    if (m_pgbFilter->isChecked())
    {
        int nCurrentFilterGroupID = D_NOT_SELECT;
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();

        if (nCurrentFilterGroupID == D_NOT_SELECT) return;

        int nCatalog = m_pcbLengthCatalog->currentIndex();
        int nComp = m_pcbLengthComp->currentData().toInt();
        int nFlag = m_pcbLengthInsDel->currentData().toInt();
        foreach (QListWidgetItem *item,m_plwFilter->selectedItems())
            DataBaseLengthFilter(((STable *)m_ptwData->currentWidget())->getArticleSelect(),nCatalog,nComp,nFlag,m_pleLength->text(),nCurrentFilterGroupID,E_DATABASE_COMMAND_UPDATE,item->data(Qt::UserRole).toString());
        RefreshFilter(nCurrentFilterGroupID);
    }
}

void Widget::SearchReplaceUpdate()
{
    if (m_pgbFilter->isChecked())
    {
        int nCurrentFilterGroupID = D_NOT_SELECT;
        foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
            nCurrentFilterGroupID = item->data(Qt::UserRole).toInt();

        if (nCurrentFilterGroupID == D_NOT_SELECT) return;

        int nCatalog = m_pcbReplaceCatalog->currentIndex();
        QStringList strListKeyword;
        if (m_pcbReplaceFind->currentData().toInt() == E_REPLACE_SPACE)
            strListKeyword = m_pleReplaceFind->text().split(" ");
        else
            strListKeyword.push_back(m_pleReplaceFind->text());

        foreach (QListWidgetItem *item,m_plwFilter->selectedItems())
            DataBaseReplaceFilter(((STable *)m_ptwData->currentWidget())->getArticleSelect(),nCatalog,
                                        m_pcbReplaceFind->currentData().toInt(),
                                        m_pleReplaceFind->text(),m_pleReplace->text(),
                                        nCurrentFilterGroupID,E_DATABASE_COMMAND_UPDATE,item->data(Qt::UserRole).toString());
        RefreshFilter(nCurrentFilterGroupID);
    }
}


void Widget::DataGroupItemChanged( QListWidgetItem *item)
{
    QMessageBox msg;
    msg.setText("Please choose...");
    msg.setModal(true);

    QPushButton *pbAll = msg.addButton("All",QMessageBox::ActionRole);
    QPushButton *pbBody = msg.addButton("Body",QMessageBox::ActionRole);
    QPushButton *pbReply = msg.addButton("Reply",QMessageBox::ActionRole);
    msg.exec();
    if (msg.clickedButton() == pbAll) DataReload("data_" + item->data(Qt::UserRole).toString(),STable::E_ARTICLE_ALL);
    else if (msg.clickedButton() == pbBody) DataReload("data_" + item->data(Qt::UserRole).toString(),STable::E_ARTICLE_BODY);
    else if (msg.clickedButton() == pbReply) DataReload("data_" + item->data(Qt::UserRole).toString(),STable::E_ARTICLE_REPLY);

}

void Widget::DataReload(QString _strTableName,int _nSelect)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    QString strSelect;
    strSelect = "select ";
    foreach(QStringList strlist,m_vecColumn)
        strSelect += "CONVERT(" + strlist.at(E_COLUMN_DATABASE) + " USING utf8),";
    strSelect = strSelect.left(strSelect.size()-1);
    strSelect += " from ";
    strSelect += _strTableName;

    if (_nSelect == STable::E_ARTICLE_BODY)
        strSelect += " WHERE article_form = 'body'";
    if (_nSelect == STable::E_ARTICLE_REPLY)
        strSelect += " WHERE article_form = 'reply'";

    QSqlQuery query(strSelect);
    STable *pTable = (STable *)m_ptwData->currentWidget();
    pTable->setArticleSelect(_nSelect);
    pTable->clear();

    pTable->SetHeaderList(&m_vecColumn,E_COLUMN_NAME);
    pTable->setRowCount(query.size());
    m_pProgress->setRange(0,query.size());
    int nCount = 0;
    while (query.next())
    {
        for (int i = 0; i < pTable->columnCount() ; i++)
        {
            QString str = query.value(i).toString().replace("\n","     ");
            pTable->setItem(nCount,i,new QTableWidgetItem(" "+str.replace("\t"," ")+" "));
        }
        nCount++;
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    db.close();
}

void Widget::FilterGroupInsert()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }

    QString strQuery = QString("insert into filtergroup set "
            "name = '" + m_pleFilterGroup->text() + "'");
    db.exec(strQuery.toUtf8());
    db.close();
    FilterGroupRefresh();
}

void Widget::FilterGroupDelete()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
    {
        QString strQuery = QString("delete from filtergroup where id = " + item->data(Qt::UserRole).toString());
        db.exec(strQuery.toUtf8());
        strQuery = QString("delete from filter where filtergroup_id = " + item->data(Qt::UserRole).toString());
        db.exec(strQuery.toUtf8());
        RefreshFilter(item->data(Qt::UserRole).toInt());
    }
    db.close();
    FilterGroupRefresh();    
}

void Widget::FilterGroupModify()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
    {
        QString strQuery = QString("update filtergroup set name = '" + m_pleFilterGroup->text() +  "' where id = " + item->data(Qt::UserRole).toString());
        qDebug() << strQuery;
        db.exec(strQuery.toUtf8());
    }
    db.close();
    FilterGroupRefresh();
}

void Widget::FilterGroupCopyPaste()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
    {
        QSqlQuery query;
        QString strQuery = QString("insert into filtergroup set "
                "name = '" + item->text() + "-'");
        query.exec(strQuery.toUtf8());
        query.exec("select max(id) from filtergroup");
        if (query.next())
        {
            strQuery = QString("insert into filter (type,data,filtergroup_id) select type,data,");
            strQuery += query.value(0).toString();
            strQuery += " from filter where filtergroup_id = " + item->data(Qt::UserRole).toString();
            qDebug() << strQuery;
            query.exec(strQuery.toUtf8());
        }
    }
    db.close();
    FilterGroupRefresh();
}

void Widget::FilterGroupRefresh()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    m_plwFilterGroup->clear();
    QSqlQuery query("select id,name from filtergroup");
    while (query.next())
    {
        QListWidgetItem *pItem = new QListWidgetItem(query.value(1).toString(),m_plwFilterGroup);
        pItem->setData(Qt::UserRole, QVariant(query.value(0)));
    }
    db.close();
}

void Widget::DataBaseFilter(int _nType,QString _strJson,int _nGroup,int _nCommand,QString _strFilterId)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }

    QString sql;
    switch(_nCommand)
    {
    case E_DATABASE_COMMAND_INSERT:
        sql = "INSERT INTO filter SET ";
        sql += QString("type=") + QString::number(_nType) + ",";
        break;
    case E_DATABASE_COMMAND_UPDATE:
        sql = "UPDATE filter SET ";
        break;
    }
    sql += QString("data='") + _strJson + "',";
    sql += QString("filtergroup_id=" ) + QString::number(_nGroup);
    if (_nCommand == E_DATABASE_COMMAND_UPDATE)
        sql += QString(" where id=") + _strFilterId;
    QSqlQuery query;
    if (query.exec(sql.toUtf8()) == false)
    {
        qDebug() << sql;
        qDebug() << query.lastError().text();
    }
    db.close();
}

void Widget::DataBaseTimeFilter(int _nArticle ,QDate _dateStart ,QDate _dateEnd ,int _nGroup,int _nCommand,QString _strFilterId )
{    
    QString strJson;
    SJson json;
    strJson = json.Set(strJson,"Article",QString::number(_nArticle));
    strJson = json.Set(strJson,"Start",_dateStart.toString("yyyy-MM-dd"));
    strJson = json.Set(strJson,"End",_dateEnd.toString("yyyy-MM-dd"));
    DataBaseFilter(E_FILTER_TYPE_DATE,json.Sql(strJson),_nGroup,_nCommand,_strFilterId);
}

void Widget::DataBaseSearchFilter(int _nArticle,int _nCategory,int _nMethod,int _nKeyword, QString _str,int _nGroup,int _nCommand,QString _strFilterId)
{    
    QString strJson;
    SJson json;
    strJson = json.Set(strJson,"Article",QString::number(_nArticle));
    strJson = json.Set(strJson,"Category",_nCategory);
    strJson = json.Set(strJson,"Method",_nMethod);
    strJson = json.Set(strJson,"Keyword",_nKeyword);
    strJson = json.Set(strJson,"String",_str);
    DataBaseFilter(E_FILTER_TYPE_SEARCH,json.Sql(strJson),_nGroup,_nCommand,_strFilterId);
}

void Widget::DataBaseLengthFilter(int _nArticle,int _nCategory,int _nComp,int _nInsDel,QString _str,int _nGroup,int _nCommand,QString _strFilterId)
{
    QString strJson;
    SJson json;
    strJson = json.Set(strJson,"Article",QString::number(_nArticle));
    strJson = json.Set(strJson,"Category",_nCategory);
    strJson = json.Set(strJson,"Comp",_nComp);
    strJson = json.Set(strJson,"InsDel",_nInsDel);
    strJson = json.Set(strJson,"String",_str);
    DataBaseFilter(E_FILTER_TYPE_LENGTH,json.Sql(strJson),_nGroup,_nCommand,_strFilterId);
}


void Widget::DataBaseCounterFilter(int _nArticle,int _nCategory,int _nComp,int _nInsDel,QString _str,int _nGroup,int _nCommand,QString _strFilterId)
{
    QString strJson;
    SJson json;
    strJson = json.Set(strJson,"Article",QString::number(_nArticle));
    strJson = json.Set(strJson,"Category",_nCategory);
    strJson = json.Set(strJson,"Comp",_nComp);
    strJson = json.Set(strJson,"InsDel",_nInsDel);
    strJson = json.Set(strJson,"String",_str);
    DataBaseFilter(E_FILTER_TYPE_COUNTER,json.Sql(strJson),_nGroup,_nCommand,_strFilterId);
}



void Widget::DataBaseReplaceFilter(int _nArticle,int _nCategory,int _nFind,QString _strFind,QString _strReplace,int _nGroup,int _nCommand,QString _strFilterId)
{
    QString strJson;
    SJson json;
    strJson = json.Set(strJson,"Article",QString::number(_nArticle));
    strJson = json.Set(strJson,"Category",_nCategory);
    strJson = json.Set(strJson,"Find",_nFind);
    strJson = json.Set(strJson,"String_Find",_strFind);
    strJson = json.Set(strJson,"String_Replace",_strReplace);
    DataBaseFilter(E_FILTER_TYPE_REPLACE,json.Sql(strJson),_nGroup,_nCommand,_strFilterId);
}

void Widget::RefreshFilter(int _nGroup)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    QSqlQuery query("select id,type,data from filter where filtergroup_id = " + QString::number(_nGroup));

    SJson json;
    m_plwFilter->clear();
    while (query.next())
    {
        QString str;
        QString strJson = query.value(2).toString();
        str = STable::GetArticleType(json.Get(strJson,"Article").toInt());
        switch(query.value(1).toInt())
        {
        case E_FILTER_TYPE_DATE:
            str += "<Date> Start : ";
            str += json.Get(strJson,"Start");
            str += " End : ";
            str += json.Get(strJson,"End");
            break;
        case E_FILTER_TYPE_SEARCH:
            str += "<Search> ";
            str += m_pcbCatalog->itemText(json.GetNumber(strJson,"Category")) + " , ";
            str += m_pcbMethod->itemText(json.GetNumber(strJson,"Method")) + " , ";
            str += m_pcbKeyword->itemText(json.GetNumber(strJson,"Keyword")) + " , ";
            str += json.Get(strJson,"String");
            break;
        case E_FILTER_TYPE_LENGTH:
            str += "<Length> ";
            str += m_pcbLengthCatalog->itemText(json.GetNumber(strJson,"Category")) + " ";
            str += m_pcbLengthComp->itemText(json.GetNumber(strJson,"Comp")) + " ";
            str += json.Get(strJson,"String") + " , ";
            str += m_pcbLengthInsDel->itemText(json.GetNumber(strJson,"InsDel"));
            break;
        case E_FILTER_TYPE_REPLACE:
            str += "<Replace> ";
            str += m_pcbReplaceCatalog->itemText(json.GetNumber(strJson,"Category")) + " , ";
            str += m_pcbReplaceFind->itemText(json.GetNumber(strJson,"Find")) + " ";
            str += json.Get(strJson,"String_Find") + " --> ";
            str += json.Get(strJson,"String_Replace");
            break;
        case E_FILTER_TYPE_COUNTER:
            str += "<Counter> ";
            str += m_pcbCounterCatalog->itemText(json.GetNumber(strJson,"Category")) + " ";
            str += m_pcbCounterComp->itemText(json.GetNumber(strJson,"Comp")) + " ";
            str += json.Get(strJson,"String") + " , ";
            str += m_pcbCounterInsDel->itemText(json.GetNumber(strJson,"InsDel"));
            break;
        }        
        QListWidgetItem *pItem = new QListWidgetItem(str,m_plwFilter);
        pItem->setData(Qt::UserRole, QVariant(query.value(0)));        
    }
    db.close();
}

void Widget::currentGroupItemChanged(QListWidgetItem *_pCurrent, QListWidgetItem *_pPrev)
{
    Q_UNUSED(_pPrev);
    if (_pCurrent == 0) return;
    RefreshFilter(_pCurrent->data(Qt::UserRole).toInt());
    m_pleFilterGroup->setText(_pCurrent->text());
    m_pleFilterGroup->repaint();
}

void Widget::FilterDelete()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    foreach (QListWidgetItem *item,m_plwFilter->selectedItems())
    {
        QString strQuery = QString("delete from filter where id = '" + item->data(Qt::UserRole).toString() + "'");
        db.exec(strQuery.toUtf8());
    }
    db.close();
    foreach (QListWidgetItem *item,m_plwFilterGroup->selectedItems())
        RefreshFilter(item->data(Qt::UserRole).toInt());
}

void Widget::currentFilterItemChanged(QListWidgetItem *_pCurrent, QListWidgetItem *_pPrev)
{
    Q_UNUSED(_pPrev);
    if (_pCurrent == 0) return;
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("bigbird.iptime.org");
    db.setUserName("admin");
    db.setPassword("admin123");
    db.setDatabaseName("concepters");
    if (db.open() == false)
    {
        qDebug() << db.lastError().text();
        return;
    }
    QSqlQuery query("select id,type,data from filter where id = " + _pCurrent->data(Qt::UserRole).toString());
    if (!query.next()) return;
    SJson json;
    QString strJson = query.value(2).toString();
    switch(query.value(1).toInt())
    {
    case E_FILTER_TYPE_DATE:
        m_pdeStart->setDate(QDate::fromString(json.Get(strJson,"Start"),"yyyy-MM-dd"));
        m_pdeEnd->setDate(QDate::fromString(json.Get(strJson,"End"),"yyyy-MM-dd"));
        m_pleString->setText("");
        m_pleLength->setText("");
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        break;
    case E_FILTER_TYPE_SEARCH:
        m_pcbCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbMethod->setCurrentIndex(json.GetNumber(strJson,"Method"));
        m_pcbKeyword->setCurrentIndex(json.GetNumber(strJson,"Keyword"));
        m_pleString->setText(json.Get(strJson,"String"));
        m_pleLength->setText("");
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");

        break;
    case E_FILTER_TYPE_LENGTH:
        m_pcbLengthCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbLengthComp->setCurrentIndex(json.GetNumber(strJson,"Comp"));
        m_pcbLengthInsDel->setCurrentIndex(json.GetNumber(strJson,"InsDel"));
        m_pleLength->setText(json.Get(strJson,"String"));
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        m_pleString->setText("");
        break;
    case E_FILTER_TYPE_REPLACE:
        m_pcbReplaceCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbReplaceFind->setCurrentIndex(json.GetNumber(strJson,"Find"));
        m_pleReplaceFind->setText(json.Get(strJson,"String_Find"));
        m_pleReplace->setText(json.Get(strJson,"String_Replace"));
        m_pleString->setText("");
        m_pleLength->setText("");
        break;
    case E_FILTER_TYPE_COUNTER:
        m_pcbCounterCatalog->setCurrentIndex(json.GetNumber(strJson,"Category"));
        m_pcbCounterComp->setCurrentIndex(json.GetNumber(strJson,"Comp"));
        m_pcbCounterInsDel->setCurrentIndex(json.GetNumber(strJson,"InsDel"));
        m_pleCounter->setText(json.Get(strJson,"String"));
        m_pleReplaceFind->setText("");
        m_pleReplace->setText("");
        m_pleString->setText("");
        break;
    }
}

bool Widget::ReloadColumn()
{
    m_vecColumn.clear();
    qDebug() << "file open ready";

    QFile file("column.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text) == false) return false;
    {
        qDebug() << "file open starting";
        while (!file.atEnd())
        {
            QString str = QString(file.readLine());
            if (str.at(0) == QChar('#')) continue;
            if (str.trimmed().isEmpty()) continue;
            m_vecColumn.push_back(str.split(","));
        }
    }
    if (m_vecColumn.size() <= 0) return false;

    m_nColumn = -1;
    m_nTitle = -1;
    m_nBody = -1;
    m_nPlatformTitle = -1;
    foreach(QStringList strList,m_vecColumn)
    {
        if (strList.at(E_COLUMN_DATE).trimmed() == QString("o") )
            break;
        else
            m_nColumn++;
    }
    m_nColumn++;
    foreach(QStringList strList,m_vecColumn)
    {
        if (strList.at(E_COLUMN_DATABASE).trimmed() == QString("article_title") )
            break;
        else
            m_nTitle++;
    }
    m_nTitle++;
    foreach(QStringList strList,m_vecColumn)
    {
        if (strList.at(E_COLUMN_DATABASE).trimmed() == QString("article_data") )
            break;
        else
            m_nBody++;
    }
    m_nBody++;

    foreach(QStringList strList,m_vecColumn)
    {
        if (strList.at(E_COLUMN_DATABASE).trimmed() == QString("platform_title") )
            break;
        else
            m_nPlatformTitle++;
    }
    m_nPlatformTitle++;

    return true;
}

void Widget::FileImport()
{
    QString strFilename = QFileDialog::getOpenFileName(0,"Import file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));

    QFile file(strFilename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;

    STable *pNew = new STable;
    QTextCodec *codec = QTextCodec::codecForName("eucKR");
    QTextStream in(&file);
    int ncRow=0;
    int nCount=0;
    bool bQuit = true;
    int nRead = 0;
    int nFileLine = 0;
    QVector<int> wgHeader;
    QStringList strlistHeader;

    for(int i = 0; i < m_vecColumn.size(); i++)
    {
        strlistHeader << m_vecColumn.at(i).at(E_COLUMN_NAME);
    }


    while(!in.atEnd())
    {
        in.readLine();
        nFileLine++;
    }

    in.seek(0);

    while(!in.atEnd())
    {
        QString strLine = in.readLine();

        if (nCount == 0)
        {
            QStringList strings = strLine.split(",");
            if (strings.at(0) == QString("#Head#"))
            {
                m_pProgress->setRange(0,nFileLine - 1);
                pNew->setRowCount(nFileLine - 1);

                pNew->setColumnCount(m_vecColumn.size());
                for (int i = 1; i < strings.size();i++)
                {
                    for (int j = 0; j < m_vecColumn.size(); j++)
                    {
                        if (strlistHeader.contains(strings.at(i)))
                        {
                            if (m_vecColumn.at(j).at(E_COLUMN_NAME) == strings.at(i).trimmed())
                            {
                                wgHeader << j;
                            }
                        }
                        else
                            wgHeader << -1;
                    }
                }
                nCount++;
                qDebug() << m_vecColumn.size();

                for(int i = 0; i < m_vecColumn.size(); i++)
                {
                    qDebug() << i;
                    pNew->setHorizontalHeaderItem(i ,new QTableWidgetItem(m_vecColumn.at(wgHeader.at(i)).at(E_COLUMN_NAME)));
                }

                continue;
            }
            else
            {
                pNew->setColumnCount(strings.size());
                m_pProgress->setRange(0,nFileLine);
                pNew->setRowCount(nFileLine);

            }
        }
        strLine = strLine.replace("\"","");
        QStringList strings = strLine.split(",");
        int ncCol=0;
        //pNew->setRowCount(strings.size());
        foreach(QString str,strings)
        {
            if(wgHeader.at(ncCol) != -1)
                pNew->setItem(ncRow,wgHeader.at(ncCol),new QTableWidgetItem(QString(" " + str.trimmed() + " ")));
            ncCol++;
        }
        ncRow++;
        m_pProgress->setValue(ncRow+1);
        m_pProgress->repaint();
        //qDebug() << ncRow;
    }

    file.close();
    m_ptwData->addTab(pNew,"import");
    m_ptwData->setCurrentIndex(m_ptwData->count()-1);
}

void Widget::FileExport()
{
    QString strFilename = QFileDialog::getSaveFileName(0,"Exoprt file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("Text files (*.csv)"));
    if (strFilename.toLower().right(4) != QString(".csv"))
        strFilename += ".csv";
    QFile file(strFilename);
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;

    QTextStream out(&file);
    QTableWidget *pCurrent = (QTableWidget *)m_ptwData->currentWidget();
    out << "#Head#,";

    foreach(QStringList strList,m_vecColumn)
        out << strList.at(E_COLUMN_NAME) << ",";
    out << endl;

    m_pProgress->setRange(0,pCurrent->rowCount()-1);
    for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
    {
        for (int nColumnCount = 0;nColumnCount < pCurrent->columnCount() ;nColumnCount++ )
        {
            QString str = pCurrent->item(nCount,nColumnCount)->text();
            str = str.replace(",",".");
            str = str.replace("\n","");
            out << "\"" << str << "\"" << ",";
        }
        out << "\"\"" << endl;
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    file.close();
}

void Widget::FileExit()
{
    exit(1);
}


void Widget::CountSave()
{
    QTableWidget *pCurrent = (QTableWidget *)m_ptwData->currentWidget();
    int nCatalog = m_pcbCountCatalog->currentIndex();
    QString strFilename = QFileDialog::getSaveFileName(0,"Count file",QDir::currentPath(),
            "csv files (*.csv);;All files (*.*)",new QString("csv files (*.csv)"));
    if (strFilename.toLower().right(4) != QString(".csv"))
        strFilename += ".csv";
    m_pProgress->setRange(0,pCurrent->rowCount()-1);

    QVector <SCount> vecData;
    for (int nCount = 0 ; nCount < pCurrent->rowCount(); nCount++ )
    {
        QString str;
        if (nCatalog == m_nColumn)
        {
            QDateTime date;
            str = date.fromString(pCurrent->item(nCount,nCatalog)->text().trimmed(),"yyyy-MM-dd hh:mm:ss").date().toString("yyyy-MM-dd");
        }
        else
            str = pCurrent->item(nCount,nCatalog)->text().trimmed();
        bool bInsert = true;
        for (int i = 0; i < vecData.size(); i++)
        {
            if(vecData[i].m_str.compare(str) == 0)
            {
                vecData[i].m_nCount++;
                bInsert = false;
                break;
            }
        }
        if (bInsert)
            vecData.push_back(SCount(str));
        m_pProgress->setValue(nCount);
        m_pProgress->repaint();
    }
    QFile file(strFilename);
    if(!file.open(QFile::WriteOnly | QFile::Text)) return;
    QTextStream out(&file);
    out << pCurrent->horizontalHeaderItem(nCatalog)->text() << "," << vecData.size() << endl << endl;
    foreach(SCount stCount,vecData)
    {
        QString str = stCount.m_str.replace(",",".");
        str = str.replace("\n","");
        out << "\"" << str << "\"" << "," << stCount.m_nCount << endl;
    }
    file.close();
}
void Widget::Debug(QString _strMsg)
{
    /*
    QTime time = QTime::currentTime();
    QString strOut = time.toString("[hh:mm:ss] ") + _strMsg;

    QFile file(QDate::currentDate().toString(Qt::ISODate)+ "_" + QString::number(QCoreApplication::applicationPid())+ ".debug.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        return;

    QTextStream out(&file);
    out << strOut << "\n";
    file.close();
    */
}
