#include "fmp_login.h"
#include "ui_fmp_login.h"
#include <QMessageBox>
#include <QDesktopWidget>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include "fmp_num_pad.h"
#include "fmnetwork.h"
#include <QDebug>

FMPLogin::FMPLogin(QString url, QString storeId, QString partnerId, QDialog *parent) :
    FMPWnd(parent),
    ui(new Ui::FMPLogin),
    _numPad(new FMNumPad),
    _userName(""),
    _errorMsg(""),
    _url(url),
    _storeId(storeId),
    _partnerId(partnerId)
{
    ui->setupUi(this);
    connect(_numPad, SIGNAL(digit_confirm()), this, SLOT(on_login_btn_clicked()));

    QDesktopWidget w;
    QRect rc = w.availableGeometry();
    _numPad->setGeometry((rc.width()+640)/2, (rc.height()-480)/2, _numPad->width(), _numPad->height());
}

FMPLogin::~FMPLogin()
{
    delete ui;
    delete _numPad;
}

void FMPLogin::on_login_btn_clicked()
{
    _numPad->close();
    this->setEnabled(false);

    if(login(ui->user_edit->text(), ui->pwd_edit->text())) {
        this->close();
    } else {
        QMessageBox::critical(this, "Login Failed", _errorMsg);
        this->setEnabled(true);
        ui->pwd_edit->clear();
        ui->pwd_edit->setFocus();
    }
}

bool FMPLogin::login(QString userName, QString password)
{
    _userName = "";
    QByteArray reqData = tr("{\"StoreId\": \"%1\",\"PartnerId\": \"%2\",\"UserId\": \"%3\",\"Pwd\": \"%4\"}")
            .arg(_storeId)
            .arg(_partnerId)
            .arg(userName)
            .arg(password).toLatin1();
    QByteArray rspData;
    FMNetwork net;
    if(net.post(_url, &reqData, &rspData)) {
        // 解析返回的数据
        QJsonParseError error;
        QJsonDocument json = QJsonDocument::fromJson(rspData, &error);
        if(error.error == QJsonParseError::NoError) {
            QJsonObject job = json.object();

            if(job["Code"] == 1000) {
                _userName = job["Data"].toObject()["UserId"].toString();
            } else{
                _errorMsg = job["Msg"].toString();
            }
        } else {
            _errorMsg = error.errorString();
        }
    }
    return isLogined();
}

void FMPLogin::on_key_btn_clicked()
{
    _numPad->setLineEdit(ui->user_edit);
    _numPad->close();
    _numPad->show();
    ui->user_edit->setFocus();
}

void FMPLogin::on_key_btn_2_clicked()
{
    _numPad->setLineEdit(ui->pwd_edit);
    _numPad->close();
    _numPad->show();
    ui->pwd_edit->setFocus();
}
