#include <qdir.h>
#include <qdebug.h>
#include <QHBoxLayout>

#include "leftwidget.h"
#include "filemanager.h"
#include "global.h"

LeftWidget::LeftWidget(QWidget *parent) : QDockWidget(parent) {
    setWindowTitle("文件浏览");

    _treeWidget = new QTreeWidget();
    _treeWidget->setHeaderHidden(true);

    _sampleDataItem = new QTreeWidgetItem(_treeWidget);
    _sampleDataItem->setText(0, "样品数据");
#if 0
    _baseLineItem = new QTreeWidgetItem(_treeWidget);
    _baseLineItem->setText(0,"基线");
#endif
    _analysisStateItem = new QTreeWidgetItem(_treeWidget);
    _analysisStateItem->setText(0, "分析状态");

    _treeWidget->setSortingEnabled(false);

    _treeWidget->insertTopLevelItem(0, _sampleDataItem);
    //    _treeWidget->insertTopLevelItem(1, _baseLineItem);
    _treeWidget->insertTopLevelItem(2, _analysisStateItem);

    setWidget(_treeWidget);

    // init file name.
    initFileName(_sampleDataItem, Global::SampleDataFloder);
#if 0
    initFileName(_baseLineItem,Global::BaseLineFolder);
#endif
    initFileName(_analysisStateItem, Global::AnalysisStateFolder);

    expandAll(_sampleDataItem);
    //    expandAll(_baseLineItem);
    expandAll(_analysisStateItem);

    Global::updateFileList();


    // connections
    connect(_treeWidget, &QTreeWidget::itemDoubleClicked,
            this, &LeftWidget::slotTreeWidgetItemClicked);

    // 右键菜单
    _contextMenu  = new QMenu(_treeWidget);
    _deleteAction = new QAction("删除", this);
    _contextMenu->addAction(_deleteAction);

    _treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(_treeWidget, &QTreeWidget::customContextMenuRequested,
            this, &LeftWidget::slotShowContextMenu);
}

void LeftWidget::reloadFileName() {
    clearAllChildItems(_sampleDataItem);
    // clearAllChildItems(_baseLineItem);
    clearAllChildItems(_analysisStateItem);

    initFileName(_sampleDataItem, Global::SampleDataFloder);
#if 0
    initFileName(_baseLineItem,Global::BaseLineFolder);
#endif
    initFileName(_analysisStateItem, Global::AnalysisStateFolder);
    // 更新文件列表
    Global::updateFileList();
}

QString LeftWidget::filePathCheck(const QString fileName, const QString folderPath) {
    QString resultFileName = fileName;

    QDir        dir(folderPath);
    QStringList files = dir.entryList(QDir::Files);
    for (const QString &existedFileName : files) {
        QFileInfo fileInfo(existedFileName);
        if (fileName == fileInfo.baseName()) {
            QDateTime currentDateTime = QDateTime::currentDateTime();
            QString   formattedTime   = currentDateTime.toString("yyyy_MM_dd_HH_mm_ss");

            resultFileName = fileName + QString("_") + formattedTime;
            break;
        }
    }

    return resultFileName;
}

void LeftWidget::initData() {
    //    const QString folderPath = QDir::currentPath()+"/../experiment_data";
    const QString folderPath = Global::SampleDataFloder;
#if 1
    QDir dir(folderPath);
    if (!dir.exists()) {
        qWarning() << "文件夹不存在: " << folderPath;
        return;
    }

    // 遍历文件
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
    for (const QFileInfo &fileInfo : fileList) {
        QFile file(fileInfo.absoluteFilePath());
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QString content = file.readAll();
            qDebug() << "读取文件 " << fileInfo.absoluteFilePath() << " 内容: " << content;
            file.close();
            // 写入文件操作示例：这里简单在文件末尾追加一行内容
            if (file.open(QIODevice::Append | QIODevice::Text)) {
                file.write("\n这是通过递归写入添加的内容");
                qDebug() << "已向文件 " << fileInfo.absoluteFilePath() << " 写入内容";
                file.close();
            } else {
                qWarning() << "无法打开文件进行写入: " << fileInfo.absoluteFilePath();
            }
        } else {
            qWarning() << "无法打开文件进行读取: " << fileInfo.absoluteFilePath();
        }
    }
#endif
}
void LeftWidget::slotTreeWidgetItemClicked(QTreeWidgetItem *item, int column) {
    qDebug() << "item clicked:" << item->text(0) << column;

    if (Global::Mode::Analysis != Global::_mode) {
        return;
    }

    QString fileName;
    // 获取父节点
    QTreeWidgetItem *parentItem = item->parent();
    if (parentItem) {
        qDebug() << "parent item text:" << parentItem->text(0);
        if (parentItem == _sampleDataItem) {
            fileName = Global::SampleDataFloder + "/" + item->text(0);
#if 0
        }else if(parentItem == _baseLineItem){
            fileName =Global::BaseLineFolder +  "/" +item->text(0);
#endif
        } else if (parentItem == _analysisStateItem) {
            fileName = Global::AnalysisStateFolder + "/" + item->text(0);
        }
    } else {
        qDebug() << "item has no parent (it is a top-level item)";
        return;
    }

    emit sigSendAnalysisFileName(fileName);
}
void LeftWidget::initFileName(QTreeWidgetItem *parentItem, const QString &folderPath) {
    QDir        dir(folderPath);
    QStringList files = dir.entryList(QDir::Files);
    for (const QString &fileName : files) {
        QTreeWidgetItem *subItem = new QTreeWidgetItem();
        subItem->setText(0, fileName);
        subItem->setData(0, Qt::UserRole, QVariant::fromValue(folderPath + "/" + fileName));
        parentItem->addChild(subItem);
    }
}

void LeftWidget::expandAll(QTreeWidgetItem *item) {
    item->setExpanded(true);
    for (int i = 0; i < item->childCount(); ++i) {
        expandAll(item->child(i));
    }
}

void LeftWidget::clearAllChildItems(QTreeWidgetItem *parentItem) {
    int childCount = parentItem->childCount();
    for (int i = 0; i < childCount; ++i) {
        QTreeWidgetItem *childItem = parentItem->takeChild(0);
        delete childItem;
    }
}


#if 0
void LeftWidget::recursiveFolderOperation(const QString& folderPath) {
    QDir dir(folderPath);
    if (!dir.exists()) {
        qWarning() << "文件夹不存在: " << folderPath;
        return;
    }

    // 遍历文件
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
    for (const QFileInfo& fileInfo : fileList) {
        QFile file(fileInfo.absoluteFilePath());
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QString content = file.readAll();
            qDebug() << "读取文件 " << fileInfo.absoluteFilePath() << " 内容: " << content;
            file.close();

            // 写入文件操作示例：这里简单在文件末尾追加一行内容
            if (file.open(QIODevice::Append | QIODevice::Text)) {
                file.write("\n这是通过递归写入添加的内容");
                qDebug() << "已向文件 " << fileInfo.absoluteFilePath() << " 写入内容";
                file.close();
            } else {
                qWarning() << "无法打开文件进行写入: " << fileInfo.absoluteFilePath();
            }
        } else {
            qWarning() << "无法打开文件进行读取: " << fileInfo.absoluteFilePath();
        }
    }

    // 递归遍历子文件夹
    QFileInfoList subDirList = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const QFileInfo& subDirInfo : subDirList) {
        recursiveFolderOperation(subDirInfo.absoluteFilePath());
    }
}
#endif

void LeftWidget::slotShowContextMenu(const QPoint &pos) {
    QPoint globalPos = _treeWidget->mapToGlobal(pos);
    _contextMenu->exec(globalPos);

    // 获取当前选中的项
    QTreeWidgetItem *currentItem = _treeWidget->itemAt(pos);
    if (currentItem == nullptr) {
        return;
    }

    QString filePath = currentItem->data(0, Qt::UserRole).toString();
    if (filePath.isEmpty()) {
        return;
    }
    // qDebug() << "file:" << filePath;
    if (QFile::remove(filePath)) {
        qDebug() << "文件删除成功:" << filePath;
    } else {
        qWarning() << "文件删除失败:" << filePath;
    }

    reloadFileName();
}
