#include <QtAlgorithms>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QVariant>
#include <QSqlError>
#include <QDebug>
#include <QDate>
#include <QDateTime>
#include "sinfluencer.h"

void SInfluencer::setInitiaizer(SInitializer &_initializer)
{
    m_pSInitializer = &_initializer;
    m_SBodyInfluencerMap.setInitiaizer(_initializer);
    m_SReplyInfluencerMap.setInitiaizer(_initializer);
    m_SStatsInfBloggerBuzzbyday.setInitiaizer(_initializer);
    m_SStatsInfBloggerRank.setInitiaizer(_initializer);
    m_STInfluencer.setInitiaizer(_initializer);
}

bool SInfluencer::uploadData(int _companyNum)
{
    m_pSInitializer->insertLog("Start upload influencer");

    QSqlDatabase dbWeb = m_pSInitializer->getDatabase(SDBManager::E_DATABASE_WEB);
    m_pSInitializer->updateWebDBInfoState(dbWeb, _companyNum, "Influence (Start)");
    if (!m_SBodyInfluencerMap.uploadData(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to upload influencer body map");
        return false;
    }
    if (!m_SReplyInfluencerMap.uploadData(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to upload influencer reply map");
        return false;
    }
    if (!m_SStatsInfBloggerBuzzbyday.uploadData(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to upload stats_inf_blogger_buzzbyday");
        return false;
    }
    if (!m_SStatsInfBloggerRank.uploadData(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to upload stats_inf_blogger_rank");
        return false;
    }
    if (!m_STInfluencer.uploadData(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to upload influencer");
        return false;
    }
    m_pSInitializer->insertLog("End upload influencer");
    m_pSInitializer->updateWebDBInfoState(dbWeb, _companyNum, "Influence (Finish)");

    return true;
}

bool SInfluencer::changeTable(int _companyNum)
{
    m_pSInitializer->insertLog("Start table change influencer");
    QSqlDatabase dbWeb = m_pSInitializer->getDatabase(SDBManager::E_DATABASE_WEB);
    if (!m_SBodyInfluencerMap.changeTable(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to change influencer body map");
        return false;
    }
    if (!m_SReplyInfluencerMap.changeTable(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to change influencer reply map");
        return false;
    }
    if (!m_STInfluencer.changeTable(dbWeb, _companyNum))
    {
        m_pSInitializer->insertLog("Fail to change influencer");
        return false;
    }

    return true;
}

bool SInfluencer::makeCategory(SDatagroup &_datagroup, int _nCategory, const QList<SInitializer::stFilter> &_listFilter)
{
    QVector<QStringList> vecData[SInitializer::E_ARTICLE_MAX];
    bool bFiltered[SInitializer::E_ARTICLE_MAX];

    for (int i = 0; i < SInitializer::E_ARTICLE_MAX; i++)
        bFiltered[i] = false;
    _datagroup.copyData(vecData);
    foreach (SInitializer::stFilter filter, _listFilter)
    {
        switch(filter.m_nType)
        {
        case E_FILTER_TYPE_DATE://Date
            m_SFilterAlgorithm.FilterDate(vecData, bFiltered, filter.m_vData.toString(),
                                          m_pSInitializer->getColumnIntArray()[SInitializer::E_DATA_article_date]);

            break;
        case E_FILTER_TYPE_SEARCH:
            m_SFilterAlgorithm.FilterSearch(vecData, bFiltered, filter.m_vData.toString());

            break;
        case E_FILTER_TYPE_LENGTH:
            m_SFilterAlgorithm.FilterLength(vecData, bFiltered, filter.m_vData.toString());
            break;
        case E_FILTER_TYPE_REPLACE:
            m_SFilterAlgorithm.FilterReplace(vecData, bFiltered, filter.m_vData.toString());
            break;
        case E_FILTER_TYPE_COUNTER:
            m_SFilterAlgorithm.FilterCounter(vecData, bFiltered, filter.m_vData.toString());
            break;
        }
    }
    stReal streal;
    m_pSInitializer->insertLog(QString("CategoryNum:") + QString::number(_nCategory) + ",(" +
                               QString::number(vecData[SInitializer::E_ARTICLE_BODY].size()) + '/' + QString::number(vecData[SInitializer::E_ARTICLE_REPLY].size()) + ")" + "(Body/Reply)" );
    const int *anColumn = m_pSInitializer->getColumnIntArray();
    if (bFiltered[SInitializer::E_ARTICLE_BODY])
    {
        foreach (const QStringList& strlist, vecData[SInitializer::E_ARTICLE_BODY])
        {
            streal.m_setRealAllUrl.insert(strlist[anColumn[SInitializer::E_DATA_article_url]].trimmed());
            streal.m_setRealBodyUrl.insert(strlist[anColumn[SInitializer::E_DATA_article_url]].trimmed());
            _datagroup.addRealUrl(strlist[anColumn[SInitializer::E_DATA_article_url]].trimmed());
        }
    }

    if (bFiltered[SInitializer::E_ARTICLE_REPLY])
    {
        foreach (const QStringList& strlist, vecData[SInitializer::E_ARTICLE_REPLY])
        {
            streal.m_setRealAllUrl.insert(strlist[anColumn[SInitializer::E_DATA_article_url]].trimmed());
            streal.m_mapRealReplyUniqueUrl.insertMulti(strlist[anColumn[SInitializer::E_DATA_article_url]].trimmed(),
                    strlist[anColumn[SInitializer::E_DATA_article_order]].trimmed().toInt());
            _datagroup.addRealUrl(strlist[anColumn[SInitializer::E_DATA_article_url]].trimmed());
        }
    }

    m_mapCategory.insert(_nCategory, streal);
    return true;
}

bool SInfluencer::makeOverallCategory(int _categoryNum)
{
    if (m_mapCategory.size() < 1)
        return true;

    stReal streal;
    for (QMap<int, stReal>::iterator iterPos = m_mapCategory.begin(); iterPos != m_mapCategory.end(); iterPos++ )
    {
        stReal& val = iterPos.value();
        foreach (const QString& _strurl, val.m_setRealBodyUrl )
            streal.m_setRealBodyUrl.insert(_strurl);
        foreach (const QString& _strurl, val.m_setRealAllUrl )
            streal.m_setRealAllUrl.insert(_strurl);

        for (QMap<QString, int>::iterator iterPos1 = val.m_mapRealReplyUniqueUrl.begin(); iterPos1 != val.m_mapRealReplyUniqueUrl.end();
             iterPos1++)
        {
            streal.m_mapRealReplyUniqueUrl.insertMulti(iterPos1.key(), iterPos1.value());
        }
    }

    m_mapCategory.insert(_categoryNum, streal);
    return true;

}

bool SInfluencer::makeTable(SDatagroup &_datagroup)
{
    if (m_mapCategory.size() > 1)
    {
        m_pSInitializer->insertLog("Make influencer tables");
        m_pSInitializer->insertLog("Make influencer body tables");
        m_SBodyInfluencerMap.makeTable(_datagroup, m_mapCategory);
        m_pSInitializer->insertLog("Make influencer reply tables");
        m_SReplyInfluencerMap.makeTable(_datagroup, m_mapCategory);
        m_pSInitializer->insertLog("Make influencer stats_inf_blogger_buzzy tables");
        m_SStatsInfBloggerBuzzbyday.makeTable(_datagroup, m_mapCategory);
        m_pSInitializer->insertLog("Make influencer stats_inf_blogger_rank table");
        m_SStatsInfBloggerRank.makeTable(_datagroup, m_mapCategory);
        m_pSInitializer->insertLog("Make influencer influencer");
        m_STInfluencer.makeTable(_datagroup, m_mapCategory);
    }
    return true;
}

void SInfluencer::STInfluencer::makeTable(SDatagroup &_datagroup, const QMap<int, stReal>& _mapCategory)
{
    const QMap<QString, QStringList>* mapBody = _datagroup.getmapBody();
    const QMap<QString, QMap<int, QStringList> >* mapReply = _datagroup.getmapReply();
    const QStringList* orderedUrl = _datagroup.getOrderedUrl();

    const int* anColumn = m_pSInitializer->getColumnIntArray();

    for (QMap<int, stReal>::const_iterator iterPos = _mapCategory.constBegin(); iterPos != _mapCategory.constEnd(); iterPos++)
    {
        QMap<SDatagroup::stProfileurlKey, stInfluencer> mapRank;
        const stReal& streal = iterPos.value();
        foreach (const QString& _url, *orderedUrl)
        {
            if (streal.m_setRealBodyUrl.contains(_url))
            {
                SDatagroup::stProfileurlKey stprofileurlkey(m_pSInitializer->getPlatformForm((*mapBody)[_url][anColumn[SInitializer::E_DATA_platform_form]].trimmed()),
                        (*mapBody)[_url][anColumn[SInitializer::E_DATA_article_id]].trimmed());

                if (!mapRank.contains(stprofileurlkey))
                {
                    mapRank.insert(stprofileurlkey, stInfluencer());
                    mapRank[stprofileurlkey].id_id = _datagroup.getstBody(_url)->id_id;
                    mapRank[stprofileurlkey].id_num = _datagroup.getstBody(_url)->id_num;
                    mapRank[stprofileurlkey].nickname_num = _datagroup.getstBody(_url)->nickname_num;
                    mapRank[stprofileurlkey].community_num = _datagroup.getstBody(_url)->community_num;
                    mapRank[stprofileurlkey].profile = (*(_datagroup.getmapBody(stprofileurlkey)))[anColumn[SInitializer::E_DATA_article_profile]].trimmed();
                    mapRank[stprofileurlkey].profileurl = (*(_datagroup.getmapBody(stprofileurlkey)))[anColumn[SInitializer::E_DATA_article_profileurl]].trimmed();
                    mapRank[stprofileurlkey].category_num = iterPos.key();
                    mapRank[stprofileurlkey].community_title = _datagroup.getstCommunity(*(_datagroup.getmapBody(stprofileurlkey)))->title;
                    mapRank[stprofileurlkey].community_url = _datagroup.getstCommunity(*(_datagroup.getmapBody(stprofileurlkey)))->url;
                    mapRank[stprofileurlkey].community_id = _datagroup.getstCommunity(*(_datagroup.getmapBody(stprofileurlkey)))->id;
                    mapRank[stprofileurlkey].nickname_nickname = _datagroup.getstBody(_url)->nickname_nickname;
                    mapRank[stprofileurlkey].nickname_exnickname = _datagroup.getstBody(_url)->nickname_exnickname;
                    mapRank[stprofileurlkey].platformname_num = _datagroup.getstBody(_url)->platformname_num;
                    mapRank[stprofileurlkey].platformname_name = _datagroup.getstBody(_url)->platformname_name;
                }
                mapRank[stprofileurlkey].bodycount++;

                if ((*mapReply).contains(_url))
                {
                    for (QMap<int, QStringList>::const_iterator iterPos1 = (*mapReply)[_url].constBegin(); iterPos1 != (*mapReply)[_url].constEnd(); iterPos1++)
                    {
                        //if ((iterPos1.value()[anColumn[SInitializer::E_DATA_article_id]].trimmed() != (*mapBody)[_url][anColumn[SInitializer::E_DATA_article_id]].trimmed()))
                            mapRank[stprofileurlkey].replycount++;
                    }
                }
            }
        }
        for (QMap<SDatagroup::stProfileurlKey, stInfluencer>::iterator iterPos1 = mapRank.begin(); iterPos1 != mapRank.end(); iterPos1++)
        {
            stInfluencer &val = iterPos1.value();
            val.influencervalue = val.bodycount * m_pSInitializer->getInfluencerParam(0) + val.replycount * m_pSInitializer->getInfluencerParam(1);
        }
        QList<stInfluencer> listmap = mapRank.values();
        qSort(listmap.begin(), listmap.end(), isGreaterInfluencerValue());
        int rank = 1;
        for (QList<stInfluencer>::iterator iterPos1 = listmap.begin(); iterPos1 != listmap.end(); iterPos1++)
        {
            iterPos1->rank = rank++;
        }
        m_listMap.append(listmap);
    }
}

/*
bool SInfluencer::STInfluencer::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "delete from influencer where company_num = " + QString::number(_nCompany);
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into influencer (rank,company_num,id_num,nickname_num,community_num,bodycount,replycount,influencervalue,profile,profileurl,id_id)"
               " VALUES (:RANK,:COMPANY_NUM,:ID_NUM,:NICKNAME_NUM,:COMMUNITY_NUM,:BODY_COUNT,:REPLY_COUNT,:INPL,:PROFILE,:PROFILE_URL,:ID_ID)";

    query.clear();
    query.prepare(strQuery.toUtf8());

    foreach (const stInfluencer& stinfluencer, m_listMap)
    {
        query.bindValue(":RANK", stinfluencer.rank);
        query.bindValue(":COMPANY_NUM", _nCompany);
        query.bindValue(":ID_NUM", stinfluencer.id_num);
        query.bindValue(":NICKNAME_NUM", stinfluencer.nickname_num);
        query.bindValue(":COMMUNITY_NUM", stinfluencer.community_num);
        query.bindValue(":BODY_COUNT", stinfluencer.bodycount);
        query.bindValue(":REPLY_COUNT", stinfluencer.replycount);
        query.bindValue(":ID_ID", stinfluencer.id_id);
        query.bindValue(":INPL", QString::number(stinfluencer.influencervalue, 'g', 3));
        //query.bindValue(":PROFILE", ((stinfluencer.profile.trimmed().isEmpty())? " " : sqlString(stinfluencer.profile).trimmed().replace(QChar(160), "")));
        //query.bindValue(":PROFILE_URL", ((stinfluencer.profileurl.trimmed().isEmpty())? " ", stinfluencer.profileurl.trimmed()));
        query.bindValue(":PROFILE", sqlString(stinfluencer.profile).trimmed().replace(QChar(160), ""));
        query.bindValue(":PROFILE_URL", stinfluencer.profileurl.trimmed());
        if (query.exec() == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }

    strQuery = "update dbinfo set influencercount = " + QString::number(m_listMap.size()) + " where company_num = "
            + QString::number(_nCompany);
    query.exec(strQuery);

    return true;
}
*/

bool SInfluencer::STInfluencer::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "delete from influencer_" + QString::number(_nCompany) + "_update";
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into influencer_" + QString::number(_nCompany) +
            "_update (rank,category_num,id_num,nickname_num,community_num,bodycount,replycount,influencervalue,profile,profileurl,id_id,"
            "community_title,community_url,community_id,nickname_nickname,nickname_exnickname,platformname_num,platformname_name) VALUES (";

    query.clear();

    foreach (const stInfluencer& stinfluencer, m_listMap)
    {
        QString str = strQuery;
        str += QString::number(stinfluencer.rank) + ",";
        str += QString::number(stinfluencer.category_num) + ",";
        str += QString::number(stinfluencer.id_num) + ",";
        str += QString::number(stinfluencer.nickname_num) + ",";
        str += QString::number(stinfluencer.community_num) + ",";
        str += QString::number(stinfluencer.bodycount) + ",";
        str += QString::number(stinfluencer.replycount) + ",";
        str += QString::number(stinfluencer.influencervalue, 'g', 3) + ",";
        str += "'" + sqlString(stinfluencer.profile).trimmed().replace(QChar(160), "") + "',";
        str += "'" + stinfluencer.profileurl.trimmed() + "',";
        str += "'" + sqlString(stinfluencer.id_id) + "',";
        str += "'" + sqlString(stinfluencer.community_title) + "',";
        str += "'" + stinfluencer.community_url + "',";
        str += "'" + stinfluencer.community_id + "',";
        str += "'" + sqlString(stinfluencer.nickname_nickname) + "',";
        str += "'" + sqlString(stinfluencer.nickname_exnickname) + "',";
        str += QString::number(stinfluencer.platformname_num) + ",";
        str += "'" + stinfluencer.platformname_name + "')";

        if (query.exec(str.toUtf8()) == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }

    strQuery = "update dbinfo set influencercount = " + QString::number(m_listMap.size()) + " where company_num = "
            + QString::number(_nCompany);
    query.exec(strQuery);

    return true;
}

bool SInfluencer::STInfluencer::changeTable(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery;
    QSqlQuery query(_db);
    strQuery = "RENAME TABLE ";
    strQuery += "influencer_" + QString::number(_nCompany) + " TO " + "influencer_" + QString::number(_nCompany) + "_temp" + ",";
    strQuery += "influencer_" + QString::number(_nCompany) + "_update" + " TO " + "influencer_" + QString::number(_nCompany) + ",";
    strQuery += "influencer_" + QString::number(_nCompany) + "_temp" + " TO " + "influencer_" + QString::number(_nCompany) + "_update";
    if (!query.exec(strQuery.toUtf8()))
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    return true;
}

void SInfluencer::SStatsInfBloggerRank::makeTable(SDatagroup &_datagroup, const QMap<int, stReal>& _mapCategory)
{
    const QMap<QString, QStringList>* mapBody = _datagroup.getmapBody();
    const QMap<QString, QMap<int, QStringList> >* mapReply = _datagroup.getmapReply();
    const int* anColumn = m_pSInitializer->getColumnIntArray();
    const int RANK = 10;


    for (QMap<int, stReal>::const_iterator iterPos = _mapCategory.constBegin(); iterPos != _mapCategory.constEnd(); iterPos++)
    {
        const stReal& streal = iterPos.value();
        QMap<SDatagroup::stProfileurlKey, stStatsInfBloggerRank> mapRank;

        foreach (const QString& _url, streal.m_setRealBodyUrl)
        {
            SDatagroup::stProfileurlKey stprofileurlkey(m_pSInitializer->getPlatformForm((*mapBody)[_url][anColumn[SInitializer::E_DATA_platform_form]].trimmed()),
                    (*mapBody)[_url][anColumn[SInitializer::E_DATA_article_id]].trimmed());

            if (!mapRank.contains(stprofileurlkey))
            {
                mapRank.insert(stprofileurlkey, stStatsInfBloggerRank());
                mapRank[stprofileurlkey].id_id = (*mapBody)[_url][anColumn[SInitializer::E_DATA_article_id]].trimmed();
                mapRank[stprofileurlkey].nickname_nickname = (*mapBody)[_url][anColumn[SInitializer::E_DATA_article_nickname]].trimmed();
            }

            mapRank[stprofileurlkey].bodycount++;

            if ((*mapReply).contains(_url))
            {
                for (QMap<int, QStringList>::const_iterator iterPos1 = (*mapReply)[_url].constBegin(); iterPos1 != (*mapReply)[_url].constEnd(); iterPos1++)
                {
                    //if ((iterPos1.value()[anColumn[SInitializer::E_DATA_article_id]].trimmed() != (*mapBody)[_url][anColumn[SInitializer::E_DATA_article_id]].trimmed()))
                        mapRank[stprofileurlkey].replycount++;
                }
            }
        }

        for (QMap<SDatagroup::stProfileurlKey, stStatsInfBloggerRank>::iterator iterPos = mapRank.begin(); iterPos != mapRank.end(); iterPos++)
        {
            stStatsInfBloggerRank &val = iterPos.value();
            val.influencevalue = val.bodycount * m_pSInitializer->getInfluencerParam(0) + val.replycount * m_pSInitializer->getInfluencerParam(1);
        }

        QList<stStatsInfBloggerRank> listMap = mapRank.values();

        qSort(listMap.begin(), listMap.end(), isGreaterInfluencerValue());
        // influencevalue
        for(int i = 0; i < RANK && i < listMap.size(); i++)
        {
            listMap[i].rank = i + 1;
            listMap[i].subject = "influencevalue";
            m_listMap.append(listMap.at(i));
            //qDebug() << listMap[i].id_id;
        }

        qSort(listMap.begin(), listMap.end(), isGreaterBodyCount());
        // influencevalue
        for(int i = 0; i < RANK && i < listMap.size(); i++)
        {
            listMap[i].rank = i + 1;
            listMap[i].subject = "bodycount";
            m_listMap.append(listMap.at(i));
            //qDebug() << listMap[i].id_id;
        }

        qSort(listMap.begin(), listMap.end(), isGreaterReplyCount());
        // influencevalue
        for(int i = 0; i < RANK && i < listMap.size(); i++)
        {
            listMap[i].rank = i + 1;
            listMap[i].subject = "replycount";
            m_listMap.append(listMap.at(i));
            //qDebug() << listMap[i].id_id;
        }
        listMap.clear();
    }
}

/*
bool SInfluencer::SStatsInfBloggerRank::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    //_db.transaction();
    QString strQuery = "delete from stats_inf_blogger_rank where company_num = " + QString::number(_nCompany);
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    //_db.commit();
    //_db.transaction();
    strQuery = "insert into stats_inf_blogger_rank(rank,id_id,nickname_nickname,bodycount,replycount,influencevalue,subject,company_num)"
               " VALUES (:rank,:id_id,:nickname_nickname,:bodycount,:replycount,:influencevalue,:subject,:company_num)";
    query.clear();
    query.prepare(strQuery.toUtf8());

    foreach (const stStatsInfBloggerRank& ststats, m_listMap)
    {
        query.bindValue(":rank", ststats.rank);
        query.bindValue(":id_id", ststats.id_id);
        query.bindValue(":company_num", _nCompany);
        query.bindValue(":nickname_nickname", ststats.nickname_nickname);
        query.bindValue(":bodycount", ststats.bodycount);
        query.bindValue(":replycount", ststats.replycount);
        query.bindValue(":influencevalue", QString::number(ststats.influencevalue, 'g', 3));
        query.bindValue(":subject", ststats.subject);
        if (query.exec() == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    //_db.commit();
    return true;
}
*/

bool SInfluencer::SStatsInfBloggerRank::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    //_db.transaction();
    QString strQuery = "delete from stats_inf_blogger_rank where company_num = " + QString::number(_nCompany);
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    //_db.commit();
    //_db.transaction();
    strQuery = "insert into stats_inf_blogger_rank(rank,id_id,nickname_nickname,bodycount,replycount,influencevalue,subject,company_num)"
               " VALUES (";
    query.clear();

    foreach (const stStatsInfBloggerRank& ststats, m_listMap)
    {
        QString str = strQuery;
        str += QString::number(ststats.rank) + ",";
        str += "'" + sqlString(ststats.id_id) + "',";
        str += "'" + sqlString(ststats.nickname_nickname) + "',";
        str += QString::number(ststats.bodycount) + ",";
        str += QString::number(ststats.replycount) + ",";
        str += QString::number(ststats.influencevalue, 'g', 3) + ",";
        str += "'" + ststats.subject + "',";
        str += QString::number(_nCompany) + ")";
        if (query.exec(str.toUtf8()) == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    //_db.commit();
    return true;
}


void SInfluencer::SStatsInfBloggerBuzzbyday::makeTable(SDatagroup &_datagroup, const QMap<int, stReal> &_mapCategory)
{
    const QMap<QString, QStringList>* mapBody = _datagroup.getmapBody();
    const QMap<QString, QMap<int, QStringList> >* mapReply = _datagroup.getmapReply();
    const int* anColumn = m_pSInitializer->getColumnIntArray();
    QDate dateStart(2100,1,1),dateEnd(2000,1,1);

    QMap<QDate, stInfluenceBuzz> map;

    for (QMap<int, stReal>::const_iterator iterPos = _mapCategory.constBegin(); iterPos != _mapCategory.constEnd(); iterPos++)
    {
        const stReal& streal = iterPos.value();
        foreach (const QString& _url, streal.m_setRealBodyUrl)
        {
            QDate date = QDateTime::fromString((*mapBody)[_url][anColumn[SInitializer::E_DATA_article_date]].trimmed().replace("T", " "), "yyyy-MM-dd HH:mm:ss").date();
            dateStart = (date < dateStart ) ? date : dateStart;
            dateEnd = (date > dateEnd ) ? date : dateEnd;
            if (!map.contains(date))
                map.insert(date, stInfluenceBuzz());
            map[date].bodycount++;
            map[date].idcount.insert((*mapBody)[_url][anColumn[SInitializer::E_DATA_article_id]].trimmed());
        }
        if (streal.m_mapRealReplyUniqueUrl.size() > 0)
        {
            for (QMap<QString, int>::const_iterator iterPos1 = streal.m_mapRealReplyUniqueUrl.constBegin(); iterPos1 != streal.m_mapRealReplyUniqueUrl.constEnd(); iterPos1++)
            {
                QDate date = QDateTime::fromString((*mapReply)[iterPos1.key()][iterPos1.value()][anColumn[SInitializer::E_DATA_article_date]].trimmed().replace("T", " "),
                            "yyyy-MM-dd HH:mm:ss").date();
                dateStart = (date < dateStart ) ? date : dateStart;
                dateEnd = (date > dateEnd ) ? date : dateEnd;
                if (!map.contains(date))
                    map.insert(date, stInfluenceBuzz());
                map[date].replycount++;
            }
        }
        else
        {
            foreach (const QString& _url, streal.m_setRealBodyUrl)
            {
                for (QMap<int, QStringList>::const_iterator iterPos1 = mapReply->value(_url).constBegin(); iterPos1 != mapReply->value(_url).constEnd(); iterPos1++)
                {
                    QDate date = QDateTime::fromString((*iterPos1)[anColumn[SInitializer::E_DATA_article_date]].trimmed().replace("T", " "),
                                "yyyy-MM-dd HH:mm:ss").date();
                    dateStart = (date < dateStart ) ? date : dateStart;
                    dateEnd = (date > dateEnd ) ? date : dateEnd;
                    if (!map.contains(date))
                        map.insert(date, stInfluenceBuzz());
                    map[date].replycount++;
                }
            }
        }
    }

    for (QDate date = dateStart; date <= dateEnd; date = date.addDays(1))
    {
        if (!map.contains(date))
            map.insert(date, stInfluenceBuzz());
        stStatsInfBloggerBuzzbyday ststats;

        ststats.date = date.toString("yyyy-MM-dd");
        ststats.formateddate = date.toString("yyyyMMdd").toInt();
        ststats.bodycount = map[date].bodycount;
        ststats.idcount = map[date].idcount.size();
        ststats.replycount = map[date].replycount;
        m_listMap.append(ststats);
    }
}
/*
bool SInfluencer::SStatsInfBloggerBuzzbyday::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    //_db.transaction();
    QString strQuery = "delete from stats_inf_blogger_buzzbyday where company_num = " + QString::number(_nCompany);
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    //_db.commit();
    //_db.transaction();
    strQuery = "insert into stats_inf_blogger_buzzbyday (company_num,date,formateddate,idcount,bodycount,replycount) "
               "VALUES (:company_num,:date,:formateddate,:idcount,:bodycount,:replycount)";
    query.clear();
    query.prepare(strQuery.toUtf8());

    foreach (const stStatsInfBloggerBuzzbyday& ststats, m_listMap)
    {
        query.bindValue(":company_num", _nCompany);
        query.bindValue(":date", ststats.date);
        query.bindValue(":formateddate", ststats.formateddate);
        query.bindValue(":idcount", ststats.idcount);
        query.bindValue(":bodycount", ststats.bodycount);
        query.bindValue(":replycount", ststats.replycount);

        if (query.exec() == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    //_db.commit();
    return true;
}
*/


bool SInfluencer::SStatsInfBloggerBuzzbyday::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "delete from stats_inf_blogger_buzzbyday where company_num = " + QString::number(_nCompany);
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into stats_inf_blogger_buzzbyday (company_num,date,formateddate,idcount,bodycount,replycount) "
               "VALUES (";
    query.clear();

    foreach (const stStatsInfBloggerBuzzbyday& ststats, m_listMap)
    {
        QString str = strQuery;
        str += QString::number(_nCompany) + ",";
        str += "'" + ststats.date + "',";
        str += QString::number(ststats.formateddate) + ",";
        str += QString::number(ststats.idcount) + ",";
        str += QString::number(ststats.bodycount) + ",";
        str += QString::number(ststats.replycount) + ")";
        if (query.exec(str.toUtf8()) == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    return true;
}


void SInfluencer::SBodyInfluencerMap::makeTable(SDatagroup &_datagroup, const QMap<int, stReal> &_mapCategory)
{
    int num = 0;
    const QStringList* orderedUrl = _datagroup.getOrderedUrl();
    for (QMap<int, stReal>::const_iterator iterPos = _mapCategory.constBegin(); iterPos != _mapCategory.constEnd(); iterPos++)
    {
        const stReal& streal = iterPos.value();
        foreach (const QString& strUrl, *orderedUrl)
        {
            if (streal.m_setRealBodyUrl.contains(strUrl))
            {
                stBodyInfluencerMap stbody;
                stbody.num = num++;
                stbody.body_num = _datagroup.getstBodyNum(strUrl);
                stbody.id_num = _datagroup.getstBody(strUrl)->id_num;
                stbody.category_num = iterPos.key();
                stbody.realin |= REAL_BODY;
                stbody.community_num = _datagroup.getstBody(strUrl)->community_num;
                stbody.body_date = _datagroup.getstBody(strUrl)->date;
                m_listMap.append(stbody);
                _datagroup.addRealBodyCategory(strUrl, iterPos.key());
                if (streal.m_mapRealReplyUniqueUrl.contains(strUrl))
                {
                    stbody.realin |= REAL_REPLY;
                    foreach (int order, streal.m_mapRealReplyUniqueUrl.values(strUrl))
                    {
                        _datagroup.addRealReplyCategory(strUrl, order, iterPos.key());
                    }
                }
            }
        }
    }
}
/*
bool SInfluencer::SBodyInfluencerMap::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "truncate body_influencer_map_" + QString::number(_nCompany) + "_update";

    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into body_influencer_map_" + QString::number(_nCompany) + "_update (num,category_num,id_num,body_num,realin)"
            " values (:num,:category_num,:id_num,:body_num,:realin)";
    query.clear();
    query.prepare(strQuery.toUtf8());

    foreach (const stBodyInfluencerMap& stmap, m_listMap)
    {
        query.bindValue(":num", stmap.num);
        query.bindValue(":category_num", stmap.category_num);
        query.bindValue(":id_num", stmap.id_num);
        query.bindValue(":body_num", stmap.body_num);
        query.bindValue(":realin", stmap.realin);
        if (query.exec() == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    return true;
}
*/


bool SInfluencer::SBodyInfluencerMap::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "truncate body_influencer_map_" + QString::number(_nCompany) + "_update";

    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into body_influencer_map_" + QString::number(_nCompany) + "_update (num,category_num,id_num,body_num,realin,community_num,body_date)"
            " values (";
    query.clear();


    foreach (const stBodyInfluencerMap& stmap, m_listMap)
    {
        QString str = strQuery;
        str += QString::number(stmap.num) + ",";
        str += QString::number(stmap.category_num) + ",";
        str += QString::number(stmap.id_num) + ",";
        str += QString::number(stmap.body_num) + ",";
        str += QString::number(stmap.realin) + ",";
        str += QString::number(stmap.community_num) + ",";
        str += "'" + stmap.body_date + "')";

        if (query.exec(str.toUtf8()) == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    return true;
}




void SInfluencer::SReplyInfluencerMap::makeTable(SDatagroup &_datagroup, const QMap<int, stReal> &_mapCategory)
{
    int num = 0;
    const QMap<QString, QMap<int, QStringList> >* mapReply = _datagroup.getmapReply();

    for (QMap<int, stReal>::const_iterator iterPos = _mapCategory.constBegin(); iterPos != _mapCategory.constEnd(); iterPos++)
    {
        const stReal& streal = iterPos.value();

        if (streal.m_mapRealReplyUniqueUrl.size() > 0)
        {
            for (QMap<QString, int>::const_iterator iterPos1 = streal.m_mapRealReplyUniqueUrl.constBegin(); iterPos1 != streal.m_mapRealReplyUniqueUrl.end(); iterPos1++)
            {
                stReplyInfluencerMap streply;
                streply.num = num++;
                streply.body_num = _datagroup.getstBodyNum(iterPos1.key());
                streply.category_num = iterPos.key();
                streply.realin |= REAL_REPLY;
                streply.id_num = _datagroup.getstReply(iterPos1.key(), iterPos1.value())->id_num;
                streply.reply_num = _datagroup.getstReply(iterPos1.key(), iterPos1.value())->num;
                streply.community_num  = _datagroup.getstReply(iterPos1.key(), iterPos1.value())->community_num;
                streply.body_date = _datagroup.getstBody(iterPos1.key())->date;
                m_listMap.append(streply);

                _datagroup.addRealReplyCategory(iterPos1.key(), iterPos1.value(), iterPos.key());
            }
        }
        else
        {
            foreach (const QString& _url, streal.m_setRealBodyUrl)
            {
                for (QMap<int, QStringList>::const_iterator iterPos1 = mapReply->value(_url).constBegin(); iterPos1 != mapReply->value(_url).constEnd(); iterPos1++)
                {
                    stReplyInfluencerMap streply;
                    streply.num = num++;
                    streply.body_num = _datagroup.getstBodyNum(_url);
                    streply.category_num = iterPos.key();
                    streply.realin |= REAL_REPLY;
                    streply.id_num = _datagroup.getstReply(_url, iterPos1.key())->id_num;
                    streply.reply_num = _datagroup.getstReply(_url, iterPos1.key())->num;
                    streply.community_num = _datagroup.getstReply(_url, iterPos1.key())->community_num;
                    streply.body_date = _datagroup.getstBody(_url)->date;
                    _datagroup.addRealReplyCategory(iterPos1.value()[SInitializer::E_DATA_article_url].trimmed(), iterPos1.key(), iterPos.key());
                    m_listMap.append(streply);
                }
            }
        }
    }
}


/*
bool SInfluencer::SReplyInfluencerMap::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "truncate reply_influencer_map_" + QString::number(_nCompany) + "_update";
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into reply_influencer_map_" + QString::number(_nCompany) + "_update (num,category_num,id_num,body_num,reply_num,realin)"
            " values (:num,:category_num,:id_num,:body_num,:reply_num,:realin)";
    query.clear();
    query.prepare(strQuery.toUtf8());

    foreach (const stReplyInfluencerMap& stmap, m_listMap)
    {
        query.bindValue(":num", stmap.num);
        query.bindValue(":category_num", stmap.category_num);
        query.bindValue(":id_num", stmap.id_num);
        query.bindValue(":body_num", stmap.body_num);
        query.bindValue(":realin", stmap.realin);
        query.bindValue(":reply_num", stmap.reply_num);
        if (query.exec() == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    return true;
}
*/

bool SInfluencer::SReplyInfluencerMap::uploadData(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery = "truncate reply_influencer_map_" + QString::number(_nCompany) + "_update";
    QSqlQuery query(_db);
    if (query.exec(strQuery.toUtf8()) == false)
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    strQuery = "insert into reply_influencer_map_" + QString::number(_nCompany) +
            "_update (num,category_num,id_num,body_num,reply_num,realin,community_num,body_date)"
            " values (";
    query.clear();

    foreach (const stReplyInfluencerMap& stmap, m_listMap)
    {
        QString str = strQuery;
        str += QString::number(stmap.num) + ",";
        str += QString::number(stmap.category_num) + ",";
        str += QString::number(stmap.id_num) + ",";
        str += QString::number(stmap.body_num) + ",";
        str += QString::number(stmap.reply_num) + ",";
        str += QString::number(stmap.realin) + ",";
        str += QString::number(stmap.community_num) + ",";
        str += "'" + stmap.body_date + "')";
        if (query.exec(str.toUtf8()) == false)
        {
            m_pSInitializer->insertLog(query.lastQuery());
            m_pSInitializer->insertLog(query.lastError().text());
            return false;
        }
    }
    return true;
}


bool SInfluencer::SBodyInfluencerMap::changeTable(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery;
    QSqlQuery query(_db);
    strQuery = "RENAME TABLE ";
    strQuery += "body_influencer_map_" + QString::number(_nCompany) + " TO " + "body_influencer_map_" + QString::number(_nCompany) + "_temp" + ",";
    strQuery += "body_influencer_map_" + QString::number(_nCompany) + "_update" + " TO " + "body_influencer_map_" + QString::number(_nCompany) + ",";
    strQuery += "body_influencer_map_" + QString::number(_nCompany) + "_temp" + " TO " + "body_influencer_map_" + QString::number(_nCompany) + "_update";
    if (!query.exec(strQuery.toUtf8()))
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    return true;
}


bool SInfluencer::SReplyInfluencerMap::changeTable(QSqlDatabase &_db, const int &_nCompany)
{
    QString strQuery;
    QSqlQuery query(_db);
    strQuery = "RENAME TABLE ";
    strQuery += "reply_influencer_map_" + QString::number(_nCompany) + " TO " + "reply_influencer_map_" + QString::number(_nCompany) + "_temp" + ",";
    strQuery += "reply_influencer_map_" + QString::number(_nCompany) + "_update" + " TO " + "reply_influencer_map_" + QString::number(_nCompany) + ",";
    strQuery += "reply_influencer_map_" + QString::number(_nCompany) + "_temp" + " TO " + "reply_influencer_map_" + QString::number(_nCompany) + "_update";
    if (!query.exec(strQuery.toUtf8()))
    {
        m_pSInitializer->insertLog(query.lastQuery());
        m_pSInitializer->insertLog(query.lastError().text());
        return false;
    }
    return true;
}


