#include "fmPlugin.h"
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QVariant>
#include <QDebug>
#include <QSettings>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonDocument>
#include <QEventLoop>
#include <QTimer>
#include <QJsonArray>
#include <QDataStream>

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

void FmPlugin::SetRemoteInfo(const QString &ip, int port)
{
    m_host = ip;
    m_port = port;
}

bool FmPlugin::DoOrderEntry(const OrderObject *orderObject, QString &error, bool bVerify)
{
    QTcpSocket socket;
    // 连接
    socket.connectToHost(m_host, m_port);
    if (socket.waitForConnected())
    {
        // 初始化请求数据
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_5_3);
        out << quint32(0);
        out << _GetOrderEntryData(orderObject, bVerify);
        out.device()->seek(0);
        out << (quint32)(block.size() - sizeof(quint32));

        // 发送
        socket.write(block);
        if (socket.waitForBytesWritten())
        {
            // 接收返回
            if (socket.waitForReadyRead())
            {
                QJsonObject recvJson =  QJsonDocument::fromJson(socket.readAll()).object();
                if(recvJson["statusCode"].toInt()==100)
                {
                    socket.close();
                    return true;
                }else
                {
                    error = recvJson["msg"].toString();
                    socket.close();
                    return false;
                }
            }
        }
    }
    error = socket.errorString();
    socket.close();
    return false;
}

bool FmPlugin::RefundOrder(const QString &orderId, QString &error)
{
    QTcpSocket socket;
    // 连接
    socket.connectToHost(m_host, m_port);
    if (socket.waitForConnected())
    {
        // 初始化请求数据
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_5_3);
        out << quint32(0);
        out << _GetRefundOrderData(orderId);
        out.device()->seek(0);
        out << (quint32)(block.size() - sizeof(quint32));

        // 发送
        socket.write(block);
        if (socket.waitForBytesWritten())
        {
            // 接收返回
            if (socket.waitForReadyRead())
            {
                QJsonObject recvJson =  QJsonDocument::fromJson(socket.readAll()).object();
                if(recvJson["statusCode"].toInt()==100)
                {
                    socket.close();
                    return true;
                }else
                {
                    error = recvJson["msg"].toString();
                    socket.close();
                    return false;
                }
            }
        }
    }
    error = socket.errorString();
    socket.close();
    return false;
}

QByteArray FmPlugin::_GetOrderEntryData(const OrderObject *orderObject, bool bVerify)
{
    QJsonObject rObj, cObj;
    if(bVerify)
    {
        rObj.insert("fm_cmd", "put_order_check");
    }else
    {
        rObj.insert("fm_cmd", "put_order");
    }
    rObj.insert("fm_ver", "1.0");
    cObj.insert("pay_id", "002");
    cObj.insert("pay_str", "非码外卖");
    cObj.insert("pay_ebcode", orderObject->channel);
    cObj.insert("pay_ebcode_str", orderObject->channelName);
    cObj.insert("products_fee", orderObject->shop_fee-orderObject->package_fee);    // 商品金额
    cObj.insert("service_fee", orderObject->service_fee);   // 平台佣金
    cObj.insert("discount_fee", orderObject->discount_fee); // 优惠总额
    cObj.insert("dis_shop_fee", orderObject->dis_shop_fee); // 商家承担优惠金额
    cObj.insert("dis_platform_fee", orderObject->dis_platform_fee); // 平台承担优惠金额
    cObj.insert("send_fee", orderObject->send_fee);         // 配送费
    cObj.insert("shop_fee", orderObject->total_fee-orderObject->send_fee-orderObject->service_fee-orderObject->dis_shop_fee);         // 商户能够拿到的钱(去除平台佣金)
    cObj.insert("package_fee", orderObject->package_fee);   // 打包费
    cObj.insert("invoice_amount",orderObject->total_fee-orderObject->send_fee-orderObject->service_fee-orderObject->dis_shop_fee);
    cObj.insert("paid_trans_id",orderObject->order_id);
    cObj.insert("fm_id",orderObject->order_id);
    rObj.insert("pay_id", cObj);
    QJsonArray products;
    for(int i=0; i < orderObject->proList.count(); i++)
    {
        QJsonObject tObj;
        tObj.insert("consume_num", orderObject->proList.at(i)->productAmount);
        tObj.insert("pid", orderObject->proList.at(i)->pid);
        tObj.insert("original_price", orderObject->proList.at(i)->price);
        products.insert(i, tObj);
    }
    rObj.insert("products", products);

    QJsonDocument doc(rObj);
    return doc.toJson(QJsonDocument::Compact);
}

QByteArray FmPlugin::_GetRefundOrderData(const QString &orderId)
{
    QJsonObject rObj;
    rObj.insert("fm_cmd", "refund_order");
    rObj.insert("fm_ver", "1.0");
    rObj.insert("fm_id", orderId);

    QJsonDocument doc(rObj);
    return doc.toJson(QJsonDocument::Compact);
}
