#include "trendmanager.h"
#include "db/xsqlexcute.h"
#include <QDebug>
#include <QDate>

TrendManager::TrendManager()
{
}

TrendManager::~TrendManager()
{
}

void TrendManager::doExcute()
{
    if(toExcuteType() == decode)
    {
        decodeToMysql();
    }
    else if(toExcuteType() == getData)
    {
        getDataFromMysql();
    }
}

void TrendManager::decodeToMysql()
{

//    QString sql = QString("insert into stock_basis (code, name, blemind2,blemind3,listdate) "
//                          "value(':code', ':name', ':blemind2',':blemind3',':listdate') on DUPLICATE key "
//                          "update name = ':name',blemind2=':blemind2',blemind3=':blemind3',listdate=':listdate';");
//    sql.replace(":code",stock.code);
//    sql.replace(":name",stock.name);
//    sql.replace(":blemind2",stock.blemind2);
//    sql.replace(":blemind3",stock.blemind3);
//    sql.replace(":listdate",stock.listDate);
    QList<_trendStocks> d = trendStocksDatas;
    if(!d.isEmpty())
    {
        //插入到数据库
        XSqlExcute* sqlIns = new XSqlExcute;
        sqlIns->openMysql("192.168.0.201","nstocks","admin","1qazse42W3","TrendManager");
        sqlIns->transaction("TrendManager");
        int count = d.count();
        QString sql = "";
        for(int i = 0 ; i < count ; i++)
        {
            sql = QString("insert into stocks_in_trend (code, trade_day, sort,type) "
                                  "value(':code', ':trade_day', :sort,':type') on DUPLICATE key "
                                  "update code = ':code',trade_day=':trade_day',sort=:sort,type=':type';");
            sql.replace(":code",d[i].code);
            sql.replace(":trade_day",d[i].tradeDay);
            sql.replace(":sort",d[i].sort);
            sql.replace(":type",d[i].type);

            qDebug() << sql;
            sqlIns->query(sql,"TrendManager");
        }
//        XSqlExcute::instance()->commit();
        sqlIns->commit("TrendManager");

        //获取板块成分数据
        sql = QString("select b.blemind2 as blemind2 , COUNT(s.code) as count from stocks s, stock_basis b where trade_day = '%1' and s.code = b.code GROUP BY b.blemind2;").arg(getParam("date"));
        QSqlQuery q = sqlIns->query(sql,"TrendManager");
        qDebug() << "TrendManager bleminds : count : " << q.size();
        while (q.next())
        {
            QString blemind2 = q.value("blemind2").toString();
            QString count = q.value("count").toString();
            blemind2StockCounts.insert(blemind2,count);
            qDebug()<< "blemind2: " <<blemind2 << "count: " << count;
        }

        //获取当前榜单数据
        sql = QString("select b.blemind2 as blemind2 , COUNT(s.code) as count from stocks_in_trend s, stock_basis b where trade_day = '%1' and s.code = b.code GROUP BY b.blemind2 ORDER BY count DESC;").arg(getParam("date"));
        q = sqlIns->query(sql,"TrendManager");
        qDebug() << "TrendManager stocks_in_trend bleminds : count : " << q.size();
        while (q.next())
        {
            trends t;
            t.blemind2 = q.value("blemind2").toString();
            t.stocksCount = q.value("count").toString();
            t.tradeDay = getParam("date");
            t.type = getParam("type");
            double tvalue = (double)t.stocksCount.toInt()*(double)t.stocksCount.toInt()/(double)blemind2StockCounts[t.blemind2].toInt();
            t.trendsValue = QString::number(tvalue);
            trendsDatas.insert(t.blemind2,t);
            qDebug()<< "stocks_in_trend blemind2: " <<t.blemind2 << " count: " << t.stocksCount << " tvalue:" << tvalue;
        }

        //插入到数据库中
        QHashIterator<QString, trends> i(trendsDatas);
        while (i.hasNext())
        {
            i.next();
            sql = QString("insert into trends (blemind2, trade_day, stocks_count,trend_value,trend_value_change,sort,sort_change,type) "
                                  "value(':blemind2', ':trade_day', :stocks_count,:trend_value,:trendValueChange,:sort,:SortChange,':type') on DUPLICATE key "
                                  "update blemind2 = ':blemind2',trade_day=':trade_day',stocks_count=:stocks_count,trend_value=:trend_value,trend_value_change=:trendValueChange,sort=:sort,sort_change=:SortChange,type=':type';");
            sql.replace(":blemind2",i.value().blemind2);
            sql.replace(":trade_day",i.value().tradeDay);
            sql.replace(":stocks_count",i.value().stocksCount);
            sql.replace(":trend_value",i.value().trendsValue);
            sql.replace(":trendValueChange",i.value().trendsValueChanged);
            sql.replace(":sort",i.value().sort);
            sql.replace(":SortChange",i.value().sortChanged);
            sql.replace(":type",i.value().type);

            qDebug() << sql;
            sqlIns->query(sql,"TrendManager");
        }

        //重新查询，并排序
        sql = QString("select  blemind2 ,trend_value  from trends s where trade_day = '%1' ORDER BY trend_value DESC;").arg(getParam("date"));
        q = sqlIns->query(sql,"TrendManager");
        qDebug() << "TrendManager trends bleminds : count : " << q.size();
        QDate lastDate = QDate::fromString(getParam("date"),"yyyy-MM-dd");

        QString lastDateStr = lastDate.addDays(-1).toString("yyyy-MM-dd");
        int sort = 1;
        QString tvSql = "";
        while (q.next())
        {
            QString blemind2 = q.value("blemind2").toString();
            if(trendsDatas.contains(blemind2))
            {
                trendsDatas[blemind2].sort = QString::number(sort++);

                tvSql = QString("select trend_value,sort from trends where blemind2 = '%1' and trade_day = '%2' and type = '%3'")
                        .arg(blemind2).arg(lastDateStr).arg(getParam("type"));
                QSqlQuery tvq = sqlIns->query(tvSql,"TrendManager");
                if(tvq.next())
                {
                    double lastTrendValue = tvq.value("trend_value").toDouble();
                    int lastSort = tvq.value("sort").toInt();
                    trendsDatas[blemind2].sortChanged = QString::number(lastSort - trendsDatas[blemind2].sort.toInt());
                    trendsDatas[blemind2].trendsValueChanged = QString::number(trendsDatas[blemind2].trendsValue.toDouble() - lastTrendValue);
                }
                else
                {
                    trendsDatas[blemind2].sortChanged = "0";
                    trendsDatas[blemind2].trendsValueChanged = trendsDatas[blemind2].trendsValue;
                }

                //更新到数据库
                sql = QString("update trends set sort = %1 , trend_value_change = %4,sort_change = %5  where blemind2 = '%2' and type = '%3' and trade_day = '%6';")
                        .arg(trendsDatas[blemind2].sort).arg(trendsDatas[blemind2].blemind2).arg(trendsDatas[blemind2].type)
                        .arg(trendsDatas[blemind2].trendsValueChanged).arg(trendsDatas[blemind2].sortChanged).arg(getParam("date"));
                qDebug() << sql;
                sqlIns->query(sql,"TrendManager");
            }
            qDebug()<< "trend blemind2: " << blemind2 << " sort: " << QString::number(sort-1);
        }


        //计算sort_change 和 trend_value_change

//        //更新到数据库
//        QHashIterator<QString, trends> ii(trendsDatas);
//        while (ii.hasNext())
//        {
//            ii.next();
//            sql = QString("update trends set sort = %1 where blemind2 = '%2' and type = '%3';")
//                    .arg(ii.value().sort).arg(i.value().blemind2).arg(i.value().type);
//            qDebug() << sql;
//            sqlIns->query(sql,"TrendManager");
//        }


        sqlIns->deleteLater();
    }
}

void TrendManager::getDataFromMysql()
{
    QString type = getParam("type");
    QString typeId = "differrange10";
    if(type == "20")
        typeId = "differrange20";
    QString sql = QString("select s.code as code ,b.name as name,trade_day,open,close,differrange,%3,trade_days,agencies_hold,b.blemind2 as blemind2,b.blemind3 as blemind3 from stocks s, stock_basis b where trade_day = '%1' and s.code = b.code ORDER BY %3 DESC LIMIT %2;")
            .arg(getParam("date")).arg(getParam("limitCount")).arg(typeId);
    XSqlExcute* sqlIns = new XSqlExcute;
    sqlIns->openMysql("192.168.0.201","nstocks","admin","1qazse42W3","TrendManager");
    QSqlQuery q = sqlIns->query(sql,"TrendManager");
    qDebug() << "TrendManager::getDataFromMysql() : count : " << q.size();
    sqlIns->deleteLater();
    int sort = 1;
    trendStocksDatas.clear();
    trendsDatas.clear();
    blemind2StockCounts.clear();

    while (q.next())
    {
        _trendStocks tstocks;
        tstocks.code = q.value("code").toString();
        tstocks.name = q.value("name").toString();
        tstocks.tradeDay = q.value("trade_day").toString();
        tstocks.open = q.value("open").toString();
        tstocks.close = q.value("close").toString();
        tstocks.differRange = q.value("differrange").toString();
        tstocks.differRangeP10 = q.value("differrange10").toString();
        tstocks.tradeDays = q.value("trade_days").toString();
        tstocks.agenciesHold = q.value("agencies_hold").toString();
        tstocks.blemind2 = q.value("blemind2").toString();
        tstocks.blemind3 = q.value("blemind3").toString();
        if(tstocks.tradeDays.toInt() < 120)
            continue;
        if(tstocks.agenciesHold.toDouble() < 2)
            continue;
        tstocks.type = type;
        tstocks.sort = QString::number(sort++);
        trendStocksDatas.append(tstocks);
        qDebug()<< "tradeDay: " <<tstocks.tradeDay << "code: " << tstocks.code << " name: " << tstocks.name << " blemind2: " << tstocks.blemind2;
    }
    qDebug() << " trendDatas count : " << trendStocksDatas.count();


}

bool TrendManager::hasTrendData()
{
    XSqlExcute* sqlIns = new XSqlExcute;
    sqlIns->openMysql("192.168.0.201","nstocks","admin","1qazse42W3","TrendManager");
    QString sql = "select COUNT(s.code) as count from stocks_in_trend s where trade_day = '2021-11-25';";
    QSqlQuery q = sqlIns->query(sql,"TrendManager");
    bool hasData = false;
    if(q.next())
    {
        hasData = q.value("count").toInt() > 0 ? true : false;
    }
    sqlIns->deleteLater();
    return hasData;
}
