#include "dbsetForm.h"
#include "ui_dbsetForm.h"
#include "QsLog.h"
#include "DTools/configManger.h"
#include "Control/flowControl.h"

DbsetForm::DbsetForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DbsetForm)
{
    ui->setupUi(this);

    _Init();

    connect(this, &DbsetForm::connectDb, &FlowControl::GetInstance(), &FlowControl::onConnectDb);
    connect(&FlowControl::GetInstance(), &FlowControl::connectDbFinsh, this, &DbsetForm::onConnectDbFinsh);

    on_dbsetBtnOk_clicked();
}

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

void DbsetForm::_Init()
{
    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);

    ConfigManger::SqlConnectInfo info;
    info = ConfigManger::GetInstance().GetSqlConnectInfo();
    ui->dbsetEdt0->setText(info.host);
    ui->dbsetEdt1->setText(info.username);
    ui->dbsetEdt2->setText(info.password);
    ui->dbsetEdt3->setText(info.database);

    ui->dbsetLabError->hide();
    ui->dbsetPgb0->hide();
}

void DbsetForm::_SetSubElementEnable(bool bEnable)
{
    ui->dbsetEdt0->setEnabled(bEnable);
    ui->dbsetEdt1->setEnabled(bEnable);
    ui->dbsetEdt2->setEnabled(bEnable);
    ui->dbsetEdt3->setEnabled(bEnable);
    ui->dbsetBtnOk->setEnabled(bEnable);
    ui->dbsetBtnCancle->setEnabled(bEnable);
}

void DbsetForm::onConnectDbFinsh(bool bSuccess, const QString &error)
{
    Q_UNUSED(error);
    if(bSuccess)
    {
        ConfigManger::SqlConnectInfo info;
        info.host = ui->dbsetEdt0->text();
        info.username = ui->dbsetEdt1->text();
        info.password = ui->dbsetEdt2->text();
        info.database = ui->dbsetEdt3->text();
        ConfigManger::GetInstance().SetSqlConnectInfo(info);
        this->accept();
    }else
    {
        ui->dbsetPgb0->hide();
        ui->dbsetLabError->setText(tr("连接数据库失败!"));
        ui->dbsetLabError->show();
        _SetSubElementEnable(true);
    }
}

void DbsetForm::on_dbsetBtnOk_clicked()
{
    ui->dbsetLabError->hide();

//    if(ui->dbsetEdt0->text().isEmpty() ||
//       ui->dbsetEdt1->text().isEmpty() ||
//       ui->dbsetEdt3->text().isEmpty())
//    {
//        ui->dbsetLabError->setText(tr("请输入正确信息!"));
//        ui->dbsetLabError->show();
//        return;
//    }

    ui->dbsetPgb0->show();
    _SetSubElementEnable(false);

    QString host, username, password, dbname;
    host = ui->dbsetEdt0->text();
    username = ui->dbsetEdt1->text();
    password = ui->dbsetEdt2->text();
    dbname = ui->dbsetEdt3->text();
    emit connectDb(host, username, password, dbname);
}

void DbsetForm::on_dbsetBtnCancle_clicked()
{
    QLOG_TRACE() << __FUNCTION__;
    this->reject();
}
