#include "fmPrinter.h"
#include <windows.h>
#include <winspool.h>
#include <QFile>
#include <QCoreApplication>
#include <QDateTime>

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

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

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

QString FmPrinter::_GetPrintData(OrderObject *pData)
{
    QString str_list;
    QString str_print;
    QString str_comd_list;

    QString filePath = QString("%1/printformat.txt").arg(QCoreApplication::applicationDirPath());
    QFile file(filePath);
    if( !file.open( QFile::ReadOnly)){
        return QString("无法打开printformat.txt!");
    }
    for(int i=0; i<pData->proList.count(); i++)
    {
        QString name, price;
        name = pData->proList[i]->name;
        price = QString("\r\n       x%1  %2  %4\r\n").arg(pData->proList[i]->productAmount).arg(_Penny2Dollar(pData->proList[i]->price))
                .arg(_Penny2Dollar(pData->proList[i]->price*pData->proList[i]->productAmount));
        str_comd_list.append(QString(name+price));
    }

    QByteArray array = file.readAll();
    str_print = QString::fromUtf8(array);

    QStringList cfgList;
    cfgList = pData->printcfg.split('|');

    foreach (QString v, cfgList) {
       QString print, fee;
       if(!v.compare("顾客留存"))
       {
           fee = "应付金额：￥"+_Penny2Dollar(pData->user_fee);
       }else if(!v.compare("商户留存"))
       {
           if(!pData->pay_type.compare("货到付款"))
           {
               fee = "应收现金：￥"+_Penny2Dollar(pData->shop_fee);
           }else
           {
               fee = "应收现金：￥ 0";
           }
       }else
       {
           if(!pData->pay_type.compare("货到付款"))
           {
               fee = "应收现金：￥"+_Penny2Dollar(pData->user_fee);
           }else
           {
               fee = "应收现金：￥ 0";
           }
       }

       print = str_print.arg(v).arg(pData->channelName).arg(pData->order_id).arg(pData->pay_type)
               .arg(pData->customer).arg(pData->phone).arg(pData->address.replace("埇","Yong")).arg(str_comd_list)
               .arg(_Penny2Dollar(pData->total_fee-pData->send_fee)).arg(_Penny2Dollar(pData->discount_fee)).arg(_Penny2Dollar(pData->send_fee)).arg(pData->total_amount)
               .arg(fee).arg(QDateTime::fromTime_t(pData->create_time).toString("yy-MM-dd hh:mm")).arg(pData->remark).arg(pData->courier_name).arg(pData->courier_phone)
               .arg(pData->delivery_time==0? "立即送出":QDateTime::fromTime_t(pData->delivery_time).toString("yyyy-MM-dd hh:mm:ss"));

       str_list.append(print);
    }

    return str_list;
}

bool FmPrinter::_RawDataToPrinter(QString printerName, QString data)
{
    LPTSTR szPrinterName = (LPTSTR)printerName.toStdWString().c_str();
    QByteArray tmpData = data.toLocal8Bit();
    LPBYTE lpData=(LPBYTE)tmpData.data();
    DWORD dwCount = strlen((char*)lpData);
    BOOL     bStatus = FALSE;
    HANDLE     hPrinter = NULL;
    DOC_INFO_1 DocInfo;
    DWORD      dwJob = 0L;
    DWORD      dwBytesWritten = 0L;

    // Open a handle to the printer.
    bStatus = OpenPrinter( szPrinterName, &hPrinter, NULL );
    if (bStatus) {
        // Fill in the structure with info about this "document."
        DocInfo.pDocName = (LPTSTR)L"TakeawayDoc";
        DocInfo.pOutputFile = NULL;
        DocInfo.pDatatype = (LPTSTR)L"RAW";

        // Inform the spooler the document is beginning.
        dwJob = StartDocPrinter( hPrinter, 1, (LPBYTE)&DocInfo );
        if (dwJob > 0) {
            // Start a page.
            bStatus = StartPagePrinter( hPrinter );
            if (bStatus) {
                // Send the data to the printer.
                bStatus = WritePrinter( hPrinter, lpData, dwCount, &dwBytesWritten);
                EndPagePrinter (hPrinter);
            }
            // Inform the spooler that the document is ending.
            EndDocPrinter( hPrinter );
        }
        // Close the printer handle.
        ClosePrinter( hPrinter );
    }
    // Check to see if correct number of bytes were written.
    if (!bStatus || (dwBytesWritten != dwCount)) {
        bStatus = FALSE;
    } else {
        bStatus = TRUE;
    }
    return bStatus;
}

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