#include "ToolBoxWidget.h"
#include <QObject>
#include <QPushButton>
#include "QToolAbstract.h"
#include <QMenu>
#include "ui_ToolBoxWidget.h"
#include <QStringList>
#include <QDir>
#include <QFileInfo>



#ifdef Q_OS_WIN
#include <windows.h>
#include <WinBase.h>
#endif

#ifdef Q_OS_UNIX
#include <dlfcn.h>
#endif

ToolBoxWidget::ToolBoxWidget(LAMPMainWidget::RasterMainWidget* mainWindows, QWidget *parent)
    : QWidget(parent), ui(new Ui::ToolBoxWidget), _mainWindows(mainWindows)
{
    ui->setupUi(this);
    setContextMenuPolicy(Qt::CustomContextMenu);  // 设置右键快捷菜单
    QObject::connect(this, SIGNAL(addBoxToolItemSIGNAL(QToolAbstract*)), this, SLOT(addBoxToolItemSLOT(QToolAbstract*)));

}

ToolBoxWidget::~ToolBoxWidget()
{}

void ToolBoxWidget::initMenu()
{
    contextmenu = new QMenu(this);
    //QAction* action1 = contextmenu->addAction(tr(u8"添加工具箱"));
    
}

void ToolBoxWidget::initToolbox(QString dlltoolPath)
{
    // 读取dll 文件，

    QDir dir(dlltoolPath);  // 获取当前工作目录

    // 设置文件过滤规则，只查找包含 "plugin_" 的 dll 文件
    QStringList filters;
    filters << "PluginTool_*.dll";
    
    // 获取当前目录下所有符合过滤规则的文件
    QFileInfoList files = dir.entryInfoList(filters, QDir::Files);
    for (const QFileInfo& fileInfo : files) {
        QString plugpath =fileInfo.absoluteFilePath();
        qDebug() << "Found DLL:" << plugpath;
        //continue;
        QString pluginname = fileInfo.fileName();
        typedef void (*Reg)(LAMPMainWidget::RasterMainWidget* mainwindows, ToolBoxWidget* toolbox);
        Reg fun = nullptr;

        if (!pluginname.toLower().startsWith("plugintool_"))
            return ;
        if (!pluginname.toLower().endsWith(".dll"))
            return ;
         
        HMODULE hmodel = LoadLibrary(LPCWSTR(plugpath.utf16()));
        qDebug() << "Error Code :" + QString::number(GetLastError());
        if (hmodel) {
            qDebug() << "find fun RegisterPreToolBox started!!!";
            fun = (Reg)GetProcAddress(hmodel, "RegisterPreToolBox");
            qDebug() << "find fun RegisterPreToolBox started!!!";
            if (fun) {
                qDebug() << "loading Plugin started!!!";
                fun(this->_mainWindows, this);
                qDebug() << "loading Plugin finished  : " << plugpath;
            }
            else {
                FreeLibrary(hmodel);
                qDebug() << "do not find Register function  Plugin: " << plugpath;
                continue ;
            }
        }
        else {
            qDebug() << "loading Plugin dll Failure: " << plugpath;

        }
    }

}


void ToolBoxWidget::addBoxToolItemSLOT(QToolAbstract* item)
{
    QVector<QString> xnodepath = item->getToolXpath();
    QString toolName = item->getToolName();

    QTreeWidgetItem* parentItem = findOrCreateParentItem(xnodepath);

    // 检查该父项是否已经绑定了 toolButton
    if (parentItem && ui->treeWidgetToolBox->itemWidget(parentItem, 0) == nullptr) {

        toollist.append(QToolboxTreeWidgetItem(ui->treeWidgetToolBox,parentItem,item));
        

        //QTreeWidgetItem* actionItem = new QTreeWidgetItem(parentItem);
        //parentItem->addChild(actionItem);
        //actionItem->setText(0,toolName);
        //QIcon icon(QString::fromUtf8(":/ToolBoxWidget/toolicon"));
        //QPushButton* button = new QPushButton(ui->treeWidgetToolBox);
        //button->setIcon(icon);
        //button->setText(toolName);
        //button->setLayoutDirection(Qt::LeftToRight);
        //button->setStyleSheet("QPushButton { text-align: left; }");
        //ui->treeWidgetToolBox->setItemWidget(actionItem, 0, button);
        //connect(button, SIGNAL(clicked()), item, SLOT(excute()));
        //item->setParent(ui->treeWidgetToolBox);
        //qDebug() << "ToolButton bound to parent:" << actionItem->text(0);
    }
    else {
        qDebug() << "ToolButton already bound to parent:" << parentItem->text(0);
    }
}


// 根据路径查找或创建父项
QTreeWidgetItem* ToolBoxWidget::findOrCreateParentItem( QVector<QString>& path) {
    QTreeWidgetItem* currentItem = nullptr;

    // 从树的顶层开始查找
    for ( QString& nodeName : path) {
        if (currentItem == nullptr) {
            // 如果是顶级节点
            currentItem = findOrCreateTopLevelItem(nodeName);
        }
        else {
            // 如果是子节点，查找当前父项下是否存在该子节点
            currentItem = findChildItemByName(currentItem, nodeName);
            if (currentItem == nullptr) {
                currentItem = new QTreeWidgetItem(currentItem);
                currentItem->setText(0, nodeName);
            }
        }
    }

    return currentItem;
}

// 查找顶级节点，如果没有找到则创建
QTreeWidgetItem* ToolBoxWidget::findOrCreateTopLevelItem( QString& name) {
    for (int i = 0; i < ui->treeWidgetToolBox->topLevelItemCount(); ++i) {
        QTreeWidgetItem* item = ui->treeWidgetToolBox->topLevelItem(i);
        if (item->text(0) == name) {
            return item;
        }
    }

    // 如果没有找到，创建新的顶级节点
    QTreeWidgetItem* newItem = new QTreeWidgetItem(ui->treeWidgetToolBox);
    QIcon icon(QString::fromUtf8(":/RasterProcessTool/toolboxIcon"));
    newItem->setIcon(0,icon);
    newItem->setTextAlignment(0, Qt::AlignLeft);
    newItem->setText(0, name);
    return newItem;
}

// 查找子节点，如果没有找到则返回 nullptr
QTreeWidgetItem* ToolBoxWidget::findChildItemByName(QTreeWidgetItem* parentItem,  QString& name) {
    for (int i = 0; i < parentItem->childCount(); ++i) {
        QTreeWidgetItem* childItem = parentItem->child(i);
        if (childItem->text(0) == name) {
            return childItem;
        }
    }
    return nullptr;
}

void ToolBoxWidget::OpenToolboxManagerWidget()
{

}

QToolboxTreeWidgetItem::QToolboxTreeWidgetItem(QTreeWidget* IntreeWidgetToolBox, QTreeWidgetItem* InparentItem, QToolAbstract* Initem)
{
    this->parentItem = InparentItem;
    this->item = Initem;
    this->actionItem = new QTreeWidgetItem(parentItem);
    this->button = new QPushButton(IntreeWidgetToolBox);

    QString toolName = item->getToolName();
    parentItem->addChild(actionItem);
    actionItem->setText(0, toolName);
    QIcon icon(QString::fromUtf8(":/RasterProcessTool/toolicon.png"));
    button->setIcon(icon);
    button->setText(toolName);
    button->setLayoutDirection(Qt::LeftToRight);
    button->setStyleSheet("QPushButton { text-align: left; font-weight: blob; }");
    IntreeWidgetToolBox->setItemWidget(actionItem, 0, button);
    QObject::connect(button, SIGNAL(clicked()), item, SLOT(excute()));
    item->setParent(IntreeWidgetToolBox);
    qDebug() << "ToolButton bound to parent:" << actionItem->text(0);

}

QToolboxTreeWidgetItem::~QToolboxTreeWidgetItem()
{
}

QTreeWidgetItem* QToolboxTreeWidgetItem::getTreeWidgetItem()
{
    return this->actionItem;
}

QPushButton* QToolboxTreeWidgetItem::getPushButton()
{
    return this->button;
}

QToolAbstract* QToolboxTreeWidgetItem::getToolAbstract()
{
    return this->item;
}

QTreeWidgetItem* QToolboxTreeWidgetItem::getParantTreeWidgetItem()
{
    return this->parentItem;
}
