#include <qgspoint.h>
#include "LampWindDataItem.h"
#include "BaseTool.h"
#include <QFileInfo>
#include "ManualLabelToolWidget.h"
#include <QgsMeshLayer.h>
#include <qgsmeshdataprovider.h>
#include <qgsmeshlayerutils.h>
#include <qgsmeshdataset.h>
#include <qgsproject.h>
#include <qgsvectorlayer.h>
#include <qgsmeshrenderersettings.h>
#include <qgscoordinatereferencesystem.h>
#include <qgsmapcanvas.h>
#include <qgsfeature.h>
#include <qgsgeometry.h>
#include <qgsfield.h>
#include <qgssymbol.h>
#include <qgssinglesymbolrenderer.h>
#include <qgslinesymbol.h>
#include <qgsmarkersymbol.h>
#include <qgsrenderer.h>
#include <qgsmarkersymbollayer.h>
#include <qgsmesheditor.h>
#include <qgsmeshdatasetgroupstore.h>
#include <qgsmeshdatasetgrouptreeview.h>
#include <qgsvectorfieldsymbollayer.h>
#include <qgsmemoryproviderutils.h>
#include <qgsgraduatedsymbolrenderer.h>
#include <omp.h>
#include "WidgetSettingClass.h"
#include "ImageOperatorBase.h"
#include "Wind2ERANc.h"
#include <QProgressDialog>
#include <QObject>
#include <QString>

LampWindDataItem::LampWindDataItem(QTreeWidget* IntreeWidget)
    :LampDataItem(IntreeWidget)
{
    timeArr.clear();
    Filename.clear();
    Filepath.clear();
    time_filepath.clear();
    selectItems.clear();
    this->treeWidget = IntreeWidget;
    this->ItemType = u8"LampWind";
}

LampWindDataItem::~LampWindDataItem()
{

}

void LampWindDataItem::InitTreeNode()
{
    // 创建根节点，子节点,父窗体： QTreeWidget* treeWidget; 
    // 其中要求子节点选中的时候，需要能够知道根节点的文本

    this->setText(0, this->Filename);
    this->setText(1,  u8"WindData");
    this->setCheckState(0, Qt::Unchecked);
    // 添加子节点
    for (const auto& key : timeArr.keys()) {
        QTreeWidgetItem* childItem1 = new QTreeWidgetItem(this); // 指定父节点为rootItem
        childItem1->setText(0, key);
        childItem1->setText(1, "");
        childItem1->setCheckState(0, Qt::Unchecked); // 在第一列添加复选框 [3](@ref)
    }
    //treeWidget->expandAll();

}

void LampWindDataItem::showData(ManualLabelToolWidget* mainWidget)
{
    // 获取当前节点的setCheckState
    if (this->checkState(0) == Qt::Checked) {
        for (int32_t i = 0; i < this->childCount(); i++) {
            int32_t tid = timeArr[this->child(i)->text(0)];
            this->ShowWindData(mainWidget, tid, this->child(i)->text(0));
        }
    }
    else {
        for (int32_t i = 0; i < this->childCount(); i++) {
            if (this->child(i)->checkState(0) == Qt::Checked) {
                int32_t tid = timeArr[this->child(i)->text(0)];
                this->ShowWindData(mainWidget, tid, this->child(i)->text(0));
            }
        }
    }
}

QString LampWindDataItem::getDescription()
{
    QString starttimestr = Timenanosecond2timeStr(info.firstTimestamp);
    QString endtimestr = Timenanosecond2timeStr(info.lastTimestamp);

    return QString(u8"FilePath: %1\nFileName: %2\nHeight:%3 \nWidth:%4 \nNum:%5, \nfirstTs:%6, \nlastTs:%7, \nminLon:%8, \nmaxLon:%9, \nminLat:%10, \nmaxLat:%11, \nESPG:%12, \nTransX:%13, %14, %15, \nTransY:%15, %16, %17, \nSize:%18 \n")
        .arg(this->Filepath).arg(this->Filename)
        .arg(info.Height).arg(info.Width).arg(info.Num)
        .arg(starttimestr).arg(endtimestr)
        .arg(info.minLon).arg(info.maxLon).arg(info.minLat).arg(info.maxLat)
        .arg(info.ESPGCODE)
        .arg(info.T11).arg(info.T12).arg(info.T13)
        .arg(info.T21).arg(info.T22).arg(info.T23)
        .arg(info.fileSize);
}

void LampWindDataItem::setSelectItems(QList<QString> selectItemName)
{



}

void LampWindDataItem::OpenFileData(QString path)
{
    // 读取数据
    this->info = getDataFileInfo(path.toUtf8().constData());
    int64_t* timeArr = new int64_t[this->info.Num];

    QString ncfilename = QFileInfo(path).completeBaseName();
    QProgressDialog* progressDialog = new QProgressDialog(this->treeWidget);
    progressDialog->setWindowTitle( (u8"请稍候")); // 设置对话框标题
    progressDialog->setLabelText( (u8"正在处理中...")); // 设置说明文字
    progressDialog->resize(150, 50);


    // 生成缓存文件地址
    FileCacheFolderPath = WidgetSettingClass::instance().getTempFolder() + "\\"+ ncfilename;
    QDir dir;
    dir.mkpath(FileCacheFolderPath);
    ERA5NetCDFConverter  cover;
    if (get_WindDataFileTimeArr(path.toUtf8().constData(), this->info, timeArr) == 0) {
        this->timeArr.clear();
        progressDialog->setRange(0, this->info.Num); // 设置进度范围，例如从0到100 [3,4](@ref)
        for (int64_t i = 0; i < this->info.Num; i++) {
            QString timeflag = Timenanosecond2timeStr(timeArr[i]);
            QString timefilename= QString(u8"\\mesh_wind_%1.nc").arg(timeflag.replace(":", "").replace(".", "M"));
            
            QString temppath = FileCacheFolderPath + "\\" + timefilename;
            time_filepath.insert(i, temppath);
            cover.convert_to_era5_netcdf(
                path.toUtf8().constData(),
                temppath.toUtf8().constData(),
                i
            );

            this->timeArr.insert(QString(u8"%1").arg(timeflag),i);
            if (i % 30 == 0) {
                progressDialog->setValue(i);
                progressDialog->show();
            }
           
        }
    }else{}

    this->hashCode = pathToHashCode_Qt(path);

    this->Filepath = path;
    this->Filename=QFileInfo(path).fileName();
    progressDialog->close();
    delArrPtr(timeArr);
}



void LampWindDataItem::ShowWindData(ManualLabelToolWidget* mainWidget, int64_t tid, QString timeStr)
{
    // 创建缓存文件
    //QString temppath = WidgetSettingClass::instance().getTempFolder() + QString(u8"\\mesh_wind_%1.nc").arg(timeStr.replace(":", "").replace(".", "M"));
    
    QgsMapCanvas* map_canvas = mainWidget->map_canvas; // 地图
    QString url = time_filepath[tid];
    QgsMeshLayer* meshLayer = new QgsMeshLayer(url, timeStr, "mdal");
    //qDebug() << temppath;
    QString EPSGStr = QString(u8"EPSG:%1").arg(info.ESPGCODE);
    // 获取数据提供者
    QgsMeshDataProvider* dp = meshLayer->dataProvider();
    if (!dp) {
        qDebug() << "Failed to get data provider!";
        return;
    }
    meshLayer->setCrs(QgsCoordinateReferenceSystem(EPSGStr));
    // 获取数据集组数量
    int gprCount = dp->datasetGroupCount();
    int targetVectorIndex = -1; // 初始化为-1，表示未找到

    // 遍历所有数据集组，寻找第一个矢量数据集
    for (int i = 0; i < gprCount; ++i) {
        QgsMeshDatasetIndex index(i, 0); // 组索引i，时间步0
        QgsMeshDatasetGroupMetadata meta = dp->datasetGroupMetadata(index);

        bool isVector = meta.isVector();
        QString name =  meta.name();

        if (isVector) {
            targetVectorIndex = i;
            break;
        }
    }

    // 如果找到了矢量数据集组
    if (targetVectorIndex != -1) {
        // 获取当前的渲染器设置
        QgsMeshRendererSettings s = meshLayer->rendererSettings();

        // 设置激活的矢量数据集组和标量数据集组
        s.setActiveVectorDatasetGroup(targetVectorIndex);
        s.setActiveScalarDatasetGroup(targetVectorIndex);

        // 将修改后的设置应用回图层
        meshLayer->setRendererSettings(s);

        qDebug() << "Successfully set active dataset group to index:" << targetVectorIndex;
    }
    else {
        qDebug() << "No vector dataset group found!";
    }

    mainWidget->AddLayers(meshLayer);
   
    map_canvas->setExtent(meshLayer->extent());
    map_canvas->refresh();
    
 


}
 