#include "fmPrinter.h"
#include <QFile>
#include <QCoreApplication>
#include <QDateTime>
#include <QSettings>
#include <QDebug>

FmPrinter &FmPrinter::GetInstance()
{
    static FmPrinter fp;
    return fp;
}

bool FmPrinter::DoPrint(QString printerName, OrderObject *pData)
{
    qDebug() << __FUNCTION__;
    return _RawDataToPrinter(printerName, _GetPrintData(pData));
}

bool FmPrinter::TestPrint(QString printerName, QString data)
{
    return _RawDataToPrinter(printerName, data);
}

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

FmPrinter::FmPrinter()
{
    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 FmPrinter::_GetPrintData(OrderObject *pData)
{
    qDebug() << __FUNCTION__;
    QString result_str;

     // 分辨出所有篮子信息
    QString str_comd_list;
    QMultiMap<QString, ProductObject* > map;
    QListIterator<ProductObject*> listIte(pData->proList);
    while(listIte.hasNext())
    {
        ProductObject * pObj = listIte.next();
        map.insert(pObj->bsk_num, pObj);
    }
    int index = 0;
    int count = map.uniqueKeys().count();
    foreach(QString key, map.uniqueKeys())
    {
        foreach(ProductObject* 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("$");
        }
    }

        result_str.append("#"+QString::number(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);

        qDebug() <<" 打印数据" << result_str;
        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 FmPrinter::_RawDataToPrinter(QString printerName, QString data)
{
    qDebug() << __FUNCTION__;
    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 FmPrinter::_Penny2Dollar(int penny)
{
    double dollar = (double)penny/100;
    return QString::number(dollar,'f',2);
}
