#include "formelementlist.h"
#include "qpainter.h"
#include "ui_formelementlist.h"
#include "formproduct.h"
#include "mainwindow.h"
#include "mapplication.h"
#include "msqlquerymodel.h"
#include "utils/filtertableheader.h"
#include "gui/formbaselist.h"

#include <QDrag>


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

    mModel = new MSqlQueryModel(this);
    ui->tableView->setModel(mModel);
    updateList();
    ui->tableView->setColumnWidth(0, 150);
    ui->tableView->setColumnWidth(1, 80);
    ui->tableView->setColumnWidth(2, 120);
    ui->tableView->setColumnWidth(3, 350);
    ui->tableView->setColumnWidth(4, 80);
    ui->tableView->setColumnWidth(5, 80);
    ui->tableView->setColumnWidth(6, 40);

    // Set up filter row
    auto *m_tableHeader = new FilterTableHeader(ui->tableView);
    ui->tableView->setHorizontalHeader(m_tableHeader);
    m_tableHeader->setFilter(0, "");
    m_tableHeader->setFocusColumn(0);

    ui->tableView->horizontalHeader()->model()->setHeaderData(0, Qt::Horizontal, tr("Tipo"));
    ui->tableView->horizontalHeader()->model()->setHeaderData(1, Qt::Horizontal, tr("Clase"));
    ui->tableView->horizontalHeader()->model()->setHeaderData(2, Qt::Horizontal, tr("Código"));
    ui->tableView->horizontalHeader()->model()->setHeaderData(3, Qt::Horizontal, tr("Resumen"));
    ui->tableView->horizontalHeader()->model()->setHeaderData(4, Qt::Horizontal, tr("Coste"));
    ui->tableView->horizontalHeader()->model()->setHeaderData(5, Qt::Horizontal, tr("Venta"));
    ui->tableView->horizontalHeader()->model()->setHeaderData(6, Qt::Horizontal, tr("Activo"));

    ui->tableView->setDragEnabled(true);  // Habilita el drag
    connect(ui->tableView, &QTableView::pressed, this, &formElementList::startDrag);
}

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

void formElementList::updateList()
{
    dApp->Enterprise().open();
    mModel->setQuery("SELECT TYPE1, TYPE2, CODE, TITLE, PURCHASE_PRICE, SALE_PRICE, STATE FROM ELEMENT" /*" ORDER BY CODE ASC"*/,
                     dApp->Enterprise());
    dApp->Enterprise().close();
}

void formElementList::on_buttonNew_released()
{
    formProduct *form = dApp->mainWindow()->createFormProduct(); // sustistuir por Mainwindow::createFormProduct();
    form->show();
}

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

void formElementList::on_buttonClone_released()
{

}

void formElementList::on_buttonDelete_released()
{
    QModelIndex index = ui->tableView->currentIndex();
    QAbstractItemModel *model = const_cast<QAbstractItemModel*>(index.model()); // Obtén el modelo asociado
    if (index.column() != 0)
    {
        //index = index.parent().child(index.row(), 0);
        index = model->index(index.row(), 0, index.parent());
    }
    QString ID = index.data().toString();
    QModelIndex parentIndex = index.parent();
    QModelIndex childIndex = model->index(index.row(), 2, parentIndex); // Obtén el índice del hijo
    int type = childIndex.data().toInt(); // Accede al dato
    //int type = index.parent().child(index.row(), 2).data().toInt();

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

    /*
    if (index.parent().child(index.row(), 2).data().toInt() == 0)
    {
        // TODO: borrar la composición
        if(!qry.exec(QString("DELETE FROM ELEMENTCOMPOSITION WHERE CODE = '%1';").arg(ID)))
        {
            qDebug() << "Error ejecutando el query: " << qry.lastError().text() << "\n";
            goto error;
        }
    }
    */

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

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

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

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







void formElementList::openDocument(QModelIndex index)
{
    QAbstractItemModel *model = ui->tableView->model();
    //QModelIndex item = index;
    formProduct *form = dApp->mainWindow()->createFormProduct();

    //if (index.column() != 2)
    //    item = index.parent().child(index.row(), 2);
    form->openDocument(model->index(index.row(), 2).data().toString());// item.data().toString());
    form->show();
}


void formElementList::startDrag(const QModelIndex &index) {
    if (!index.isValid())
        return;

    // Crear datos MIME
    QMimeData *mimeData = new QMimeData();
    QString data = mModel->data(index).toString();
    mimeData->setText(data);

    // Iniciar arrastre
    QDrag *drag = new QDrag(ui->tableView);
    drag->setMimeData(mimeData);

    // Crear un ícono para el cursor
    QPixmap pixmap(100, 30);
    pixmap.fill(Qt::transparent); // Fondo transparente

    QPainter painter(&pixmap);
    painter.setBrush(Qt::yellow);
    painter.drawRoundedRect(0, 0, pixmap.width(), pixmap.height(), 5, 5);

    painter.setPen(Qt::black);
    painter.drawText(pixmap.rect(), Qt::AlignCenter, data);
    painter.end();

    drag->setPixmap(pixmap); // Asignar el ícono al cursor
    //drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2)); // Centro del ícono como punto caliente


    drag->exec(Qt::MoveAction);
}

