#include "sanaly2.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; }

SAnaly2::SAnaly2(QWidget *parent)
    : QWidget(parent)
{
    if(!setListMorphere(m_strlistMorphere, m_strlistMorphereko))
    {
        m_strlistMorphere << "NNG" <<"NNP"<<"NNB"<<"NNBC"<<"NR"<<"NP"<<"VV"<<"VA"<<"VX"<<"VCP"<<"VCN"<<"MM"<<"MAG"<<"MAJ"<<"IC"<<"JKS"<<"JKC"<<"JKG"<<"JKO"<<"JKB"<<"JKV"<<"JKQ"<<"JX"<<"JC"<<"EP"<<"EF"<<"EC"<<"ETN"<<"ETM"<<"XPN"<<"XSN"<<"XSV"<<"XSA"<<"XR"<<"SF"<<"SE"<<"SSO"<<"SSC"<<"SC"<<"SY"<<"SL"<<"SH"<<"SN";
        m_strlistMorphereko << "NNG" <<"NNP"<<"NNB"<<"NNBC"<<"NR"<<"NP"<<"VV"<<"VA"<<"VX"<<"VCP"<<"VCN"<<"MM"<<"MAG"<<"MAJ"<<"IC"<<"JKS"<<"JKC"<<"JKG"<<"JKO"<<"JKB"<<"JKV"<<"JKQ"<<"JX"<<"JC"<<"EP"<<"EF"<<"EC"<<"ETN"<<"ETM"<<"XPN"<<"XSN"<<"XSV"<<"XSA"<<"XR"<<"SF"<<"SE"<<"SSO"<<"SSC"<<"SC"<<"SY"<<"SL"<<"SH"<<"SN";
    }

    QVBoxLayout *vMainLayout = new QVBoxLayout;
    vMainLayout->setAlignment(Qt::AlignVCenter);
    QVBoxLayout *vboxlayout = new QVBoxLayout;

    QGroupBox *gBox = setMorphereList();
    QGroupBox *gDate = setDate();
    QGroupBox *gFilter = setFilter();
    QGroupBox *gOther = setOther();
    QGroupBox *gSort = setSort();
    QHBoxLayout *hboxlayout = new QHBoxLayout;
    QGroupBox *gDictionary = setDictionary();
    QGroupBox *gCenterKeyword = setCenterKeyword();


    hboxlayout->addWidget(gBox,5);

    vboxlayout->addWidget(gDate,3);
    //vboxlayout->addWidget(gFilter,3);
    vboxlayout->addWidget(gSort,2);
    vboxlayout->addWidget(gOther,2);
    vboxlayout->addWidget(gDictionary,2);

    hboxlayout->addLayout(vboxlayout,5);
    vMainLayout->addLayout(hboxlayout, 2);

    vMainLayout->addWidget(gCenterKeyword, 1);

    m_ptwData = new QTabWidget;
    m_ptwData->setTabsClosable(true);
    connect(m_ptwData,SIGNAL(tabCloseRequested(int)),this,SLOT(CloseTab(int)));
    connect(m_ptwData,SIGNAL(tabBarDoubleClicked(int)),this,SLOT(DoubleClickTab(int)));
    AddTable("Start");

    vMainLayout->addWidget(m_ptwData, 8);
    setLayout(vMainLayout);
}

QGroupBox *SAnaly2::setMorphereList()
{
    QVBoxLayout *vlayout = new QVBoxLayout;
    QVBoxLayout *vlayout1 = new QVBoxLayout;

    QHBoxLayout *hlayout = new QHBoxLayout;
    QGroupBox *groupBox = new QGroupBox(tr("Morphere List"));

    m_plwMorphereList = new QListWidget;
    m_plwMorphereAdd  = new QListWidget;
    m_plwMorphereList->setSelectionMode(QAbstractItemView::MultiSelection);
    m_plwMorphereAdd->setSelectionMode(QAbstractItemView::ExtendedSelection);


    for(int i=0;i<m_strlistMorphere.size();i++)
    {
        QListWidgetItem* pitem = new QListWidgetItem(m_strlistMorphereko.at(i), m_plwMorphereList);
        pitem->setData(Qt::UserRole, QVariant(m_strlistMorphere.at(i)));
    }

    for(int i=0;i<m_strlistMorphere.size();i++)
    {
        QListWidgetItem* pitem = new QListWidgetItem(m_strlistMorphereko.at(i), m_plwMorphereAdd);
        pitem->setData(Qt::UserRole, QVariant(m_strlistMorphere.at(i)));
    }

    for(int i=0;i<m_plwMorphereAdd->count();i++)
    {
        m_plwMorphereAdd->item(i)->setHidden(true);
    }


    QPushButton *ppbAdd = new QPushButton("Add");
    QPushButton *ppbDel = new QPushButton("Del");
    vlayout->addWidget(m_plwMorphereList);
    vlayout->addWidget(ppbAdd);

    vlayout1->addWidget(m_plwMorphereAdd);
    vlayout1->addWidget(ppbDel);

    connect(ppbAdd, SIGNAL(released()),this, SLOT(MorphereListAdd()));
    connect(ppbDel, SIGNAL(released()),this, SLOT(MorphereListDel()));

    hlayout->addLayout(vlayout);
    hlayout->addLayout(vlayout1);

    groupBox->setLayout(hlayout);
    groupBox->setCheckable(true);
    return groupBox;
}


QGroupBox *SAnaly2::setDate()
{
    QHBoxLayout *hlayout = new QHBoxLayout;
    QHBoxLayout *hlayout1 = new QHBoxLayout;
    QVBoxLayout *vlayout = new QVBoxLayout;

    QGroupBox *groupBox = new QGroupBox(tr("Date"));

    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());

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

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

    m_pcbDate = new QComboBox;
    m_pcbDate->addItems(QStringList() << "ALL" << "NotAll");

    m_pcbPeriod = new QComboBox;
    m_pcbPeriod->addItems(QStringList() << "None" << "1 Day" << "1 Week" << "1 Month");

    hlayout->addWidget(m_pcbDate);
    hlayout->addWidget(new QLabel("Start:"));
    hlayout->addWidget(m_pdeStart);
    hlayout->addWidget(new QLabel("End:"));
    hlayout->addWidget(m_pdeEnd);

    hlayout1->addWidget(new QLabel("Period:"));
    hlayout1->addWidget(m_pcbPeriod);

    vlayout->addLayout(hlayout);
    vlayout->addLayout(hlayout1);

    vlayout->addLayout(hlayout);
    vlayout->addLayout(hlayout1);
    groupBox->setCheckable(true);

    groupBox->setLayout(vlayout);

    return groupBox;
}

QGroupBox *SAnaly2::setFilter()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pleKeyword = new QLineEdit;
    m_pleTop = new QLineEdit;

    hlayout->addWidget(new QLabel("Top: <"));
    hlayout->addWidget(m_pleTop);
    hlayout->addWidget(new QLabel("Keyword:"));
    hlayout->addWidget(m_pleKeyword);

    QGroupBox *groupBox = new QGroupBox(tr("Filter"));

    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);
    groupBox->setChecked(false);
    return groupBox;
}

QGroupBox *SAnaly2::setOther()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pcbThread = new QComboBox;

    hlayout->addWidget(new QLabel("Thread:"));
    hlayout->addWidget(m_pcbThread);

    m_pcbThread->addItems(QStringList() << "1" <<  "2" << "4" << "8");

    QGroupBox *groupBox = new QGroupBox(tr("Other"));
    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);

    return groupBox;
}

QGroupBox *SAnaly2::setSort()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_rbDateMorphere = new QRadioButton("Date/Morphere");
    m_rbMorphereDate = new QRadioButton("Morphere/Date");


    m_bgRadioGroup = new QButtonGroup;

    m_bgRadioGroup->addButton(m_rbMorphereDate);
    m_bgRadioGroup->addButton(m_rbDateMorphere);

    m_rbMorphereDate->setChecked(true);

    hlayout->addWidget(m_rbMorphereDate);
    hlayout->addWidget(m_rbDateMorphere);

    QGroupBox *groupBox = new QGroupBox(tr("Sort"));
    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);

    return groupBox;
}


QGroupBox *SAnaly2::setDictionary()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pcbDictionary = new QComboBox;

    m_pcbDictionary->setEditable(true);
    m_pcbDictionary->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    QPushButton* add = new QPushButton;
    QPushButton* del = new QPushButton;
    add->setText(tr("+"));
    del->setText(tr("-"));

    //hlayout->addWidget(new QLabel(tr("User-Dict: ")));
    hlayout->addWidget(m_pcbDictionary);
    hlayout->addWidget(add);
    hlayout->addWidget(del);

    connect(add, SIGNAL(released()),this, SLOT(AddDictionary()));
    connect(del, SIGNAL(released()),this, SLOT(DelDictionary()));

    QGroupBox *groupBox = new QGroupBox(tr("User Dictionary"));
    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);

    return groupBox;
}


QGroupBox *SAnaly2::setCenterKeyword()
{
    QHBoxLayout *hlayout = new QHBoxLayout;

    m_pleCKeyword = new QLineEdit;

    hlayout->addWidget(new QLabel("Center Keyword: "));
    hlayout->addWidget(m_pleCKeyword);

    QGroupBox *groupBox = new QGroupBox(tr("Center Keyword"));

    groupBox->setCheckable(true);

    groupBox->setLayout(hlayout);
    groupBox->setChecked(true);
    return groupBox;
}



void SAnaly2::AddDictionary()
{
    QStringList strFilenames = QFileDialog::getOpenFileNames(0,"Dictionary file",QDir::currentPath(),
            "dic files (*.dic);;All files (*.*)",new QString("Dictionary files (*.dic)"));

    foreach(QString strFilename, strFilenames)
    {
        QFile file(strFilename);
        if (!file.open(QIODevice::ReadOnly)) return;
    }


    for(int i = 0; i < m_pcbDictionary->count(); i++)
    {
        if(strFilenames.contains(m_pcbDictionary->itemText(i)))
            strFilenames.removeOne(m_pcbDictionary->itemText(i));
    }

    m_pcbDictionary->addItems(strFilenames);
}

QString SAnaly2::getUserDictList()
{
    QStringList strList;

    for(int i = 0; i < m_pcbDictionary->count();i++)
    {
        strList << m_pcbDictionary->itemText(i);
    }

    return strList.join(",");
}



void SAnaly2::DelDictionary()
{
    m_pcbDictionary->removeItem(0);
    qDebug() << getUserDictList();
}

bool SAnaly2::isSortMorphereDateChecked()
{
    return m_rbMorphereDate->isChecked();
}

bool SAnaly2::isSortDateMorphereChecked()
{
    return m_rbDateMorphere->isChecked();
}

SAnaly2::~SAnaly2()
{
}

void SAnaly2::MorphereListAdd()
{
    QList<QListWidgetItem *> listitem = m_plwMorphereList->selectedItems();

    foreach(QListWidgetItem *item, listitem)
    {
        for(int i = 0; i < m_plwMorphereAdd->count();i++)
        {
            if(item->data(Qt::UserRole) == m_plwMorphereAdd->item(i)->data(Qt::UserRole))
                m_plwMorphereAdd->item(i)->setHidden(false);
        }
    }
}

void SAnaly2::MorphereListDel()
{
    for(int i = m_plwMorphereAdd->count() - 1; i >= 0 ;i--)
    {
        if(m_plwMorphereAdd->item(i)->isSelected())
        {
            m_plwMorphereAdd->item(i)->setHidden(true);
        }
    }
}

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

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

void SAnaly2::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);
    }
}

void SAnaly2::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;

    m_TotalResult.clear();
    m_mapViewResult.clear();

    //qDebug() << "clear is complete";

    QTextStream in(&file);

    while(!in.atEnd())
    {
        QString strLine = in.readLine();
        strLine = strLine.replace("\"","");
        //qDebug() << strLine;
        QStringList strListLine = strLine.split(",");

        if(strListLine.size() != 4)
            continue;

        //qDebug() << strListLine.at(4).trimmed().toInt();

        QString strKey = strListLine.at(0).trimmed() + "~!@" + strListLine.at(1).trimmed() + "~!@" + strListLine.at(2).trimmed();
        m_TotalResult.insert(strKey, strListLine.at(3).trimmed().toInt());
    }

    file.close();

    for(QMap<QString, int>::iterator iterPos = m_TotalResult.begin(); iterPos != m_TotalResult.end(); iterPos++)
    {
        QString strkey = iterPos.key();
        int count = iterPos.value();
        QStringList strlistKey = strkey.split("~!@");
        QString strDate = strlistKey.at(0);
        QString strMorphere = strlistKey.at(1);
        QString strKeyword = strlistKey.at(2);

        if(m_mapViewResult.contains(strDate))
        {
            if(m_mapViewResult.value(strDate).contains(strMorphere))
            {
                m_mapViewResult[(strDate)][(strMorphere)].insertMulti(count, strKeyword);
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count, strKeyword);
                m_mapViewResult[(strDate)].insert(strMorphere, qLast);
            }
        }
        else
        {
            QMap<int, QString> qLast;
            qLast.insert(count , strKeyword);
            QMap<QString, QMap<int, QString> > qMedium;
            qMedium.insert(strMorphere, qLast);
            m_mapViewResult.insert(strDate, qMedium);
        }
    }
    ViewResult();
}

void SAnaly2::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);


    for (int i = 0; i < m_ptwData->count(); i++)
    {
        m_ptwData->setTabEnabled(i, true);
        QTabWidget* p_childWidget = (QTabWidget*)(m_ptwData->widget(i));

        for (int j = 0; j < p_childWidget->count(); j++)
        {
            p_childWidget->setTabEnabled(j, true);
            STable *stable = (STable *) (p_childWidget->widget(j));
            for (int nCount = 0 ; nCount < stable->rowCount(); nCount++ )
            {

                QString str = stable->item(nCount,0)->text().trimmed() + "," +  stable->item(nCount,1)->text().trimmed();
                out << m_ptwData->tabText(i).trimmed() << "," << p_childWidget->tabText(j).trimmed() << ",";
                out << str << endl;
            }
        }
    }

    file.close();
}
/*
struct SCount
{
    SCount()
    {
        m_str.clear();
        m_nCount = 0;
    }

    SCount(QString _str)
    {
        m_str = _str;
        m_nCount = 1;
    }
    QString m_str;
    int m_nCount;
};
*/

int SAnaly2::getThread()
{
    return m_pcbThread->currentText().toInt();
}

unsigned int SAnaly2::getDateStart()
{
    return m_pdeStart->dateTime().toString("yyyy-MM-dd").replace("-","").trimmed().toInt();
}

unsigned int SAnaly2::getDateEnd()
{
    return m_pdeEnd->dateTime().toString("yyyy-MM-dd").replace("-","").trimmed().toInt();
}

int SAnaly2::getPeriod()
{
    return m_pcbPeriod->currentIndex();
}

QStringList SAnaly2::getMorphereList()
{
    QStringList strList;
    for(int i = 0; i < m_plwMorphereAdd->count();i++)
    {
        if(m_plwMorphereAdd->item(i)->isHidden())
            continue;
        else
        {
            strList << m_plwMorphereAdd->item(i)->data(Qt::UserRole).toString();
        }
    }
    return strList;
}

bool SAnaly2::getDateAll()
{
    if(m_pcbDate->currentIndex() == 0)
        return true;
    else
        return false;
}

QTabWidget* SAnaly2::getQTabWidget()
{
      return m_ptwData;
}


void SAnaly2::MemClear()
{
    for(int i=0;i<16;i++)
    {
        m_HashResult[i].clear();
    }

    m_TotalResult.clear();
    m_mapViewResult.clear();
}

bool SAnaly2::setListMorphere(QStringList& MorphereEN, QStringList& MorphereKO)
{
    QFile fHeader("morpherelist.txt");
    if (!fHeader.open(QIODevice::ReadOnly | QIODevice::Text)) return false;

    QTextStream in(&fHeader);

    QString str = in.readLine();

    if(str.at(0) == '#')
    {
    }
    else
    {
        qDebug() << "The wrong file is read";
        return false;
    }

    while(!in.atEnd())
    {
        str = in.readLine();
        QStringList strList = str.trimmed().split("@",QString::SkipEmptyParts);
        if(strList.isEmpty())
            break;
        if(strList.size() < 2)
            return false;
        MorphereEN << strList.at(0).trimmed().replace("\"","").trimmed();
        MorphereKO << strList.at(1).trimmed().replace("\"","").trimmed();
    }

    return true;
}


void SAnaly2::RawFileExport()
{
    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);

    /*
    out << "#Head#,";
    for (int nCount = 0;nCount < pCurrent->columnCount() ;nCount++ )
        out << pCurrent->horizontalHeaderItem(nCount)->text() << ",";

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

    for( QMap<QString,QMap<QString,QMap<int, QString> > >::iterator iterPos = m_mapViewResult.begin(); iterPos != m_mapViewResult.end(); iterPos++)
    {
        for(QMap<QString, QMap<int, QString> >::iterator iterPos2 = iterPos.value().begin(); iterPos2 != iterPos.value().end(); iterPos2++)
        {
            QMapIterator<int, QString> i(m_mapViewResult[iterPos.key()][iterPos2.key()]);
            i.toBack();
            while(i.hasPrevious())
            {
                i.previous();
                out << "\"" << iterPos.key() << "\"" << ",";
                out << "\"" << iterPos2.key() << "\"" << ",";
                out << "\"" << i.value() << "\"" << ",";
                out << "\"" << i.key() << "\"" << "\n";
            }
        }
    }

    file.close();
}


void SAnaly2::setWidget(Widget *widget)
{
    m_pwidget = widget;
}

void SAnaly2::ExecThread(int _setBodyTitle)
{
    int nCount = 0;
    m_pThread = new KeywordThread*[getThread()];
    for(int i=0;i<getThread();i++)
    {
        m_pThread[i] = new KeywordThread(mutex, i, nCount);
        m_pThread[i]->setParametersfromWidget(this,0);
        m_pThread[i]->setWidget(m_pwidget);
        m_pThread[i]->setPosBody(m_pwidget->getBodyPosition());
        m_pThread[i]->setPosDate(m_pwidget->getDatePosition());
        m_pThread[i]->setPosTitle(m_pwidget->getTitlePosition());
        m_pThread[i]->setPosPlatformTitle(m_pwidget->getPlatformTitlePosition());
        m_pThread[i]->setTitleBody(_setBodyTitle);
        m_pThread[i]->setCenterKeyword(this->m_pleCKeyword->text().trimmed());
    }
    for(int i=0;i<getThread();i++)
    {
        m_pThread[i]->start();
    }
    for(int i=0;i<getThread();i++)
    {
        m_pThread[i]->wait();
    }

    for(int i=0;i<getThread();i++)
    {
        delete m_pThread[i];
    }
    delete[] m_pThread;
}

void SAnaly2::EmergeThreadResult()
{
    for(int i=0;i<getThread();i++)
    {
        for(QHash<QString, int>::iterator iterPos = m_HashResult[i].begin(); iterPos != m_HashResult[i].end();iterPos++)
        {
            if(m_TotalResult.contains(iterPos.key()))
            {
                m_TotalResult[iterPos.key()] += iterPos.value();
            }
            else
            {
                m_TotalResult.insert(iterPos.key(), iterPos.value());
            }
        }
        m_HashResult[i].clear();
    }
}

void SAnaly2::SortViewResult()
{

    if(isSortDateMorphereChecked())
    {
        for(QMap<QString, int>::iterator iterPos = m_TotalResult.begin(); iterPos != m_TotalResult.end(); iterPos++)
        {
            QString strkey = iterPos.key();
            int count = iterPos.value();
            QStringList strlistKey = strkey.split("~!@");
            QString strDate = strlistKey.at(0);
            QString strMorphere = strlistKey.at(1);
            QString strKeyword = strlistKey.at(2);

            if(m_mapViewResult.contains(strDate))
            {
                if(m_mapViewResult.value(strDate).contains(strMorphere))
                {
                    m_mapViewResult[(strDate)][(strMorphere)].insertMulti(count, strKeyword);
                }
                else
                {
                    QMap<int, QString> qLast;
                    qLast.insert(count, strKeyword);
                    m_mapViewResult[(strDate)].insert(strMorphere, qLast);
                }
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count , strKeyword);
                QMap<QString, QMap<int, QString> > qMedium;
                qMedium.insert(strMorphere, qLast);
                m_mapViewResult.insert(strDate, qMedium);
            }
        }
    }
    else
    {
        for(QMap<QString, int>::iterator iterPos = m_TotalResult.begin(); iterPos != m_TotalResult.end(); iterPos++)
        {
            QString strkey = iterPos.key();
            int count = iterPos.value();
            QStringList strlistKey = strkey.split("~!@");
            QString strDate = strlistKey.at(0);
            QString strMorphere = strlistKey.at(1);
            QString strKeyword = strlistKey.at(2);

            if(m_mapViewResult.contains(strMorphere))
            {
                if(m_mapViewResult.value(strMorphere).contains(strDate))
                {
                    m_mapViewResult[(strMorphere)][(strDate)].insertMulti(count, strKeyword);
                }
                else
                {
                    QMap<int, QString> qLast;
                    qLast.insert(count, strKeyword);
                    m_mapViewResult[(strMorphere)].insert(strDate, qLast);
                }
            }
            else
            {
                QMap<int, QString> qLast;
                qLast.insert(count , strKeyword);
                QMap<QString, QMap<int, QString> > qMedium;
                qMedium.insert(strDate, qLast);
                m_mapViewResult.insert(strMorphere, qMedium);
            }
        }
    }
}


void SAnaly2::ViewResult()
{

    foreach(STable* ptable, m_lTable)
    {
        ptable->clear();
        delete ptable;
    }
    m_lTable.clear();

    foreach(QTabWidget* pwidget, m_lTabWidget)
    {
        pwidget->clear();
        delete pwidget;
    }
    m_lTabWidget.clear();


    m_ptwTable = getQTabWidget();
    m_ptwTable->clear();

    for( QMap<QString,QMap<QString,QMap<int, QString> > >::iterator iterPos = m_mapViewResult.begin(); iterPos != m_mapViewResult.end(); iterPos++)
    {
        QTabWidget* temp = new QTabWidget;
        for(QMap<QString, QMap<int, QString> >::iterator iterPos2 = iterPos.value().begin(); iterPos2 != iterPos.value().end(); iterPos2++)
        {
            int ncRow = 0;

            STable *pNew = new STable;
            pNew->setColumnCount(2);
            pNew->setRowCount(m_mapViewResult[iterPos.key()][iterPos2.key()].size());
            pNew->setHorizontalHeaderItem(0 ,new QTableWidgetItem("Keyword"));
            pNew->setHorizontalHeaderItem(1 ,new QTableWidgetItem("Count"));

            QMapIterator<int, QString> i(m_mapViewResult[iterPos.key()][iterPos2.key()]);
            i.toBack();
            while(i.hasPrevious())
            {
                i.previous();
                pNew->setItem(ncRow,0,new QTableWidgetItem(QString(i.value())));
                pNew->setItem(ncRow,1,new QTableWidgetItem(QString::number(i.key())));
                ncRow++;
            }
            temp->addTab(pNew, iterPos2.key());
            m_lTable << pNew;
        }
        m_ptwTable->addTab(temp, iterPos.key());
        m_lTabWidget << temp;
    }
}

void SAnaly2::Exec(int setBodyTitle)
{
    QString strCKeyword = m_pleCKeyword->text().trimmed();
    if(strCKeyword.isEmpty())
        return;

    MemClear();
    ExecThread(setBodyTitle);
    EmergeThreadResult();
    SortViewResult();
    ViewResult();
}
