#include "QBatchStaticEchoDialog.h"
#include <QMessageBox>
#include <QFileInfo>
#include <QDebug>
//#include "EchoReader.h"


QStringList readFilePaths(const QString& filePath) {
    QStringList pathList; // 用于存储文件路径的列表

    // 1. 创建QFile对象并打开文件
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件:" << file.errorString();
        return pathList; // 返回空列表
    }

    QTextStream in(&file);

    in.setCodec("UTF-8");  

    while (!in.atEnd()) {
        QString line = in.readLine().trimmed(); // 读取一行并去除首尾空白字符
        if (!line.isEmpty()) { // 确保不是空行
            pathList.append(line);
        }
    }

    // 4. 关闭文件
    file.close();

    return pathList;
}


QBatchStaticEchoDialog::QBatchStaticEchoDialog(QWidget* parent)
    : QDialog(parent)
{
    setupUI();
    setupConnections();
}

QBatchStaticEchoDialog::~QBatchStaticEchoDialog()
{
    // Qt的父子对象机制会自动处理内存释放
}

void QBatchStaticEchoDialog::setupUI()
{
    // 设置对话框属性
    setWindowTitle(u8"风场数据处理");
    setMinimumSize(600, 500);

    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);

    // 创建文件列表区域
    QLabel* listLabel = new QLabel(u8"文件列表:", this);
    fileListWidget = new QListWidget(this);
    fileListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); // 支持多选

    // 创建按钮区域
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    addButton = new QPushButton(u8"添加文件", this);
    addTextButton = new QPushButton(u8"添加数据条目文件", this);
    removeButton = new QPushButton(u8"移除选中", this);
    processButton = new QPushButton(u8"开始处理", this);

    buttonLayout->addWidget(addButton);
    buttonLayout->addWidget(addTextButton);
    buttonLayout->addWidget(removeButton);
    buttonLayout->addStretch(); // 添加弹性空间
    buttonLayout->addWidget(processButton);

    // 创建复选框区域
    QHBoxLayout* checkBoxLayout = new QHBoxLayout();
    statisticCheckBox = new QCheckBox(u8"风能计算", this);
    echoCheckBox = new QCheckBox(u8"风能统计", this);
    statisticCheckBox->setChecked(true); // 默认选中

    checkBoxLayout->addWidget(statisticCheckBox);
    checkBoxLayout->addWidget(echoCheckBox);
    checkBoxLayout->addStretch();

    // 创建进度条区域
    QLabel* progressLabel = new QLabel(u8"处理进度:", this);
    progressBar = new QProgressBar(this);
    progressBar->setMinimum(0);
    progressBar->setMaximum(100);
    progressBar->setValue(0);
    progressBar->setVisible(true); // 默认显示

    // 将组件添加到主布局
    mainLayout->addWidget(listLabel);
    mainLayout->addWidget(fileListWidget);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addLayout(checkBoxLayout);
    mainLayout->addWidget(progressLabel);
    mainLayout->addWidget(progressBar);

    setLayout(mainLayout);
}

void QBatchStaticEchoDialog::setupConnections()
{
    // 连接按钮信号槽
    connect(addButton, &QPushButton::clicked, this, &QBatchStaticEchoDialog::onAddFiles);
    connect(addTextButton, &QPushButton::clicked, this, &QBatchStaticEchoDialog::onAddTextFiles);
    connect(removeButton, &QPushButton::clicked, this, &QBatchStaticEchoDialog::onRemoveFile);
    connect(processButton, &QPushButton::clicked, this, &QBatchStaticEchoDialog::onProcessFiles);
}

void QBatchStaticEchoDialog::onAddFiles()
{
    // 使用QFileDialog选择多个文件[2,5](@ref)
    QStringList files = QFileDialog::getOpenFileNames(
        this,
        u8"选择要处理的文件",
        QDir::homePath(),
        u8"All Files (*.*)"
    );

    if (!files.isEmpty()) {
        foreach(QString file, files) {
            QFileInfo fileInfo(file);
            // 避免重复添加
            if (fileListWidget->findItems(fileInfo.fileName(), Qt::MatchExactly).isEmpty()) {
                QListWidgetItem* item = new QListWidgetItem(fileInfo.fileName());
                item->setData(Qt::UserRole, file); // 存储完整路径
                fileListWidget->addItem(item);
            }
        }
    }
}

void QBatchStaticEchoDialog::onAddTextFiles()
{
    QString filePath = QFileDialog::getOpenFileName(
        this,                    // 父窗口
        u8"请选择一个文件",            // 对话框标题
        "./",                       // 初始目录（这里设为程序当前目录）
        u8"txt (*.txt);;" // 文件过滤器
    );

    QStringList dataliststr = readFilePaths(filePath);
    foreach(QString file, dataliststr) {
        QFileInfo fileInfo(file);
        if (fileInfo.exists()) {
            // 避免重复添加
            if (fileListWidget->findItems(fileInfo.fileName(), Qt::MatchExactly).isEmpty()) {
                QListWidgetItem* item = new QListWidgetItem(fileInfo.fileName());
                item->setData(Qt::UserRole, file); // 存储完整路径
                fileListWidget->addItem(item);
            }
        }
    }
}

void QBatchStaticEchoDialog::onRemoveFile()
{
    // 移除选中的项目[3](@ref)
    QList<QListWidgetItem*> selectedItems = fileListWidget->selectedItems();
    foreach(QListWidgetItem * item, selectedItems) {
        delete fileListWidget->takeItem(fileListWidget->row(item));
    }
}

void QBatchStaticEchoDialog::onProcessFiles()
{
    QString selectedDir = "";
    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::Directory); // 设置模式为选择目录
    dialog.setOption(QFileDialog::ShowDirsOnly, true);
    dialog.setViewMode(QFileDialog::Detail); // 设置视图为详细信息模式
    if (dialog.exec() == QDialog::Accepted) {
        selectedDir=dialog.selectedFiles().first();
    }
    else {
        return;
    }



    if (fileListWidget->count() == 0) {
        QMessageBox::warning(this, u8"警告", u8"请先添加要处理的文件！");
        return;
    }

    bool enableStatistic = statisticCheckBox->isChecked();
    bool enableEcho = echoCheckBox->isChecked();

    if (!enableStatistic && !enableEcho) {
        QMessageBox::warning(this, u8"警告", u8"请至少选择一个处理选项（统计或接回波）！");
        return;
    }
 
    progressBar->setValue(0);
    int totalFiles = fileListWidget->count();
    for (int i = 0; i < totalFiles; ++i) {

        QListWidgetItem* item = fileListWidget->item(i);
        QString filePath = item->data(Qt::UserRole).toString();

        if (this->echoCheckBox->isChecked()) {
            QString echodatafilepath = QString(u8"%1\\%2").arg(selectedDir).arg(QFileInfo(filePath).fileName());
            std::string infilepath = filePath.toUtf8().constData();
            std::string outfilepath = echodatafilepath.toUtf8().constData();
            //ParseEchoData(infilepath, outfilepath);

        }
        
        if (this->statisticCheckBox->isChecked()) {
            QString staticfilepath = QString(u8"%1\\%2").arg(selectedDir).arg(u8"staticResult.dat");
            std::string infilepath = filePath.toUtf8().constData();
            std::string outfilepath = staticfilepath.toUtf8().constData();
            //StaticEchoData(infilepath, outfilepath);
            //ReadEchoInfoFile(outfilepath);
        }
        // 更新进度
        int progress = (i + 1) * 100 / totalFiles;
        progressBar->setValue(progress);
    }

    QMessageBox::information(this, u8"完成", u8"文件处理完成！");
}

void QBatchStaticEchoDialog::updateProgress(int value)
{
    progressBar->setValue(value);
}