#ifndef RSPFACTORY
#define RSPFACTORY

#include "requestmodel.h"
#include "global.h"
#include "fmtool.h"
#include "QsLog.h"
#include "fmp_settings.h"
#include "tools.h"
#include "fmglobal.h"

#include <QFile>
#include <QDir>
#include <QJsonObject>
#include <QApplication>

class RspFactory
{
public:

    static bool GetResponseJson(ReqType type, QJsonObject &response, const QJsonObject &json)
    {
        if(json.isEmpty())
            return false;
        if(type == sign)
            return GetSignResponse(response, json);
        if(type == pay)
            return GetPayResponse(response, json);
        if(type == refund)
            return GetRefundResponse(response, json);
        if(type == endday)
            return GetEndDayResponse(response, json);
        if(type == shift)
            return GetShiftResponse(response, json);
        if(type == finds)
            return GetFindResponse(response, json);
        if(type == againprint)
            return GetAgainPrinteResponse(response, json);
        return false;
    }

#ifndef FM_TEST
private:
#endif

    static bool GetSignResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;
        return true;
    }

    static bool GetPayResponse(AlipayResponse &response, const QJsonObject &json)
    {
        FMTool::SetString(response.ResponseCode, 3, QString::number(json[JSON_KEY_STATUSCODE].toInt()));
        FMTool::SetString(response.ResponseMsg, 40, json[JSON_KEY_MESSAGE].toString());
        FMTool::SetString(response.CardTraceNo, 40, json[JSON_KEY_FMID].toString());
        FMTool::SetString(response.NeedPrint, 2, QString("01"));
        int transAmount = json[JSON_KEY_TRANSAMOUNT].toInt();
        int merchantDiscount = json[JSON_KEY_MERDISCOUNT].toInt();
        int platformDiscount = json[JSON_KEY_PLTDISCOUNT].toInt();
        int userAmount = transAmount - merchantDiscount - platformDiscount;

        QString number;
        {
            //用户实付
            struct EFTItem *item = (struct EFTItem *)response.EFT_Detail_information[0];
            FMTool::SetString((void *)&(item->billType), 1, "1");
            FMTool::SetString((void *)&(item->billId), 8, QString("36464"));
            FMTool::SetString((void *)&(item->amount), 12, QString::number(userAmount));
            FMTool::SetString((void *)&(item->transactionNum), 64, json[JSON_KEY_FMID].toString());
            //FMTool::SetString((void *)&(item->transactionNum), 64, "99571708191000040011");
            number = "01";
        }


        if(merchantDiscount != 0) {
            //商户补贴
            struct EFTItem *item = (struct EFTItem *)response.EFT_Detail_information[1];
            FMTool::SetString((void *)&(item->billType), 1, "1");
            FMTool::SetString((void *)&(item->billId), 8, QString("36466"));
            FMTool::SetString((void *)&(item->amount), 12, QString::number(merchantDiscount));
            //FMTool::SetString((void *)&(item->amount), 12, QString("100"));
            FMTool::SetString((void *)&(item->transactionNum), 64, json[JSON_KEY_FMID].toString());
            number = "02";
        }

        if(platformDiscount != 0) {
            //支付宝补贴
            struct EFTItem *item = (struct EFTItem *)response.EFT_Detail_information[2];
            FMTool::SetString((void *)&(item->billType), 1, "1");
            FMTool::SetString((void *)&(item->billId), 8,  QString("10001"));
            FMTool::SetString((void *)&(item->amount), 12, QString::number(platformDiscount));
            FMTool::SetString((void *)&(item->transactionNum), 64, json[JSON_KEY_FMID].toString());
            number = "03";
        }

        FMTool::SetString(response.EFT_quantity, 2, number);

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetPinter(response, json);

        return true;
    }

    static bool GetPayResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;
        return true;
    }

    static bool GetRefundResponse(AlipayResponse &response, const QJsonObject &json)
    {
        FMTool::SetString(response.ResponseCode, 3, QString::number(json[JSON_KEY_STATUSCODE].toInt()));
        FMTool::SetString(response.ResponseMsg, 40, json[JSON_KEY_MESSAGE].toString());
        FMTool::SetString(response.CardTraceNo, 40, json[JSON_KEY_FMID].toString());
        FMTool::SetString(response.NeedPrint, 2, QString("01"));

        int transAmount = json[JSON_KET_CLIENTREF].toString().toInt();
        int merchantDiscount = json[JSON_KEY_MERDISCOUNT].toInt();
        int platformDiscount = json[JSON_KEY_PLTDISCOUNT].toInt();
        int userAmount = transAmount - merchantDiscount - platformDiscount;

        QString number;

        if(json[JSON_KEY_STATUSCODE].toInt() == 100) {
            struct EFTItem *item = (struct EFTItem *)response.EFT_Detail_information[0];
            FMTool::SetString((void *)&(item->billType), 1, "1");
            FMTool::SetString((void *)&(item->billId), 8, QString("36464"));
            FMTool::SetString((void *)&(item->amount), 12, QString::number(userAmount));
            FMTool::SetString((void *)&(item->transactionNum), 64, json[JSON_KEY_FMID].toString());
            number = "01";
        }

        FMTool::SetString(response.EFT_quantity, 2, number);

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetPinter(response, json);

        return true;

    }

    static bool GetRefundResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;
        return true;
    }

    static bool GetDayEndResponse(AlipayResponse &response, const QJsonObject &json)
    {
        FMTool::SetString(response.ResponseCode, 3, QString::number(json[JSON_KEY_STATUSCODE].toInt()));
        FMTool::SetString(response.ResponseMsg, 40, json[JSON_KEY_MESSAGE].toString());
        FMTool::SetString(response.NeedPrint, 2, QString("01"));

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetPinter(response, json);

        return true;
    }


    static bool GetEndDayResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetPinter(response, json, CONFIG_PRINT_ENDDAY_NAME);

        return true;
    }


    static bool GetShiftResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetPinter(response, json, CONFIG_PRINT_SHIFT_NAME);

        return true;
    }

    static bool GetAgainPrinteResponse(AlipayResponse &response, const QJsonObject &json)
    {
        FMTool::SetString(response.ResponseCode, 3, QString::number(json[JSON_KEY_STATUSCODE].toInt()));
        FMTool::SetString(response.ResponseMsg, 40, json[JSON_KEY_MESSAGE].toString());
        FMTool::SetString(response.CardTraceNo, 40, json[JSON_KEY_FMID].toString());
        FMTool::SetString(response.NeedPrint, 2, QString("01"));

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetAgainPinter(response, json);

        return true;
    }

    static bool GetAgainPrinteResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;

        if(json[JSON_KEY_STATUSCODE].toInt() == 100)
            return SetPinter(response, json, CONFIG_PRINT_AGAIN_NAME);

        return true;
    }

    static bool GetFindResponse(AlipayResponse &response, const QJsonObject &json)
    {
        Q_UNUSED(response);
        Q_UNUSED(json);
        return false;
    }

    static bool GetFindResponse(QJsonObject &response, const QJsonObject &json)
    {
        response = json;
        return true;
    }

    static bool SetAgainPinter(AlipayResponse &response, const QJsonObject &json)
    {
        if(!json.contains(JSON_KEY_EXT) || !json[JSON_KEY_EXT].isObject())
            return false;

        FMTool::SetString(response.NeedPrint, 2, QString("00"));

        QJsonObject obj = json[JSON_KEY_EXT].toObject();
        QString str;
        str.append(obj[JSON_KEY_PRINT].toString());
        str.replace("#", "\r\n");
        str.append("==============================\r\n").append(QChar(27)).append(QChar('@')).append(QChar(29)).append("hP").append(QChar(29)).append(QChar('w')).append(QChar(2)).append(QChar(29)).append(QChar('H')).append(QChar(2));
        str.append(QChar(27)).append(QChar('a')).append(QChar(1)).append(QChar(29)).append("kF").append(QChar(20)).append(json[JSON_KEY_FMID].toString()).append("\r\n").append(QChar(27)).append('@').append('\r').append('\n');

        qDebug() << str;
        qDebug() << json;

        QFile file(qApp->applicationDirPath() + "/" + PRINT_FILE_NAME);
        QString path = qApp->applicationDirPath() + "/" + PRINT_FILE_NAME;
        FMTool::SetString(response.EFTprintFileName, 200, path.replace("/", "\\"));
        file.open(QFile::WriteOnly);

        if(!file.isOpen())
            return false;

        char array[MAX_PRINT_LEN] = { 0 };
        FMTool::SetStringWith(array, str.toUtf8().length(), str);

        file.write(array);
        file.flush();
        file.close();
        return true;
    }

    static bool SetPinter(AlipayResponse &response, const QJsonObject &json)
    {
        if(!json.contains(JSON_KEY_EXT) || !json[JSON_KEY_EXT].isObject())
            return false;

        FMTool::SetString(response.NeedPrint, 2, QString("00"));

        QJsonObject obj = json[JSON_KEY_EXT].toObject();
        QString str = obj[JSON_KEY_PRINT].toString();
        str.replace("#", "\r\n");
        str.append("\r\n");

        QFile file(qApp->applicationDirPath() + "/" + PRINT_FILE_NAME);
        QString path = qApp->applicationDirPath() + "/" + PRINT_FILE_NAME;
        FMTool::SetString(response.EFTprintFileName, 200, path.replace("/", "\\"));
        file.open(QFile::WriteOnly);

        if(!file.isOpen())
            return false;

        char array[MAX_PRINT_LEN] = { 0 };
        FMTool::SetStringWith(array, str.toUtf8().length(), str);

        file.write(array);
        file.flush();
        file.close();
        return true;
    }

    static bool SetPinter(QJsonObject &response, const QJsonObject &json, QString configKey=CONFIG_PRINT_ENDDAY_NAME)
    {
        if(!json.contains(JSON_KEY_EXT) || !json[JSON_KEY_EXT].isObject())
            return false;

        QJsonObject obj = json[JSON_KEY_EXT].toObject();
        QString str = obj[JSON_KEY_PRINT].toString();

        QString path;
        ToolS::GetPath(path);
        FMPSettings setting;
        path = setting.GetValue(CONFIG_PRINT_PATH, path).toString();

        QDir dir(path);
        if(!dir.exists()) {
            bool isOk = dir.mkpath(path);
            QLOG_INFO() << "Make path: " << path << (isOk ? " Success." : " Fail.");
        }

        QString printFileName = setting.GetValue(configKey, PRINT_FILE_NAME).toString();

        QString filePath = dir.absolutePath();
        if(!filePath.endsWith('/') && !filePath.endsWith('\\')) {
            filePath.append('/');
        }
        filePath.append(printFileName);
        response[JSON_KEY_PRINTPATH] = filePath;
        QFile file(filePath);
        file.open(QFile::WriteOnly);

        if(!file.isOpen())
            return false;

        char buf[MAX_PRINT_LEN] = { 0 };
        FMTool::SetString(buf, str.toUtf8().length(), str);

        file.write(buf);
        file.flush();
        file.close();
        return true;
    }
};

#endif // RSPFACTORY
