#include "connectionDialog.h"
#include "./ui_connectionDialog.h"
#include "mainwindow.h"
#include "settings.h"
#include "tableWidgetHoverDelegate.h"
#include <QDateTime>

#define itemID 1

ConnectionDialog::ConnectionDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ConnectionDialog)
    , m_pMainWindow(nullptr)
{
    ui->setupUi(this);
    initialize();
}

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

void ConnectionDialog::showEvent(QShowEvent* e)
{
    if(ui->connectionList->rowCount() > 0)
        ui->connectionList->setCurrentCell(0, 0);

    QDialog::showEvent(e);
}

void ConnectionDialog::closeEvent(QCloseEvent* e)
{
    if(m_isNewStatus)
    {
        if(m_pMainWindow)
        {
            m_pMainWindow->showMessageDialog(type_question, QString::fromWCharArray(L"提示"),
                                             QString::fromWCharArray(L"当前正在新建连接的编辑中，确定放弃吗"));
            if(g_msgDlgBtn == btn_No)
            {
                e->ignore();
                return;
            }
        }

        removeConnListItem(m_curConnListRow);
        m_isNewStatus = false;
    }

    QDialog::closeEvent(e);
}

void ConnectionDialog::initialize()
{
    m_isNewStatus = false;
    m_curConnListRow = -1;

    QIntValidator* validator = new QIntValidator(0, 9999, this);
    ui->lineEdit_port->setValidator(validator);

    QTableWidgetHoverDelegate* delegate = new QTableWidgetHoverDelegate(ui->connectionList);
    ui->connectionList->setItemDelegate(delegate);
    ui->connectionList->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->connectionList->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->connectionList->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); //备注
    ui->connectionList->setColumnWidth(0, 120); //名称
    //从配置文件初始化列表
    QStringList connList = Settings::instance().getConnectionList();
    for(QString connID : connList)
    {
        DatabaseConfig config = Settings::instance().loadDatabaseConfig(connID);
        appendConnListItem(connID, config.strConnectionName, config.strComment);
    }
    if(ui->connectionList->rowCount() > 0) //默认定位到第一个会话链接
    {
        QTableWidgetItem* item = ui->connectionList->item(0, 0);
        ui->connectionList->setCurrentItem(item);
        QString connID = item->data(Qt::UserRole + itemID).toString();
        loadConnInfo(connID);
        m_curConnListRow = 0;
    }

    ui->splitter->setStretchFactor(0, 2);
    ui->splitter->setStretchFactor(0, 3);

    connect(ui->connectionList, &QTableWidget::cellClicked, this, &ConnectionDialog::onTableCellClicked_connList);
    connect(ui->comboBox_dbType, &QComboBox::currentTextChanged, this, &ConnectionDialog::onComboxChanged_dbType);
    connect(ui->btnOpen, &QPushButton::clicked, this, &ConnectionDialog::onBtnClicked_open);
    connect(ui->btnCancle, &QPushButton::clicked, this, &ConnectionDialog::onBtnClicked_cancle);
    connect(ui->btnSave, &QPushButton::clicked, this, &ConnectionDialog::onBtnClicked_save);
    connect(ui->btnAdd, &QPushButton::clicked, this, &ConnectionDialog::onBtnClicked_add);
    connect(ui->btnRemove, &QPushButton::clicked, this, &ConnectionDialog::onBtnClicked_remove);
}

void ConnectionDialog::appendConnListItem(const QString& connID, const QString& connName, const QString& connRemark)
{
    int rowCount = ui->connectionList->rowCount();
    ui->connectionList->insertRow(rowCount);
    ui->connectionList->setItem(rowCount, 0, new QTableWidgetItem(connName)); //名称
    QTableWidgetItem* item = ui->connectionList->item(rowCount, 0);
    item->setData(Qt::UserRole + itemID, connID);
    item->setFlags(item->flags() & (~Qt::ItemIsEditable));
    item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->connectionList->setItem(rowCount, 1, new QTableWidgetItem(connRemark)); //备注
    item = ui->connectionList->item(rowCount, 1);
    item->setFlags(item->flags() & (~Qt::ItemIsEditable));
    item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
}

void ConnectionDialog::addNewConnListItem()
{
    int rowCount = ui->connectionList->rowCount();
    ui->connectionList->insertRow(rowCount);
    ui->connectionList->setItem(rowCount, 0, new QTableWidgetItem(QString::fromWCharArray(L"新建连接"))); //名称
    QTableWidgetItem* item = ui->connectionList->item(rowCount, 0);
    item->setFlags(item->flags() & (~Qt::ItemIsEditable));
    item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->connectionList->setItem(rowCount, 1, new QTableWidgetItem("信息编辑中...")); //备注
    item = ui->connectionList->item(rowCount, 1);
    item->setFlags(item->flags() & (~Qt::ItemIsEditable));
    item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->connectionList->setCurrentItem(item);
    //刷新详细信息
    m_curConnListRow = ui->connectionList->currentRow();
    item = ui->connectionList->item(m_curConnListRow, 0);
    ui->connectionList->setCurrentItem(item);
    QString connID = item->data(Qt::UserRole + itemID).toString();
    loadConnInfo(connID);
}

void ConnectionDialog::removeConnListItem(int row)
{
    if(row < 0 || row > ui->connectionList->rowCount())
        return;

    QString connID = ui->connectionList->item(row, 0)->data(Qt::UserRole + itemID).toString();

    for(int i = 0; i < ui->connectionList->columnCount(); i++)
        delete ui->connectionList->takeItem(row, i);
    ui->connectionList->removeRow(row);

    //刷新详细信息
    if(ui->connectionList->rowCount() == 0)
    {
        m_curConnListRow = -1;
        ui->lineEdit_connection->setText("");
        ui->lineEdit_hostName->setText("");
        ui->lineEdit_port->setText("5432");
        ui->lineEdit_userName->setText("");
        ui->lineEdit_password->setText("");
        ui->comboBox_dbType->setCurrentText("PostgreSQL");
        ui->plainTextEdit->setPlainText("");
    }
    else
    {
        m_curConnListRow = ui->connectionList->currentRow();
        QTableWidgetItem* item = ui->connectionList->item(m_curConnListRow, 0);
        ui->connectionList->setCurrentItem(item);
        QString connID = item->data(Qt::UserRole + itemID).toString();
        loadConnInfo(connID);
    }

    if(!connID.isEmpty()) //从配置文件中删除
        Settings::instance().removeDatabaseConfig(connID);
}

void ConnectionDialog::loadConnInfo(const QString& connID)
{
    if(connID.isEmpty()) //新建链接
        ui->lineEdit_password->setEchoMode(QLineEdit::Normal);
    else
        ui->lineEdit_password->setEchoMode(QLineEdit::Password);

    DatabaseConfig config = Settings::instance().loadDatabaseConfig(connID);
    ui->lineEdit_connection->setText(config.strConnectionName);
    ui->lineEdit_hostName->setText(config.strHost);
    ui->lineEdit_port->setText(QString::number(config.nPort));
    ui->lineEdit_userName->setText(config.strUserName);
    ui->lineEdit_password->setText(config.strPassword);
    if(config.strDBType == "QPSQL")
        ui->comboBox_dbType->setCurrentText("PostgreSQL");
    else if(config.strDBType == "QMYSQL")
        ui->comboBox_dbType->setCurrentText("MySQL");
    ui->plainTextEdit->setPlainText(config.strComment);
}

void ConnectionDialog::setMainWindow(MainWindow* window)
{
    m_pMainWindow = window;
}

void ConnectionDialog::setErrorInfo(const QString& info)
{
    if(m_pMainWindow)
        m_pMainWindow->showMessageDialog(type_warning, QString::fromWCharArray(L"错误"),info);
    else
        ui->label_error->setText(info);
}
void ConnectionDialog::clearErrorInfo()
{
    if(m_pMainWindow)
        m_pMainWindow->hideMessageDialog();
    else
        ui->label_error->setText("");
}

void ConnectionDialog::onComboxChanged_dbType(const QString& text)
{
    if(text == "PostgreSQL")
        ui->lineEdit_port->setText("5432");
    else if(text == "MySQL")
        ui->lineEdit_port->setText("3306");
}

void ConnectionDialog::onTableCellClicked_connList(int row, int column)
{
    if(m_curConnListRow != row)
    {
        if(m_isNewStatus)
        {
            if(m_pMainWindow)
            {
                m_pMainWindow->showMessageDialog(type_question, QString::fromWCharArray(L"提示"),
                                                 QString::fromWCharArray(L"当前正在新建连接的编辑中，确定放弃吗"));
                if(g_msgDlgBtn == btn_No)
                    return;
            }
            m_isNewStatus = false;
            removeConnListItem(m_curConnListRow);
        }

        //刷新信息
        QTableWidgetItem* item = ui->connectionList->item(row, 0);
        QString connID = item->data(Qt::UserRole + itemID).toString();
        loadConnInfo(connID);
        m_curConnListRow = row;
    }
}

void ConnectionDialog::onBtnClicked_open()
{
    if(ui->lineEdit_connection->text() == "" || ui->lineEdit_hostName->text() == "" || ui->lineEdit_userName->text() == "" ||
        ui->lineEdit_password->text() == "" || ui->lineEdit_port->text() == "")
    {
        setErrorInfo(QString::fromWCharArray(L"除‘备注’外不能有信息为空"));
        return;
    }

    DatabaseConfig config;
    config.strConnectionName = ui->lineEdit_connection->text();
    config.strHost = ui->lineEdit_hostName->text();
    config.nPort = ui->lineEdit_port->text().toInt();
    config.strUserName = ui->lineEdit_userName->text();
    config.strPassword = ui->lineEdit_password->text();
    if(ui->comboBox_dbType->currentText() == "PostgreSQL")
        config.strDBType = "QPSQL";
    else if(ui->comboBox_dbType->currentText() == "MySQL")
        config.strDBType = "QMYSQL";

    emit addConnection(config);
}

void ConnectionDialog::onBtnClicked_cancle()
{
    if(m_isNewStatus)
    {
        m_isNewStatus = false;
        removeConnListItem(m_curConnListRow);
        clearErrorInfo();
    }
    else
        close();
}

void ConnectionDialog::onBtnClicked_save()
{
    if(ui->lineEdit_connection->text() == "" || ui->lineEdit_hostName->text() == "" || ui->lineEdit_userName->text() == "" ||
        ui->lineEdit_password->text() == "" || ui->lineEdit_port->text() == "")
    {
        setErrorInfo(QString::fromWCharArray(L"除‘备注’外不能有其它信息为空"));
        return;
    }

    if(ui->connectionList->rowCount() == 0)
    {
        setErrorInfo(QString::fromWCharArray(L"当前无存储对象，请先创建一个链接"));
        return;
    }

    DatabaseConfig config;
    config.strConnectionName = ui->lineEdit_connection->text();
    config.strHost = ui->lineEdit_hostName->text();
    config.nPort = ui->lineEdit_port->text().toInt();
    config.strUserName = ui->lineEdit_userName->text();
    config.strPassword = ui->lineEdit_password->text();
    if(ui->comboBox_dbType->currentText() == "PostgreSQL")
        config.strDBType = "QPSQL";
    else if(ui->comboBox_dbType->currentText() == "MySQL")
        config.strDBType = "QMYSQL";
    if(ui->plainTextEdit->toPlainText().isEmpty())
        config.strComment = QString::fromWCharArray(L"无");
    else
        config.strComment = ui->plainTextEdit->toPlainText();

    QTableWidgetItem* item = ui->connectionList->item(ui->connectionList->currentRow(), 0);
    if(m_isNewStatus)
    {
        config.strID = QDateTime::currentDateTime().toString("yyMMddhhmmssz");
        item->setData(Qt::UserRole + itemID, config.strID);
        m_isNewStatus = false;
    }
    else
        config.strID = item->data(Qt::UserRole + itemID).toString();
    item->setText(ui->lineEdit_connection->text());
    item = ui->connectionList->item(ui->connectionList->currentRow(), 1);
    item->setText(config.strComment);

    Settings::instance().saveDatabaseConfig(config);
}

void ConnectionDialog::onBtnClicked_add()
{
    if(m_isNewStatus)
    {
        if(m_pMainWindow)
            m_pMainWindow->showMessageDialog(type_warning, QString::fromWCharArray(L"错误"),
                                             QString::fromWCharArray(L"当前正在新建链接的编辑中，请先结束操作"));
        return;
    }
    addNewConnListItem();
    m_isNewStatus = true;
}

void ConnectionDialog::onBtnClicked_remove()
{
    if(m_pMainWindow)
    {
        m_pMainWindow->showMessageDialog(type_question, QString::fromWCharArray(L"提示"),
                                         QString::fromWCharArray(L"确认删除当前选择吗"));
        if(g_msgDlgBtn == btn_Yes)
        {
            removeConnListItem(m_curConnListRow);
            if(m_isNewStatus)
                m_isNewStatus = false;
        }
    }
}
