#include "FmTakeaway_db.h"

#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
#include <QEventLoop>
#include <QNetworkReply>
#include <QCryptographicHash>
#include <QFile>
#include <QCoreApplication>

FmTakeaway_db &FmTakeaway_db::Instance()
{
    static FmTakeaway_db fmDb;
    return fmDb;
}

FmTakeaway_db::FmTakeaway_db()
{
    m_sqlWorker = new SqlWorker;
    m_sqlWorker->moveToThread(&m_thread);
    m_thread.start();

    connect(this, SIGNAL(doConnect(QSqlDatabase*)), m_sqlWorker, SLOT(onDoConnect(QSqlDatabase*)));
    connect(this, SIGNAL(doGetOpsInfo(QList<FmTakeaway_db::OperatorInfo>*)),
            m_sqlWorker, SLOT(onGetOpsInfo(QList<FmTakeaway_db::OperatorInfo>*)));
    connect(this, SIGNAL(doInputSale(const OrderObject*,FmTakeaway_db::OperatorInfo)),
            m_sqlWorker, SLOT(onInputSale(const OrderObject*,FmTakeaway_db::OperatorInfo)));
    connect(m_sqlWorker, SIGNAL(successful()), this, SIGNAL(successful()));
    connect(m_sqlWorker, SIGNAL(failed(QString)), this, SLOT(onFailed(QString)));
}

FmTakeaway_db::~FmTakeaway_db()
{
    m_thread.quit();
    m_thread.wait();
    delete m_sqlWorker;
}

void FmTakeaway_db::Connect(QString host, QString dataBase, QString userName, QString passWord, int outTime)
{
#ifdef LAO_XIANG_JI
    m_db = QSqlDatabase::addDatabase("QODBC");
    m_db.setConnectOptions(QString("SQL_ATTR_LOGIN_TIMEOUT=%1;SQL_ATTR_CONNECTION_TIMEOUT=%2")
                           .arg(outTime).arg(outTime));
    m_db.setDatabaseName(QString("Driver={sql server}; server=%1; database=%2; uid=%3; pwd=%4")
                         .arg(host).arg(dataBase).arg(userName).arg(passWord));
#endif   
    emit doConnect(&m_db);
}

QString FmTakeaway_db::GetBranchNum()
{
    return m_sqlWorker->GetBranchNum();
}

void FmTakeaway_db::InputSale(const OrderObject *orderObj, const FmTakeaway_db::OperatorInfo &operaInfo)
{
    qDebug() << __FUNCTION__ ;
    emit doInputSale(orderObj, operaInfo);
}

void FmTakeaway_db::GetOperatorsInfo(QList<FmTakeaway_db::OperatorInfo> &listOperator)
{
    emit doGetOpsInfo(&listOperator);
}

QString FmTakeaway_db::GetConnectInfo()
{
    return m_db.databaseName();
}

QString FmTakeaway_db::GetLastError()
{
    return m_lastError;
}

void FmTakeaway_db::onFailed(const QString &error)
{
    m_lastError = error;
    emit failed();
}

SqlWorker::SqlWorker()
{
    m_manger = new QNetworkAccessManager(this);
}

QString SqlWorker::GetBranchNum()
{
    return m_branchNum;
}

void SqlWorker::onDoConnect(QSqlDatabase *db)
{
    m_branchNum = "-99";
    m_db = db;
    if(!db->open())
    {
        emit failed(db->lastError().text());
        return;
    }

    // 获取门店编号
#ifdef LAO_XIANG_JI
    QSqlQuery query = QSqlQuery(*m_db);
    QString queryStr("select sys_var_value from sys_t_system where sys_var_id='g_branch_no'");
    query.prepare(queryStr);
    if (query.exec())
    {
        query.next();
        m_branchNum = query.value(0).toString();
    }else {
        emit failed(QString("query sql[%1]. error[%2]").arg(queryStr).arg(query.lastError().text()));
    }
#endif

    emit successful();
}

void SqlWorker::onGetOpsInfo(QList<FmTakeaway_db::OperatorInfo> *listOperator)
{
#ifdef LAO_XIANG_JI
    FmTakeaway_db::OperatorInfo operatorInfo;
    QSqlQuery query = QSqlQuery(*m_db);
    QString queryStr("select * from v_km_cashshift");
    query.prepare(queryStr);
    if (query.exec())
    {
        while(query.next())
        {
            operatorInfo.id = query.value(0).toString(); // 编号
            operatorInfo.name = query.value(1).toString(); // 名称
            operatorInfo.shiftId = query.value(2).toString(); // 班次编号
            operatorInfo.shiftName = query.value(3).toString(); // 班次名称
            listOperator->append(operatorInfo);
        }
        emit successful();
    }else
    {
        emit failed(QString("query sql[%1]. error[%2]").arg(queryStr).arg(query.lastError().text()));
    }
#endif
}

void SqlWorker::onInputSale(const OrderObject *orderObj, const FmTakeaway_db::OperatorInfo &operaInfo)
{
#ifdef LAO_XIANG_JI

#endif

#ifdef QIAN_JI
    m_manger->setNetworkAccessible(QNetworkAccessManager::Accessible);
    QNetworkRequest qRequset;
    qRequset.setUrl(QUrl("http://218.106.126.178:9999/wm/Service.asmx/NewOrder"));
    qRequset.setRawHeader("Content-Type","application/x-www-form-urlencoded");

    QString md5Str = QString("Bill=%1&SaleDate=%2&SaleTime=%3&Storeid=%4&Amount=%5&DeliveryDate=%6&Payment=%7&Key=a55AAWTmo18s218bI48dYa22t")
                        .arg(orderObj->order_id).arg(QDateTime::fromTime_t(orderObj->create_time).toString("yyyy-MM-dd"))
                        .arg(QDateTime::fromTime_t(orderObj->create_time).toString("yyyy-MM-dd hh:mm:ss"))
                        .arg(11003).arg(orderObj->user_fee).arg(QDateTime::fromTime_t(orderObj->create_time).toString("yyyy-MM-dd"))
                        .arg(orderObj->shop_fee);
    qDebug() << md5Str ;
    QByteArray sign = QCryptographicHash::hash(md5Str.toLatin1(), QCryptographicHash::Md5);
    QString sendArray = QString("Pm_OrderStr={\"Bill\":\"%1\",\"BillType\":\"%2\",\"SubBill\":\"%3\",\"SaleDate\":\"%4\",\"SaleTime\":\"%5\",\"Storeid\":\"%6\",\"Amount\":%7,\"Payment\":%8,\"DeliveryDate\":\"%9\",\"Body\":\"%10\",\"CustomName\":\"%11\",\"CustomPhone\":\"%12\",\"CustomAddress\":\"%13\",\"Key\":\"a55AAWTmo18s218bI48dYa22t\", \"Sign\":\"%14\",\"Goods_Detail\":[")
                        .arg(orderObj->order_id).arg(orderObj->channelName).arg(orderObj->order_id)
                        .arg(QDateTime::fromTime_t(orderObj->create_time).toString("yyyy-MM-dd"))
                        .arg(QDateTime::fromTime_t(orderObj->create_time).toString("yyyy-MM-dd hh:mm:ss"))
                        .arg("11003").arg(orderObj->user_fee).arg(orderObj->shop_fee)
                        .arg(QDateTime::fromTime_t(orderObj->create_time).toString("yyyy-MM-dd"))
                        .arg(orderObj->remark).arg(orderObj->customer).arg(orderObj->phone).arg(orderObj->address)
                        .arg(QString(sign.toHex()));
    qDebug() << QString(sign.toHex());
    QString goods("");
    for(int i=0; i < orderObj->proList.count(); i++)
    {

        QString tmp;
        if(0==i)
        {
          tmp = "";
        }else
        {
          tmp = ",";
        }
        goods.append(QString("%1{\"Goods_Id\":\"%2\",\"Goods_Name\":\"%3\",\"Quantity\":%4,\"Price\":%5}")
                  .arg(tmp)
                  .arg(((ComdObject*)orderObj->proList.at(i))->pid)
                  .arg(((ComdObject*)orderObj->proList.at(i))->name)
                  .arg(((ComdObject*)orderObj->proList.at(i))->productAmount)
                  .arg(((ComdObject*)orderObj->proList.at(i))->price));
    }
    sendArray.append(goods+"]}");
    QNetworkReply *reply = m_manger->post(qRequset , sendArray.toLatin1());
    QEventLoop eventLoop;
    connect( reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), &eventLoop, SLOT(quit()));
    eventLoop.exec();
    qDebug() << QString(reply->readAll());
#endif
}
