#include "waitdialog.h"
#include "dialog.h"
#include "ui_waitdialog.h"
#include "define.h"
#include "workutil.h"
#include <QTimer>


WaitDialog::WaitDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::WaitDialog)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_TranslucentBackground);
    ui->widget->setWindowOpacity(1);
    this->move(parent->pos());
    setWindowFlags(Qt::FramelessWindowHint| Qt::Tool );
    //setWindowFlags( windowFlags() | Qt::WindowStaysOnTopHint);
    connect( getMySock(), &mySock::sgReturnJson, this, &WaitDialog::slReturnJson);
    connect( getMySock(), &mySock::error, this, &WaitDialog::slerror);
    ui->pushButton->setVisible( false);

    ui->label->adjustSize();

    QString dllpathstr = "D:/hspos/pos_ad_dll.dll";

    LPCWSTR dllpath =  reinterpret_cast<const wchar_t *>(dllpathstr.utf16());
    dllHandle = LoadLibrary( dllpath);

    this->setStyleSheet("QWidget#mainWdg{background:rgba(140,140,140,0.4)}");
}

WaitDialog::~WaitDialog()
{
    FreeLibrary( dllHandle);
    delete ui;
}

void WaitDialog::delBtn(bool isSuccess)
{
    ui->pushButton->setVisible( true);

    if( isSuccess){
        ui->pushButton->setText( "确认");

        connect( ui->pushButton, &QPushButton::clicked, this, &WaitDialog::accept);
    }else{
        ui->pushButton->setText( "关闭");

        connect( ui->pushButton, &QPushButton::clicked, this, &WaitDialog::reject);
    }
}

void WaitDialog::delErrCode(const int code, QString msg)
{
    if(msg != "")
    {
        ui->label->setText(msg);
        delBtn( false);
    }else
    {
        QString str = "未知错误";
        switch ( code) {
        case 21:
            str =  "参数错误";
            break;
        case 41:
            str =  "交易不存在";
            break;
        case 204:
            str =  "支付超时";
            break;
        case 205:
            str =  "条码不存在";
            break;
        default:
            break;
        }
        ui->label->setText(str);
        delBtn( false);
    }

}

void WaitDialog::slReturnJson(const mySock::RequstType type,  const QJsonObject &json)
{
    int code = json[ _statusCode].toInt();
    if(  code != 100){
        if(json.contains("msg"))
            delErrCode( code, json["msg"].toString());
        else
            delErrCode( code);
        return;
    }

    this->reject();
    emit SuccessJson(type, json);
    return ;


//    QJsonObject ext = json[ _ext].toObject();
//    QString str = ext["print"].toString();

//    if( !printing( str)){
//        ui->label->setText( "支付成功,打印机故障");
//    }else{
//        ui->label->setText( "支付成功");
//    }

//    outJson = json;

//    delBtn( true);
}

bool WaitDialog::printing(const QString& text)
{
    int res;
    qDebug() << "init";

    initPrint myInit = (initPrint)GetProcAddress( dllHandle, "OpenPrinter");
    res = myInit();
    if( HS_OK != res)
        return false;
    qDebug() << "init";


    printText myText = (printText)GetProcAddress( dllHandle, "PrintText");

    QStringList strList = text.split("\r\n");
    foreach ( QString v, strList) {
        QByteArray array = v.toLocal8Bit();
        char *tmp = new char[array.size() + 1];
        strcpy( tmp, array.data());
        res = myText( tmp, 24);
        if( HS_OK != res)
            return false;

        delete []tmp;
    }

    qDebug() << "br";
    BeginPrint myBegin = (BeginPrint)GetProcAddress( dllHandle, "BeginPrint");
    res = myBegin();
    if( HS_OK != res)
        return false;

    closePrinter myClose = (closePrinter)GetProcAddress( dllHandle, "ClosePrinterEx");
    res = myClose();
    if( HS_OK != res)
        return false;

    return true;
}

void WaitDialog::slerror(int socketError, const QString &message)
{
    ui->label->setText( message);

    delBtn( false);
}

void WaitDialog::getOutJson( QJsonObject &json)
{
    json = outJson;
}

bool WaitDialog::pay(const QJsonObject &in_json , QJsonObject &out_json, Dialog *parent)
{
    WaitDialog v(parent);
    v.move(parent->pos());

    if(in_json["transactions"].toArray()[0].toObject()["code"].toString() == "" ||
       in_json["transactions"].toArray()[0].toObject()["amount"].toInt() <= 0)
    {
        v.ui->label->setText("金额或条码不能为空!");
        v.delBtn(false);
        v.exec();
        return false;
    }

    getMySock()->getNewJosn( mySock::Consume, in_json);
    connect(&v, &WaitDialog::SuccessJson, parent, &Dialog::on_successjson_come);
    if( QDialog::Accepted == v.exec()){
        v.getOutJson( out_json);
        return true;
    }

    return false;
}

bool WaitDialog::refund(const QJsonObject &in_json , QJsonObject &out_json, Dialog *parent)
{   
    WaitDialog v(parent);
    v.move(parent->pos());

    if(in_json["transactions"].toArray()[0].toObject()["refund_count"].toInt() <= 0)
    {
        v.ui->label->setText("金额或条码不能为空!");
        v.delBtn(false);
        v.exec();
        return false;
    }

    if(in_json["transactions"].toArray()[0].toObject()["paied_trans_id"].toString() == "" &&
       in_json["transactions"].toArray()[0].toObject()["fmId"].toString() == "")
    {
        v.ui->label->setText("金额或条码不能为空!");
        v.delBtn(false);
        v.exec();
        return false;
    }

    if(!in_json["transactions"].toArray()[0].toObject().contains("fmId"))
    {
        if(!g_map.contains(in_json["transactions"].toArray()[0].toObject()["paied_trans_id"].toString()))
        {
            v.ui->label->setText("交易记录不存在!");
            v.delBtn(false);
            v.exec();
            return false;
        }
    }

    getMySock()->getNewJosn( mySock::Reject, in_json);
    connect(&v, &WaitDialog::SuccessJson, parent, &Dialog::on_successjson_come);
    if( QDialog::Accepted == v.exec()){
        v.getOutJson( out_json);
        return true;
    }
    return false;
}
