#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    registwind = new Regist(this);
    userwind = new UserWindow(this);
    init_database();

    connect(this,SIGNAL(sendinfo(QSqlDatabase,QString)),registwind,SLOT(getdata(QSqlDatabase,QString)));
}

MainWindow::~MainWindow()
{
    db.close();
    delete ui;
}

void MainWindow::init_database()
{
    //数据库是否存在
    if (QSqlDatabase::contains("mysqlite")) {
        //存在
        db = QSqlDatabase::database("mysqlite");
    }
    else {
        //不存在，则创建
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("user.db");
    }
    //打开数据库
    if (!db.open()) {
       QMessageBox::about(this,"提示","打开数据库失败!");
    }
    QSqlQuery sql_query(db);
    QString sql = "create table if not exists "
                  "user(id integer primary key autoincrement,"
                  "username text not NULL ,password text not NULL);";
    if (!sql_query.exec(sql)) {
        QMessageBox::about(this,"提示","创建表失败!");
        return;
    }
}

//注册
void MainWindow::on_pushButton_2_clicked()
{
    emit sendinfo(db,"user");
    registwind->show();
    this->hide();
}

//登录
void MainWindow::on_pushButton_clicked()
{
    //查询数据库
    QString username = ui->username->text();
    QString password = ui->password->text();
    QString sql = QString("select * from user where username = '%1' "
                  "and `password` = '%2';").arg(username,password);
    QSqlQuery sql_query(db);
    if(!sql_query.exec(sql)) {
        QMessageBox::about(this,"提示","没有找到用户");
        return;
    }
    QString usname,psword;
    while (sql_query.next()) {
        usname = sql_query.value(1).toString();
        psword = sql_query.value(2).toString();
    }
    if (usname == username && psword == password) {
        QMessageBox::about(this,"提示","登录成功");
        emit sendata(db,"user");
        userwind->show();
        this->hide();
    }
}
