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

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()
{
    QString apppath=QCoreApplication::applicationDirPath();
    QString inipath=apppath+"/tmp.ini";
    QSettings *tmp=new QSettings(inipath,QSettings::IniFormat);
    printsize=tmp->value("info/printsize").toInt();
    m_appUrl = tmp->value("App/url").toString();

    QSettings *fmps=new QSettings(apppath+"/fmps.ini",QSettings::IniFormat);
    fmps->setIniCodec("GB2312");
    fmps->setValue("MODEWIDTH/width",printsize);
    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_ClosePrinter = (ClosePrinter)m_print_lib.resolve("unloaddll");
        f_LaodAddress = (LoadAddress)m_print_lib.resolve("LoadAddress");
        //test
        f_total = (Total)m_print_lib.resolve("Total");
    }
    if(f_OpenPrinter&&f_PrintText&&f_ClosePrinter&&f_LaodAddress&&f_total)//test
    {
        m_b_load_sucfl=true;
    }
}


QString FmPrinter::_GetPrintData(OrderObject *pData)
{
    QString str_list;
    QString str_print;
    QString str_comd_list;
    total=pData->proList.count()*2;
    for(int i=0; i<pData->proList.count(); i++)
    {
        QString name, price;
        name = pData->proList[i]->name;
        //test
        //        if(printsize==56)
        //        {
        //            price = QString("\n   \%1      x%2      %4\n\n").arg(_Penny2Dollar(pData->proList[i]->price)).arg(pData->proList[i]->productAmount)
        //                    .arg(_Penny2Dollar(pData->proList[i]->price*pData->proList[i]->productAmount));
        //            str_comd_list.append(QString(name+price+"   "));
        //        }
        //        else
        //        {
        //            price = QString("\n     \%1      x%2      %4\n\n").arg(_Penny2Dollar(pData->proList[i]->price)).arg(pData->proList[i]->productAmount)
        //                .arg(_Penny2Dollar(pData->proList[i]->price*pData->proList[i]->productAmount));
        //            str_comd_list.append(QString(name+price+"     "));
        //        }



//        if(printsize==56)
//        {
//            price = QString("%1    x%2    %3  优惠价 %4").arg(_Penny2Dollar(pData->proList[i]->price)).arg(pData->proList[i]->productAmount)
//                    .arg(_Penny2Dollar(pData->proList[i]->price*pData->proList[i]->productAmount)).arg(_Penny2Dollar(ss_fee));
//            str_comd_list.append(QString(name+"$"+price+"$"));
//        }
//        else
//        {

            price = QString("%1       x%2       %3").arg(_Penny2Dollar(pData->proList[i]->price)).arg(pData->proList[i]->productAmount)
                    .arg(_Penny2Dollar(pData->proList[i]->price*pData->proList[i]->productAmount));

        str_comd_list.append(QString(name+"$"+price+"$"));
//        }
    }

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

    QStringList cfgList;
    cfgList = pData->printcfg.split('|');
    //    foreach (QString v, cfgList) {
    //       QString print, fee;
    //       if(!v.compare("顾客留存"))
    //       {
    //           fee = _Penny2Dollar(!pData->channel.compare("bdwm") ? pData->shop_fee : pData->shop_fee - pData->service_fee - pData->dis_shop_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";
    //           }
    //       }
    QString invoice;
    if(pData->has_invoiced)
    {
        invoice=QString("是");
        if(pData->invoice_title.isEmpty())
        {
            pData->invoice_title=QString("无");
        }
    }else
    {
        invoice=QString("NULL");
        pData->invoice_title=QString("NULL");
    }


    QString print;

    QString deliveryStr("..");
    switch(pData->order_type)
    {
    case 1:
        deliveryStr = "立即送达";
        break;
    case 2:
        deliveryStr = QDateTime::fromTime_t(pData->delivery_time).toString("yy-MM-dd hh:mm");
        break;
    case 3:
        deliveryStr = "顾客自提";
        break;
    case 4:
        deliveryStr = "堂食";
        break;
    }

    QString remark;
    if(pData->remark.isEmpty())
    {
        remark = "NULL";
    }else
    {
        remark = QString("备注:")+pData->remark.remove(QChar('|'), Qt::CaseInsensitive);
    }

    QString str0 =pData->channelName;
    QString strUrl("http://qr10.cn/Du2Cfw");
    QString strDesc("下载APP 积分换好礼");
    QString bPrintImg("1");
    QString bPrintCode("1");
    QString bPrintXXCHC("1");
    if(pData->status == 20)
    {
        str0 = pData->channelName+"(顾客申请退单)";
        remark = QString("请马上联系站点沟通顾客，否则取消单将算入门店异常取消单，影响门店排名，站点电话在平台软件订单里面点击更多联系人");
        strUrl = "NULL";
        strDesc = "NULL";
        bPrintImg = "0";
        bPrintCode = "0";
        deliveryStr = "NULL";
        bPrintXXCHC = "0";
    }else if(pData->status == 21)
    {
        str0 = pData->channelName+"(顾客申请部分退单)";
        remark = QString("请马上联系站点沟通顾客，否则取消单将算入门店异常取消单，影响门店排名，站点电话在平台软件订单里面点击更多联系人");
        strUrl = "NULL";
        strDesc = "NULL";
        bPrintImg = "0";
        bPrintCode = "0";
        deliveryStr = "NULL";
        bPrintXXCHC = "0";
    }


//    if(!pData->channelName.compare("饿了么"))
//    {

//        print = str_print.append(QString("(鲜丰水果)")+storename).append("|").append("#"+QString::number(pData->order_index)+" 饿了么").append("|").append(pData->order_type==3?"自提":pData->delivery_party).append("|").append(pData->order_view_id.isEmpty()?pData->order_id:pData->order_view_id).append("|").append(QDateTime::fromTime_t(pData->create_time).toString("yy-MM-dd hh:mm"))
//                .append("|").append(deliveryStr).append("|").append(remark).append("|").append(invoice).append("|").append(pData->invoice_title).append("|").append(str_comd_list).append("|").append(_Penny2Dollar(pData->total_fee-pData->send_fee)).append("|").append(_Penny2Dollar(pData->discount_fee))
//                .append("|").append(_Penny2Dollar(pData->send_fee)).append("|").append(QString::number(pData->total_amount)).append("|").append(_Penny2Dollar(pData->total_fee-pData->discount_fee)).append("|").append(pData->customer).append("|").append(pData->address).append("|").
//                append(pData->phone).append("|").append("http://qr10.cn/Du2Cfw").append("|").append("下载APP 积分换好礼");
//    }
//    else
//    {
            print = str_print.append(QString("(鲜丰水果)")+storename).append("|").append("#"+QString::number(pData->order_index)).append(str0).append("|").append(pData->order_type==3?"自提":pData->delivery_party).append("|").append(bPrintCode).append("|").append(pData->order_view_id.isEmpty()?pData->order_id:pData->order_view_id).append("|").append(QDateTime::fromTime_t(pData->create_time).toString("yy-MM-dd hh:mm"))
                    .append("|").append(deliveryStr).append("|").append(bPrintImg).append("|").append(remark).append("|").append(invoice).append("|").append(pData->invoice_title).append("|").append(str_comd_list).append("|").append(_Penny2Dollar(pData->total_fee-pData->send_fee)).append("|").append(_Penny2Dollar(pData->discount_fee))
                    .append("|").append(_Penny2Dollar(pData->send_fee)).append("|").append(QString::number(pData->total_amount)).append("|").append(_Penny2Dollar(pData->total_fee-pData->discount_fee)).append("|").append(pData->customer).append("|").append(pData->address).append("|").
                    append(pData->phone).append("|").append(bPrintXXCHC).append("|").append(strUrl).append("|").append(strDesc);
    //鲜丰水果
    // if(!v.compare("顾客留存"))
    //{
    str_list.append(print);
    qDebug() << str_list;
    //}
    //}
    return str_list;
}

bool FmPrinter::_RawDataToPrinter(QString printerName, QString data)
{
    QByteArray tmpData = data.toLocal8Bit();
    char temchar[2048]={0x0};
    if(m_b_load_sucfl)
    {
        strcpy(temchar,tmpData.data());
        if(!f_LaodAddress())
        {
            return false;
        }
        if(!f_OpenPrinter())
        {
            f_ClosePrinter();
            return false;
        }
        //test
        f_total(total);
        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);
}
