#include "Fmtakeaway_printer.h"
#include <QFile>
#include <QDateTime>
#include "../../fmTakeaway/DataObject/OrderObject.h"
#include <QCoreApplication>
#include <QDebug>
#include "../fmTakeaway/DataObject/ComdObject.h"
#include <QSettings>

FmTakeaway_printer &FmTakeaway_printer::Instance()
{
    static FmTakeaway_printer fmPt;
    return fmPt;
}

bool FmTakeaway_printer::DoPrint(QString printerName, OrderObject *pData)
{
    _RawDataToPrinter(printerName, _GetPrintData(pData));
    _RawDataToPrinter(printerName, _GetPrintData(pData));
    return _RawDataToPrinter(printerName, _GetPrintData(pData));
}

bool FmTakeaway_printer::TestPrint(QString printerName, QString data)
{
    qDebug() << __FUNCTION__;
    return _RawDataToPrinter(printerName, data);
}

void FmTakeaway_printer::setStoreName(QString name)
{
    storename=name;
}

FmTakeaway_printer::FmTakeaway_printer()
{
    qDebug() <<__FUNCTION__;
    m_print_lib.setFileName(QString("%1/fmposdll.dll").arg(QCoreApplication::applicationDirPath()));
    if(m_print_lib.load())
    {
        f_OpenPrinter = (OpenPrinter)m_print_lib.resolve("inItConfig");
        f_PrintText = (PrintText)m_print_lib.resolve("PrintData");
        f_InitPrinter = (InitPrinter)m_print_lib.resolve("Initconfigini");
        f_ClosePrinter = (ClosePrinter)m_print_lib.resolve("unloaddll");
        f_LaodAddress = (LoadAddress)m_print_lib.resolve("LoadAddress");
    }
    if(f_OpenPrinter&&f_PrintText&&f_ClosePrinter&&f_LaodAddress)
    {
        qDebug() << "Load Successful";
        m_b_load_sucfl=true;
    }
}

QString FmTakeaway_printer::_GetPrintData(OrderObject *pData)
{
    QString result_str;

     // 分辨出所有篮子信息
    QString str_comd_list;
    QMultiMap<QString, ComdObject* > map;
    QListIterator<ComdObject*> listIte(pData->proList);
    while(listIte.hasNext())
    {
        ComdObject * pObj = listIte.next();
        map.insert(pObj->bsk_num, pObj);
    }
    qDebug() <<"33333333333333"<< map;
    int index = 0;
    int count = map.uniqueKeys().count();
    foreach(QString key, map.uniqueKeys())
    {
        foreach(ComdObject* pObj, map.values(key))
        {
            QString name, price;
            name = pObj->name;
            price = QString("%1   x%2   %3").arg(_Penny2Dollar(pObj->price)).arg(pObj->productAmount)
                    .arg(_Penny2Dollar(pObj->price*pObj->productAmount));

            str_comd_list.append(QString(name+"#"+price+"#"));
        }
        index++;
        if(index!=count)
        {
             str_comd_list.append("$");
        }
    }

    foreach(QString zp, pData->dis_desc)
    {
         str_comd_list.append(QString("(赠)"+zp+"#"));
    }

        result_str.append("#"+pData->order_index);
        result_str.append("|");
        result_str.append(pData->channelName);
        result_str.append("|");
        result_str.append(storename);
        result_str.append("|");
        result_str.append(pData->pay_type);
        result_str.append("|");
        result_str.append(QDateTime::fromTime_t(pData->create_time).toString("yy-MM-dd hh:mm"));
        result_str.append("|");
        result_str.append(pData->remark.isEmpty()?"无":pData->remark);
        result_str.append("|");
        result_str.append(str_comd_list);
        result_str.append("|");
        result_str.append(QString::number(pData->package_fee));
        result_str.append("|");
        result_str.append(_Penny2Dollar(pData->discount_fee));
        result_str.append("|");
        result_str.append(_Penny2Dollar(pData->send_fee));
        result_str.append("|");
        result_str.append(_Penny2Dollar(pData->total_fee));
        result_str.append("|");
        result_str.append(pData->address);
        result_str.append("|");
        result_str.append(pData->customer);
        result_str.append("|");
        result_str.append(pData->phone);
        result_str.append("|");
        result_str.append(pData->order_id);

        return result_str;
}

QString _GetPrintIni()
{
    QString path = QString("%1/printer.ini").arg(QCoreApplication::applicationDirPath());
    QSettings config(path, QSettings::IniFormat);
    QString ini;
    ini.append(config.value("Printer/Name").toString());
    ini.append("|");
    ini.append(config.value("Printer/printType").toString());
    ini.append("|");
    ini.append(config.value("Printer/PaperWidth").toString());
    ini.append("|");
    ini.append(config.value("Printer/levlel").toString());
    ini.append("|");
    ini.append(config.value("Printer/parallel").toString());
    ini.append("|");
    ini.append(config.value("Printer/type").toString());
    ini.append("|");
    ini.append(config.value("Printer/usb").toString());
    ini.append("|");
    ini.append(config.value("Printer/IP").toString());
    ini.append("|");
    ini.append( config.value("Printer/Printlabel").toString());
    ini.append("|");
    ini.append( config.value("Printer/LogDays").toString());
    ini.append("|");
    return ini;
}

bool FmTakeaway_printer::_RawDataToPrinter(QString printerName, QString data)
{
    Q_UNUSED(printerName)
    QByteArray tmpData = data.toLocal8Bit();
    char temchar[2048]={0x0};
    QByteArray iniData = _GetPrintIni().toLocal8Bit();
    qDebug() << iniData;
                char inichar[2048]={0x0};
                strcpy(inichar,iniData.data());
    if(m_b_load_sucfl)
    {
        strcpy(temchar,tmpData.data());
        if(!f_LaodAddress())
        {
            qDebug() << "load address";
            return false;
        }
        f_InitPrinter(inichar);
        if(!f_OpenPrinter())
        {
            qDebug() << "f_OpenPrinter";
            f_ClosePrinter();
            return false;
        }

        f_PrintText(temchar);
        memset(temchar,0x0,sizeof(temchar));
        f_ClosePrinter();
        return true;
    }
    else{
        memset(temchar,0x0,sizeof(temchar));
        return false;
    }
}

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


