#include "fmPrinter.h"
#include <QFile>
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QSettings>
#include "../fmTakeaway/Model/productObject.h"

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);
}

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

FmPrinter::FmPrinter()
{
    qDebug() <<__FUNCTION__;
    m_print_lib.setFileName("fmposdll.dll");
    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)
{
    QString result_str;

    int productCount = 0;

     // 分辨出所有篮子信息
    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+"#"));
            productCount += pObj->productAmount ;

        }
        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(pData->order_id);
        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->delivery_time>0?QDateTime::fromTime_t(pData->delivery_time).toString("yy-MM-dd hh:mm"):"立即送达");
        result_str.append("|");
        result_str.append(pData->remark.isEmpty()?"null":pData->remark);
        result_str.append("|");
        result_str.append(pData->has_invoiced?"是": "null");

        QString strTitle("null"), strNum("null");
        if(pData->has_invoiced)
        {
            QStringList tmp = pData->invoice_title.split("，");
            if(tmp.count()==2)
            {
                strTitle = tmp.at(0);
                strNum = tmp.at(1);
            }else
            {
               strTitle = strNum = pData->invoice_title;
            }
        }

        result_str.append("|");
        result_str.append(strTitle);
        result_str.append("|");
        result_str.append(strNum);
        result_str.append("|");
        result_str.append(str_comd_list);
        result_str.append("|");
        result_str.append(QString::number(productCount));
        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(_Penny2Dollar(pData->product_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);
        // 外卖订单后加 0
        result_str.append("|0");

        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)
{
    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);
}
