#include "formthirdlist.h"
#include "ui_formthirdlist.h"
#include "mapplication.h"
#include "../mainwindow.h"
#include "formthird.h"
#include "utils/filtertableheader.h"

#include <QSqlQueryModel>
#include <QResizeEvent>


formThirdList::formThirdList(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::formThirdList)
{

    ui->setupUi(this);
    //QStringList header;
    //header << tr("Código") << tr("Título") << tr("Tipo") << tr("Precio de Compra");

    mModel = new QSqlQueryModel(this);
    //ui->tableView->setModel(mModel);

    QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(mModel);
    ui->tableView->setModel(proxyModel);

    // Set up filter row
    m_tableHeader = new FilterTableHeader(ui->tableView);
    ui->tableView->setHorizontalHeader(m_tableHeader);
    m_tableHeader->setFilter(1, "");
    m_tableHeader->setFocusColumn(1);
    // Disconnect clicking in header to select column, since we will use it for sorting.
    // Note that, in order to work, this cannot be converted to the standard C++11 format.
    disconnect(m_tableHeader, SIGNAL(sectionPressed(int)),this, SLOT(selectColumn(int)));
    //connect(m_frozen_table_view->filterHeader(), &FilterTableHeader::filterChanged, filterHeader(), &FilterTableHeader::filterChanged);
    connect(m_tableHeader, &FilterTableHeader::filterChanged, this, &formThirdList::applyFilter);


    updateList();
    ui->tableView->setColumnHidden(0, true);
    m_tableHeader->generateFilters(mModel->columnCount(), 0);
}

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

void formThirdList::updateList()
{
    dApp->Enterprise().open();
    mModel->setQuery("SELECT ID, CIF, NAME, NICKNAME, ADDRESS, CITY, PHONE, MOBILE, FAX, EMAIL FROM THIRD ORDER BY ID ASC",
                     dApp->Enterprise());

    dApp->Enterprise().close();
}

void formThirdList::applyFilter()
{
    dApp->Enterprise().open();
    QString query = "SELECT ID, CIF, NAME, NICKNAME, ADDRESS, CITY, PHONE, MOBILE, FAX, EMAIL FROM THIRD";
    QString filters = "";

    for (int i = 1; i < mModel->columnCount(); i++)
    {
        if(m_tableHeader->filterValue(i).isEmpty())
            continue;

        if(!filters.isEmpty())
            filters += " AND ";
        //WHERE NAME LIKE '%ter%'
        filters += mModel->headerData(i, Qt::Horizontal).toString() + " LIKE '%" + m_tableHeader->filterValue(i) + "%'";
    }
    if (!filters.isEmpty())
        query += " WHERE " + filters;

    //query += " ORDER BY ID ASC";

    mModel->setQuery(query,
                     dApp->Enterprise());

    if (mModel->lastError().isValid())
        qDebug() << mModel->lastError();

    dApp->Enterprise().close();
}

void formThirdList::on_buttonNew_released()
{
    formThird *form = dApp->mainWindow()->createFormThird();
    form->show();
}

void formThirdList::on_buttonEdit_released()
{
    openDocument(ui->tableView->currentIndex());
}

void formThirdList::on_buttonClone_released()
{

}

void formThirdList::on_buttonDelete_released()
{
    QModelIndex index = ui->tableView->currentIndex();
    QAbstractItemModel *model = const_cast<QAbstractItemModel*>(index.model()); // Obtén el modelo asociado
    QModelIndex parentIndex = index.parent(); // Obtén el índice del padre
    if (index.column() != 0)
        index = model->index(index.row(), 0, parentIndex); // Obtén el índice del hijo

    QString ID = index.data().toString();
    QModelIndex childIndex = model->index(index.row(), 2, parentIndex); // Obtén el índice del hijo
    int type = childIndex.data().toInt(); // Accede al dato

    dApp->Enterprise().open();
    QSqlQuery qry = QSqlQuery(dApp->Enterprise());

    if(!qry.exec(QString("DELETE FROM THIRD WHERE CODE = '%1';").arg(ID)))
    {
        qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
    }
    updateList();
    dApp->Enterprise().close();
}

void formThirdList::on_buttonUpdate_released()
{
    updateList();
}

void formThirdList::on_tableView_doubleClicked(const QModelIndex &index)
{
    openDocument(index);
}


void formThirdList::openDocument(QModelIndex index)
{

    formThird *form = dApp->mainWindow()->createFormThird();
    form->openDocument(index.model()->index(index.row(), 0).data().toString());
    form->show();
}

void formThirdList::resizeEvent(QResizeEvent *event)
{
    QStringList texts = { tr("Nuevo"), tr("Editar"), tr("Clonar"), tr("Borrar"), tr("Actualizar") };
    QList<QPushButton*> buttons = { ui->buttonNew, ui->buttonEdit, ui->buttonClone, ui->buttonDelete, ui->buttonUpdate };

    for (int i = 0; i < buttons.size(); ++i) {
        buttons[i]->setText(event->size().width() > 390 ? texts[i] : "");
    }
}


