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

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

LeftWidget::LeftWidget(QWidget *parent ): QDockWidget(parent)
{
    //    setStyleSheet("background-color: yellow;");

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

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

    _treeWidget->setSortingEnabled(false);

    _treeWidget->addTopLevelItem(_sampleDataItem);
    _treeWidget->addTopLevelItem(_baseLineItem);
    _treeWidget->addTopLevelItem(_analysisStateItem);

    setWidget(_treeWidget);

    //init file name.
    initFileName(_sampleDataItem,FileManager::SampleDataFloder);
    initFileName(_baseLineItem,FileManager::BaseLineFolder);
    initFileName(_analysisStateItem,FileManager::AnalysisStateFolder);

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

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

void LeftWidget::initData()
{
    const QString folderPath = QDir::currentPath()+"/../experiment_data";
#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::instance()->getMode()){
        return;
    }

    QString fileName;
    // 获取父节点
    QTreeWidgetItem *parentItem = item->parent();
    if (parentItem) {
        qDebug() << "parent item text:" << parentItem->text(0);
        if(parentItem == _sampleDataItem){
            fileName =FileManager::SampleDataFloder + "/" + item->text(0);
        }else if(parentItem == _baseLineItem){
            fileName =FileManager::BaseLineFolder +  "/" +item->text(0);
        }else if(parentItem == _analysisStateItem){
            fileName =FileManager::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);
        //        _sampleDataItem->addChild(new QTreeWidgetItem(0,fileName));
        parentItem->addChild(subItem);
    }

#if 0
    // 获取文件夹中的所有文件名
    QStringList files = dir.entryList(QDir::Files);  // 只列出文件
    qDebug() << "Files in the current directory:";
    foreach (const QString &fileName, files)
    {
        qDebug() << fileName;
    }
#endif
}

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

#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
