#include "fmPlugin.h"
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QVariant>
#include <QDebug>
#include <QSettings>
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonArray>
#include <QTimer>
#include <QDir>
#include <QFile>

FmPlugin &FmPlugin::GetInstance()
{
    static FmPlugin fmPlugin;
    return fmPlugin;
}

bool FmPlugin::ConnectDb(const QString &host, const QString &username, const QString &password, const QString &dbname, QString &error)
{
    // TODO(用于鲜丰演示)
    return true;

    // 清除之前的连接
    QSqlDatabase::removeDatabase(m_db.connectionName());

    m_db = QSqlDatabase::addDatabase("QODBC");
    m_db.setConnectOptions(QString("SQL_ATTR_LOGIN_TIMEOUT=5;SQL_ATTR_CONNECTION_TIMEOUT=5"));
    m_db.setDatabaseName(QString("Driver={sql server}; server=%1; database=%2; uid=%3; pwd=%4")
                             .arg(host).arg(dbname).arg(username).arg(password));

    if(m_db.open())
    {
       error = QString("success");
       m_db.close();

       return true;
    }else
    {
       error = m_db.lastError().text();

       return false;
    }
}

bool FmPlugin::GetStoreInfo(QString &storeId, QString &posId, QString &cashierId, QDateTime &dateTime, QString &error)
{
    // TODO(用于鲜丰演示)
    QString apppath=QCoreApplication::applicationDirPath();
    QString inipath=apppath+QString("/tmp.ini");
    qDebug()<<inipath;
    QSettings set(inipath, QSettings::IniFormat);
    storeId = set.value("info/storeId").toString();
    posId = set.value("info/posId").toString();
    cashierId = QString("001");
    qDebug()<<storeId<<posId;

    return true;

    /*if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }

    QSqlQuery query = QSqlQuery(m_db);
    // 获取门店号
    QString queryStoreId("select sys_var_value from sys_t_system where sys_var_id='g_branch_no';");
    query.prepare(queryStoreId);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    query.next();
    storeId = query.value(0).toString();
    m_storeId = storeId;
    // 获取营业日
    QString queryDateTime("select sys_var_value from sys_t_system where sys_var_id='dBusiness';");
    query.prepare(queryDateTime);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    query.next();
    dateTime = query.value(0).toDateTime();

    posId="1";
    cashierId="1";

    error = QString("success");
    m_db.close();
    return true;
    */
}

bool FmPlugin::GetOnDutyCashiers(QList<CashierObject> &cashiersList, QString &error)
{
    // TODO(用于鲜丰演示)
    CashierObject obj;
    obj.id = "001";
    obj.name = "鲜丰测试";
    cashiersList.append(obj);
    return true;


    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }
    // 获取在班收银员信息
    QSqlQuery query = QSqlQuery(m_db);
    QString queryCashiers("select * from v_km_cashshift;");
    query.prepare(queryCashiers);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    while(query.next())
    {
        CashierObject cashierObj;
        cashierObj.id           = query.value(0).toString();
        cashierObj.name         = query.value(1).toString();
        cashierObj.shiftId      = query.value(2).toString();
        cashierObj.shiftName    = query.value(3).toString();
        cashiersList.append(cashierObj);
    }

    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::DoOrderEntry(const OrderObject *orderObject, const QString &cashierId, const QString &cashierName, const QString &shiftId, const QString &shiftName, QString &error)
{
    QString apppath=QCoreApplication::applicationDirPath();
    // 检查这单之前是否写过
    QString remark_file_path = QString("%1/orders/%2/%3_%4").arg(apppath, QDateTime::fromTime_t(orderObject->create_time).toString("yyyy-MM-dd"), orderObject->channel ,orderObject->order_id);
    QFile file(remark_file_path);
    if(file.exists())
    {
        error = "aready writed to haiding";
        return true;
    }

    QString inipath=apppath+QString("/config.ini");
    QSettings set(inipath, QSettings::IniFormat);
    QUrl url;
    url = set.value("HdServer/url").toUrl();

    QNetworkAccessManager manger;
    QNetworkRequest qRequset;
    qRequset.setUrl(url);
    qRequset.setRawHeader("Content-Type","application/json;charset=utf-8");
    qRequset.setRawHeader("Accept", "application/json;charset=utf-8");
    QNetworkReply *reply = manger.post(qRequset, _GetOrderEntryData(orderObject));
    QEventLoop eventLoop;
    QObject::connect(&manger, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), &eventLoop, SLOT(quit()));
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &eventLoop, SLOT(quit()));
    // 加用定时器防止网络出现异常长时间不返回导致的阻塞
    QTimer::singleShot(10000, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    reply->deleteLater();
    if( reply->error() != QNetworkReply::NoError)
    {
        error = reply->errorString();
        return false;
    }
    QByteArray recvArray = reply->readAll();
    error = QString(recvArray);
    if(recvArray.size() == 0)
    {
        error = "nothing recved";
        return false;
    }
    QJsonObject recvJson;
    recvJson = QJsonDocument::fromJson(recvArray).object();
    if(recvJson["echoCode"].toString() != "0")
    {
        error = recvJson["echoMessage"].toString();
        return false;
    }
    QDir().mkpath(remark_file_path.mid(0,remark_file_path.lastIndexOf("/")));
    file.open(QFile::WriteOnly);
    file.close();
    return true;
}

bool FmPlugin::GetStockInfo(QList<StockObject> &stockList, QString &error)
{
    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }
    StockObject stock;
    QSqlQuery query = QSqlQuery(m_db);
    QString queryStock("select * from v_km_clearfood;");
    query.prepare(queryStock);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    while(query.next())
    {
        stock.id = query.value(0).toString();
        stock.num = query.value(2).toInt();
        stockList.append(stock);
    }
    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::_InsertInto_p_t_fmwm_custinfo(int &custid)
{
    QSqlQuery query =  QSqlQuery(m_db);
    // 插入顾客信息表
    QString queryInsert("insert into p_t_fmwm_custinfo(cphone, ccust_n, ssex, saddr) \
                         values(?,?,?,?) select @@identity;");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->phone);
    query.bindValue(1, m_orderObject->customer);
    query.bindValue(2, "");
    query.bindValue(3, m_orderObject->address);
    if(!query.exec())
    {
       return false;
    }
    query.next();
    custid = query.value(0).toInt();
    return true;
}

bool FmPlugin::_InsertInto_d_t_food_fmbill0(const QString& cashierId, const QString& cashierName, const QString& shiftId, const QString& shiftName, int custid)
{
    QSqlQuery query = QSqlQuery(m_db);
    // 查询营业日
    QDateTime dbussiness;
    QString queryDateTime("select sys_var_value from sys_t_system where sys_var_id='dBusiness';");
    query.prepare(queryDateTime);
    if (!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    query.next();
    dbussiness = query.value(0).toDateTime();

    // 插入到临时表
    QString queryInsert("insert into d_t_food_fmbill0(cbill_c,cbranch_c,dBusiness,"
                         "ccashier_c, ccashier_n, cshift_c, cshift_n,"
                         "iguestnum,dtbilltime,dtsettletime,noughtamt,npayamt,"
                         "ndisamt,sbilltype,fmwmbillid,sprovider,nfreight,icustid)"
                         "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, m_storeId);
    query.bindValue(2, dbussiness);
    query.bindValue(3, cashierId);
    query.bindValue(4, cashierName);
    query.bindValue(5, shiftId);
    query.bindValue(6, shiftName);
    query.bindValue(7, m_orderObject->remark.mid(m_orderObject->remark.lastIndexOf(':')+1).toInt());
    query.bindValue(8, QDateTime::fromTime_t(m_orderObject->create_time));
    query.bindValue(9, QDateTime::fromTime_t(m_orderObject->create_time));
    query.bindValue(10, _Penny2Dollar(m_orderObject->shop_fee));
    query.bindValue(11, _Penny2Dollar(m_orderObject->shop_fee));
    query.bindValue(12, _Penny2Dollar(m_orderObject->discount_fee));
    query.bindValue(13, QString("\351\200\201\351\244\220\345\215\225"));// 送餐单
    query.bindValue(14, m_orderObject->order_id);
    query.bindValue(15, m_orderObject->channelName);
    query.bindValue(16, m_orderObject->pay_type.compare("在线支付") ? "0" : _Penny2Dollar(m_orderObject->send_fee));
    query.bindValue(17, custid);
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    return true;
}

bool FmPlugin::_InsertInto_d_t_food_fmbills0()
{
    QSqlQuery query = QSqlQuery(m_db);
    // 插入商品详情
    QString queryInsert("insert into d_t_food_fmbills0(cbill_c,cfoodbill,"
                         "cfood_c,cfood_n,nqty,nprc,namt)"
                         "values(?,?,?,?,?,?,?);");
    query.prepare(queryInsert);
    for(int i=0; i<m_orderObject->proList.count(); i++)
    {
        query.bindValue(0, m_orderObject->order_id);
        query.bindValue(1, QString("%1").arg(QString::number(i+1),4,QChar('0')));
        query.bindValue(2, m_orderObject->proList.at(i)->pid);
        query.bindValue(3, m_orderObject->proList.at(i)->name);
        query.bindValue(4, QString::number(m_orderObject->proList.at(i)->productAmount));
        query.bindValue(5, _Penny2Dollar(m_orderObject->proList.at(i)->price));
        query.bindValue(6, _Penny2Dollar(m_orderObject->proList.at(i)->price*m_orderObject->proList.at(i)->productAmount));
        if(!query.exec())
        {
            m_lastError = query.lastError().text();
            return false;
        }
    }
    return true;
}

bool FmPlugin::_InsertInto_d_t_bill_fmpay0()
{
    QSqlQuery query = QSqlQuery(m_db);
    // 插入支付详情
    QString queryInsert("insert into d_t_bill_fmpay0(cbill_c,"
                         "cbillpay,cpay_c,cpay_n,npayamt)"
                         "values(?,?,?,?,?);");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, "01");
    QString cpay_c, cpay_n;
    if(!m_orderObject->pay_type.compare("在线支付"))
    {
        if(!m_orderObject->channel.compare("mtwm"))
        {
            cpay_c = QString("14");
            cpay_n = QString("\347\276\216\345\233\242\345\244\226\345\215\226");//美团外卖
        }else if(!m_orderObject->channel.compare("fmwd"))
        {
            cpay_c = QString("13");
            cpay_n = QString("\345\276\256\344\277\241\345\244\226\345\215\226");//微店外卖
        }
    }else
    {
        cpay_c = QString("01");
        cpay_n = QString("\347\216\260\351\207\221");//现金
    }
    query.bindValue(2, cpay_c);
    query.bindValue(3, cpay_n);
    query.bindValue(4, _Penny2Dollar(m_orderObject->shop_fee));
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    return true;
}

bool FmPlugin::_Exec_pr_fmwm()
{
    QSqlQuery query = QSqlQuery(m_db);
    query.prepare("exec pr_fmwm ?, ? output;");
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, 0, QSql::Out);
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    if(query.boundValue(1).toInt() != 1)
    {
        m_lastError = QString("pr_fmwm result[%1]").arg(query.boundValue(1).toInt());
        return false;
    }
    return true;
}

QString FmPlugin::_Penny2Dollar(int penny)
{
    double dollar = (double)penny/100;
    return QString::number(dollar,'f',2);
}

QByteArray FmPlugin::_GetOrderEntryData(const OrderObject *orderObject)
{
    QJsonObject rObj;
    rObj.insert("uuid", "b62f44da9a7e421f88cb006159863ab7");
    rObj.insert("senderCode", "CWLB");
    rObj.insert("sendWrh", "-");
    rObj.insert("receiverCode", "95560000001");
    rObj.insert("contactor", orderObject->customer);
    rObj.insert("phoneNumber", orderObject->phone);
    rObj.insert("deliverAddress", orderObject->address);
    rObj.insert("remark", "非码测试");
    rObj.insert("ocrDate", QDateTime::fromTime_t(orderObject->create_time).toString("yyyy-MM-ddThh:mm:ss.zzz+0800"));
    rObj.insert("filler", "*");
    rObj.insert("seller", "*");
    QJsonArray products;
    for(int i=0; i < orderObject->proList.count(); i++)
    {
       QJsonObject cObj;
       cObj.insert("skuId", "01001");
       cObj.insert("qty", orderObject->proList.at(i)->productAmount);
       cObj.insert("price", orderObject->proList.at(i)->price);
       products.insert(i, cObj);
    }

    rObj.insert("products", products);
    qDebug() << rObj;
    return QJsonDocument(rObj).toJson(QJsonDocument::Compact);
}
