#include "loginform.h"
#include "ui_loginform.h"
#include <QMessageBox>
#include <pqQtlib/utils/pqfileutils.h>
#include <QJsonDocument>
#include "QJsonObject"

using namespace PQ;

LoginForm::LoginForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginForm),_request(nullptr)
{
    ui->setupUi(this);
    connect(this,&LoginForm::loginFinish,this,&LoginForm::clear);
    connect(glo,&GlobalInfo::doInited,this,&LoginForm::login);
    ui->status->setVisible(false);
    this->setEnabled(true);
    ui->linePass->setEchoMode(QLineEdit::Password);
    auto dt = PQ::CacheFile::readFile("userpass.cache");
    auto list = QString::fromUtf8(dt).split("[,]");
    if(list.size() == 2){
        ui->lineUser->setText(list.at(0));
        ui->linePass->setText(list.at(1));
    }
}

LoginForm::~LoginForm()
{
    delete ui;
}

void LoginForm::on_pushLogin_clicked()
{

//    QFileInfo fileInfo(QCoreApplication::applicationDirPath() + "/Config.ini");
//    if(!fileInfo.exists()){
//        qDebug()<<"配置文件不存在";
//        QMessageBox::information(this,"注意","请设置配置");
//        return;
//    }

    auto glo = GlobalInfo::this_();
    auto uname = this->ui->lineUser->text();
    auto upass = this->ui->linePass->text();
//    auto url = glo->config()->baseUrl+"/api/v1/signin";
    auto url = glo->config()->baseUrl+"/v1/signin";
//    QMap<QString,QString> params;
//    params.insert("password",upass);
//    params.insert("username",uname);

    if(uname.size() <= 0 || uname.size() <= 0) {
        QMessageBox::information(this,"注意","请输入正确的账号密码");
        return;
    }

    QJsonObject obj;
    obj.insert("password",upass);
    obj.insert("username",uname);
    obj.insert("platform",2);

    qDebug() << url << obj.toVariantMap();

    request()->post(url,obj);
    ui->status->setVisible(true);
    this->setEnabled(false);
}

void  LoginForm::clear(){
    if(_request){
        _request->deleteLater();
        _request = nullptr;
    }
}

HttpRequest *LoginForm::request()
{
    if(!_request){
        _request = new HttpRequest(this);
        connect(_request,&HttpRequest::result,this,&LoginForm::result);
    }
    return _request;
}


void LoginForm::result(int /*code*/, const QJsonObject & body)
{
    qDebug()<<body;
    ui->status->setVisible(false);
    this->setEnabled(true);
    QString message = body["message"].toString();

    if(body.value("code").toInt(404) != 200){
        QMessageBox msg(QMessageBox::Information, "错误", " 网络异常", QMessageBox::Ok, this);
        msg.exec();
//        ui->username->clear();
//        ui->password->clear();
        return;
    }

    QStringList list;
    list << ui->lineUser->text() <<  ui->linePass->text();
    CacheFile::writeFile("userpass.cache",list.join("[,]").toUtf8());
    CacheFile::writeFile("userlogin.cache",QJsonDocument(body).toJson());
    auto data  = body.value("data").toObject();
    if(data.isEmpty()){
        QMessageBox msg(QMessageBox::Information, "错误", "用户名或密码错误", QMessageBox::Ok, this);
        msg.exec();
        return;
    }
    UserInfo user;
    user.accountId = data["account_id"].toInt();
    user.userId = data["user_id"].toInt();
    user.userName = data["name"].toString();
    user.headPortrait = data["head_portrait"].toString();
    user.isVip = data["is_vip"].toInt(-1) == 1 ? true : false;
    user.acessToken = data["access_token"].toString();
//    GlobalInfo::this_()->setUser(user);
    GlobalInfo::this_()->start(user,false);
    emit loginFinish();
}

void LoginForm::on_pushButton_2_clicked()
{
    emit SettingsClicked();
}

void LoginForm::on_pushButton_clicked()
{
    CacheFile cf;
    auto dt = cf.readFile("userlogin.cache");
    UserInfo user;
    QJsonObject obj = QJsonDocument::fromJson(dt).object();
    if(!obj.isEmpty()){
        auto data  = obj.value("data").toObject();
        user.accountId = data["account_id"].toInt();
        user.userId = data["user_id"].toInt();
        user.userName = data["name"].toString();
        user.headPortrait = data["head_portrait"].toString();
        user.isVip = data["is_vip"].toInt(-1) == 1 ? true : false;
        user.acessToken = data["access_token"].toString();
    } else {
        QMessageBox::warning(this,tr("请先成功登陆一次！"),tr("请先成功登陆一次！"));
        return;
    }
    GlobalInfo::this_()->start(user,true);
    emit loginFinish();
}

void LoginForm::login()
{
    emit loginFinish();
}
