#include "QtSARAntModelSetting.h"
#include "AllHead.h"
#include <QMessageBox>
#include <opencascade/BRepBuilderAPI_MakeSolid.hxx>
#include <opencascade/BRepPrimAPI_MakePrism.hxx>
#include <opencascade/BRepPrimAPI_MakePrism.hxx>
#include "OCCTBase.h"

antModelClass::antModelClass(QString filpath)
{
	QMessageBox::information(nullptr, QString::fromUtf8(u8"模型坐标系提示"), QString::fromUtf8(u8"模型的Y轴为飞行方向，Z轴为雷达指向"));
	if (QFile::exists(filpath)) {
		ReadTopoDs_Shape(filpath, this->antModel); 
	}
	else {
		this->createDefaultAntModel();
	}
}

antModelClass::antModelClass()
{
	QMessageBox::information(nullptr, QString::fromUtf8(u8"模型坐标系提示"), QString::fromUtf8(u8"模型的Y轴为飞行方向，Z轴为雷达指向"));
	this->createDefaultAntModel();
}

antModelClass::~antModelClass()
{
	this->antModelShow.Nullify();
	this->antModel.Nullify();
}

void antModelClass::initAxis()
{
	gp_Pnt rotationCenter(0, 0, 0);
	gp_Ax1 rotationAxis_X(rotationCenter, gp_Dir(1.0, 0.0, 0.0));
	gp_Ax1 rotationAxis_Y(rotationCenter, gp_Dir(0.0, 1.0, 0.0));
	gp_Ax1 rotationAxis_Z(rotationCenter, gp_Dir(0.0, 0.0, 1.0));
}

//
// 根据侧视角摆动时，应该是在卫星飞行与雷达照射的平面上进行摆动
//
void antModelClass::applyAntModel(
	double Sx, double Sy, double Sz, 
	double Vx , double Vy , double Vz ,	
	double incidenceAngle, double AzAngle, bool isRIGHT) {

	FEKOBase::SatelliteState satepos{
		FEKOBase::SatellitePosition{Sx,Sy,Sz},
		FEKOBase::SatelliteVelocity{Vx,Vy,Vz},
	};

	FEKOBase::FEKOantPitionDirect antposition_Direct;
	TopoDS_Shape inDs = this->antModel;
	TopoDS_Shape outDs = FEKOBase::SatellitePos2FEKOAntPos(satepos, incidenceAngle, AzAngle, isRIGHT, &antposition_Direct, inDs);
	Handle(AIS_Shape) aisShape = new AIS_Shape(outDs);
	this->antModelShow = aisShape;
	this->antposition_Direct = antposition_Direct;
	
	return;
}

void antModelClass::createDefaultAntModel()
{

	// 创建三个方向的箭头
	//TopoDS_Shape arrow1 = CreateArrow(gp_Dir(1, 0, 0), 0.3, 0.1); // X方向 
	TopoDS_Shape arrow2 = CreateArrow(gp_Dir(0, 1, 0), 1, 0.1); // Y方向
	TopoDS_Shape arrow3 = CreateArrow(gp_Dir(0, 0, 1), 1.5, 0.1); // Z方向

	// 创建雷达模型

	gp_Ax2 modelCoor = gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0));

	//TopoDS_Shape ant_pyramid = BRepPrimAPI_MakeWedge(modelCoor, 0.1, 0.1, 1.0,-1.0,-1.0,1.0,1.0).Shape();


	// 创建一个包含所有箭头的复合体
	TopoDS_Compound compound;
	BRep_Builder builder;


	builder.MakeCompound(compound);
	//builder.Add(compound, arrow1);
	builder.Add(compound, arrow2);
	builder.Add(compound, arrow3);
	//builder.Add(compound, ant_pyramid);
	this->antModel = compound; // 雷达三维模型

}

FEKOBase::FEKOantPitionDirect antModelClass::get_antposition_Direct()
{
	return this->antposition_Direct;
}

Handle(AIS_InteractiveObject) antModelClass::get_antModelShow()
{
	return this->antModelShow;
}

antModelClass antModelClassFactory()
{
	QString filepath = getOpenFilePath(
		nullptr,
		QString::fromUtf8(u8"导入雷达模型"),
		QString::fromUtf8(u8"STL Files (*.stl);;STL Files (*.stla);;step Files (*.stp);;step Files (*.step);;IGES Files (*.iges);;IGES Files (*.igs)"));
	antModelClass result(filepath);     
	return result;
}
 

QtSARAntModelSettingClass::QtSARAntModelSettingClass(QWidget* parent)
{
	ui.setupUi(this);
	this->simulationparams = std::make_shared<FEKOBase::FEKOSimulationDataparams>(); // 参数初始化
	this->ui.lineEdit_TaskName->setText(this->simulationparams->taskName);
	this->ui.lineEdit_farsourcePath->setText(this->simulationparams->AntennaRadiationFileName);
 
	this->Widgetfreqsetting=new QtFreqParamsSetting(this);
	this->WidgetImageSetting = new QtWidgetsClass_ImageSetting(this);
	// 添加成像模式
	this->WidgetISARMode = new QtWidgetsClass_ISAR();
	this->WidgetCirCleSARMode = new QtWidgetsClass_CircleSAR();
	this->WidgetScanMode = new	QtWidgetsClass_Scan();
	this->WidgetstriMode = new	QtWidgetsClass_Strip();



	QObject::connect(this->WidgetISARMode, SIGNAL(OKClick()), this, SLOT(OKClickISAR( )));
	QObject::connect(this->WidgetstriMode,SIGNAL(OKClick()),this,SLOT(OKClickStrip( )));
	QObject::connect(this->WidgetCirCleSARMode, SIGNAL(OKClick()), this, SLOT(OKClickCircleSAR( )));
	QObject::connect(this->WidgetScanMode, SIGNAL(OKClick()), this, SLOT(OKClickScane( )));
	QObject::connect(this->Widgetfreqsetting, SIGNAL(OKClick()), this, SLOT(OKClickFreqSetting(  )));
	QObject::connect(this->WidgetImageSetting, SIGNAL(OKClick()), this, SLOT(OKClickImageSetting(  )));
	// 添加频率
	//this->Widgetfreqsetting->freqParams = this->freqSetting;
	this->ui.tabWidget->removeTab(0);
	this->ui.tabWidget->insertTab(0, this->Widgetfreqsetting, u8"频率设置");
	this->ui.tabWidget->removeTab(2);
	this->ui.tabWidget->insertTab(2, this->WidgetImageSetting, u8"成像设置");

	this->ui.comboBox_ImageMode->addItem(FEKOBase::FEKOImageModeenumToString(FEKOBase::FEKOImageMode::Strip));
	this->ui.comboBox_ImageMode->addItem(FEKOBase::FEKOImageModeenumToString(FEKOBase::FEKOImageMode::Scane));
	this->ui.comboBox_ImageMode->addItem(FEKOBase::FEKOImageModeenumToString(FEKOBase::FEKOImageMode::ISAR));
	this->ui.comboBox_ImageMode->addItem(FEKOBase::FEKOImageModeenumToString(FEKOBase::FEKOImageMode::CircleSAR));

	this->ui.comboBox_LookSide->addItem(u8"左视");
	this->ui.comboBox_LookSide->addItem(u8"右视");


	// 绘制模型
	this->antModel = nullptr;
	this->myContext = nullptr;
	this->ui.tabantModeMove->setEnabled(false);

}

QtSARAntModelSettingClass::~QtSARAntModelSettingClass()
{

}

void QtSARAntModelSettingClass::removeModeSettingWidget()
{
	this->ui.tabWidget->removeTab(1);
	this->FEKOAntPoselist.clear();
}

void QtSARAntModelSettingClass::switchStripImageParamsWeight()
{
	this->removeModeSettingWidget();
	this->ui.tabWidget->insertTab(1, this->WidgetstriMode, u8"条带成像设置");
	this->ui.comboBox_LookSide->setEnabled(true);
}

void QtSARAntModelSettingClass::switchScanImageParamsWeight()
{
	this->removeModeSettingWidget();
	this->ui.tabWidget->insertTab(1, this->WidgetScanMode, u8"扫描成像设置");
	this->ui.comboBox_LookSide->setEnabled(true);

}

void QtSARAntModelSettingClass::switchISARImageParamsWeight()
{
	this->removeModeSettingWidget();
	this->ui.tabWidget->insertTab(1, this->WidgetISARMode, u8"ISAR成像设置");
	this->ui.comboBox_LookSide->setEnabled(false);
}

void QtSARAntModelSettingClass::switchCircleSARImageParamsWeight()
{
	this->removeModeSettingWidget();
	this->ui.tabWidget->insertTab(1, this->WidgetCirCleSARMode, u8"圆迹SAR成像设置");
	this->ui.comboBox_LookSide->setEnabled(false);
}

void QtSARAntModelSettingClass::ReferenceWindows()
{
	this->ui.lineEdit_TaskName->setText(this->simulationparams->getTaskName());
	//this->ui.comboBox_ImageMode->setCurrentText(FEKOBase::FEKOImageModeenumToString(this->simulationparams->imagemode));

	switch (this->simulationparams->imagemode) {
	case FEKOBase::FEKOImageMode::Strip:
		this->ui.comboBox_ImageMode->setCurrentIndex(0);
		break;
	case FEKOBase::FEKOImageMode::Scane:
		this->ui.comboBox_ImageMode->setCurrentIndex(1);
		break;
	case FEKOBase::FEKOImageMode::ISAR:
		this->ui.comboBox_ImageMode->setCurrentIndex(2);
		break;
	case FEKOBase::FEKOImageMode::CircleSAR:
		this->ui.comboBox_ImageMode->setCurrentIndex(3);
		break;
	}
	
	if (this->simulationparams->isRight) {
		this->ui.comboBox_LookSide->setCurrentIndex(1);
	}
	else {
		this->ui.comboBox_LookSide->setCurrentIndex(0);
	}

	this->ui.lineEdit_refRange->setText(QString::number(this->simulationparams->refRange));
	this->ui.lineEdit_incangle->setText(QString::number(this->simulationparams->incangle));

	emit this->simulationparams->FEKOSimulationDataparamsChanged(); // 将参数修改发送到不同界面中

	this->generator_FEKOSatelliteParams();

}

void QtSARAntModelSettingClass::refreshFEKOSimulationParams()
{
	this->simulationparams->taskName = this->ui.lineEdit_TaskName->text();
	this->simulationparams->AntennaRadiationFileName = this->ui.lineEdit_farsourcePath->text();
	this->simulationparams->isRight = this->ui.comboBox_LookSide->currentIndex() == 1;
	this->simulationparams->imagemode=FEKOBase::FEKOImageModeString2Enum(this->ui.comboBox_ImageMode->currentText().trimmed());
	this->simulationparams->refRange = this->ui.lineEdit_refRange->text().toDouble();
	this->simulationparams->incangle = this->ui.lineEdit_incangle->text().toDouble();
}

void QtSARAntModelSettingClass::setOCCTDocument(Handle(AIS_InteractiveContext) myContext)
{
	this->myContext = myContext;

	QString antFilePath=getOpenFilePath(
		nullptr,
		QString::fromUtf8(u8"导入雷达模型"),
		QString::fromUtf8(u8"STL Files (*.stl);;STL Files (*.stla);;step Files (*.stp);;step Files (*.step);;IGES Files (*.iges);;IGES Files (*.igs)"));
	
	if (isExists(antFilePath)) {
		this->antModel = new antModelClass(antFilePath);
	}
	else {
		this->antModel = new antModelClass();
	}
	this->ui.tabantModeMove->setEnabled(true);
}


void QtSARAntModelSettingClass::OKClickISAR( )
{
 
	this->refreshFEKOSimulationParams();
	this->generator_FEKOSatelliteParams();
	// 绘制展示模型
	if (this->myContext.IsNull()) {
		this->ui.horizontalSlider_PRF->setValue(0);
		//this->on_horizontalSlider_PRF_valueChanged(0);
	}
	emit this->simulationparams->FEKOSimulationDataparamsChanged();
}
void QtSARAntModelSettingClass::OKClickStrip( )
{
	qDebug() << u8"计算 Strip...";
	this->refreshFEKOSimulationParams();
	this->generator_FEKOSatelliteParams();
	if (this->myContext.IsNull()) {
		this->ui.horizontalSlider_PRF->setValue(0);
	}
	emit this->simulationparams->FEKOSimulationDataparamsChanged();
}
void QtSARAntModelSettingClass::OKClickCircleSAR( )
{
	this->refreshFEKOSimulationParams();
	this->generator_FEKOSatelliteParams();
	// 绘制展示模型
	if (this->myContext.IsNull()) {
		this->ui.horizontalSlider_PRF->setValue(0);
		//this->on_horizontalSlider_PRF_valueChanged(0);
	}
	emit this->simulationparams->FEKOSimulationDataparamsChanged();

}
void QtSARAntModelSettingClass::OKClickScane( )
{
	this->refreshFEKOSimulationParams();
	this->generator_FEKOSatelliteParams();
	if (this->myContext.IsNull()) {
		this->ui.horizontalSlider_PRF->setValue(0);
	}
	emit this->simulationparams->FEKOSimulationDataparamsChanged();
}

void QtSARAntModelSettingClass::OKClickFreqSetting( )
{
	this->refreshFEKOSimulationParams();
	emit this->simulationparams->FEKOSimulationDataparamsChanged();
}

void QtSARAntModelSettingClass::OKClickImageSetting( )
{
	this->refreshFEKOSimulationParams();
	emit this->simulationparams->FEKOSimulationDataparamsChanged();
}

void QtSARAntModelSettingClass::on_comboBox_ImageMode_currentIndexChanged(int index)
{
	QString text = this->ui.comboBox_ImageMode->currentText();
	this->simulationparams->imagemode = FEKOBase::FEKOImageModeString2Enum(text.trimmed());
	if (this->simulationparams->imagemode == FEKOBase::FEKOImageMode::UNKNOW) {
		QMessageBox::information(nullptr, QString::fromUtf8(u8"错误"), QString::fromUtf8(u8"未知的成像模式"));
		return;
	}
	else if (this->simulationparams->imagemode == FEKOBase::FEKOImageMode::Strip) {
		this->switchStripImageParamsWeight();
	}
	else if (this->simulationparams->imagemode == FEKOBase::FEKOImageMode::Scane) {
		this->switchScanImageParamsWeight();
	}
	else if (this->simulationparams->imagemode == FEKOBase::FEKOImageMode::ISAR) {
		this->switchISARImageParamsWeight();
	}
	else if (this->simulationparams->imagemode == FEKOBase::FEKOImageMode::CircleSAR) {
		this->switchCircleSARImageParamsWeight();
	}
	else {
		QMessageBox::information(nullptr, QString::fromUtf8(u8"错误"), QString::fromUtf8(u8"未知的成像模式"));
	}
}

void QtSARAntModelSettingClass::on_pushButton_ffe_clicked()
{
	QtWidgetsClass_FarSourceSetting* ffeselectwindows = new QtWidgetsClass_FarSourceSetting(this);
	QObject::connect(ffeselectwindows, SIGNAL(setResultSelected(size_t, size_t, QString)), this, SLOT(SelectFFESourcePath(size_t, size_t, QString)));
	ffeselectwindows->show();
}

void QtSARAntModelSettingClass::on_comboBox_LookSide_currentIndexChanged(int index)
{
	QString lookside = this->ui.comboBox_LookSide->currentText();
	if (lookside == u8"左视") {
		this->simulationparams->isRight = false;
	}
	else {
		this->simulationparams->isRight = true;
	}
}

void QtSARAntModelSettingClass::on_horizontalSlider_PRF_valueChanged(int value)
{
	if (this->FEKOAntPoselist.size() == 0) {
		return;
	}

	this->ui.horizontalSlider_PRF->setMinimum(0);
	this->ui.horizontalSlider_PRF->setMaximum(this->FEKOAntPoselist.size()-1);
	
	
	// 移除旧
	Handle(AIS_InteractiveObject) moveShapeold = this->antModel->get_antModelShow();
	this->myContext->Remove(moveShapeold,Standard_False);
	
	// 增加新
	FEKOBase::FEKOSatelliteParams temp = this->FEKOAntPoselist[value];
	this->antModel->applyAntModel(temp.pose.pos.Px, temp.pose.pos.Py, temp.pose.pos.Pz, temp.pose.vel.Vx, temp.pose.vel.Vy, temp.pose.vel.Vz, temp.incidenceAngle, temp.AzAngle, this->simulationparams->isRight);
	Handle(AIS_InteractiveObject) moveShape = this->antModel->get_antModelShow();
	this->myContext->Display(moveShape, Standard_True);


	if (this->simulationparams->imagemode == FEKOBase::FEKOImageMode::ISAR || this->simulationparams->imagemode == FEKOBase::FEKOImageMode::CircleSAR) {
		this->ui.label_AZ_Angle->setText(u8"方位角：");
	}
	else {
		this->ui.label_AZ_Angle->setText(u8"侧摆角：");
	}
	this->ui.lineEdit_PRF_Show->setText(QString::number(temp.PRFidx));
	this->ui.lineEdit_X_Show->setText(QString::number(temp.pose.pos.Px));
	this->ui.lineEdit_Y_Show->setText(QString::number(temp.pose.pos.Py));
	this->ui.lineEdit_Z_Show->setText(QString::number(temp.pose.pos.Pz));
	this->ui.lineEdit_Az_Show->setText(QString::number(temp.AzAngle));
	this->ui.lineEdit_incangle_Show->setText(QString::number(temp.incidenceAngle));
	
	this->ui.lineEdit_X_Show->setReadOnly(true);
	this->ui.lineEdit_Y_Show->setReadOnly(true);
	this->ui.lineEdit_Z_Show->setReadOnly(true);
	this->ui.lineEdit_Az_Show->setReadOnly(true);
	this->ui.lineEdit_incangle_Show->setReadOnly(true);


}

void QtSARAntModelSettingClass::on_pushButton_OK_clicked()
{
	this->refreshFEKOSimulationParams(); // 最后更新下参数
	this->saveFEKOImageSettingXML();
	
	QString luatext = this->createLuaSciptString(0, this->FEKOAntPoselist.size());

	// 写入文件
	QString filePath = this->workSpace + QDir::separator() + this->simulationparams->taskName + QString(u8"_%1.lua").arg(FEKOBase::FEKOImageModeenumToString(this->simulationparams->imagemode));
	// 创建文件对象
	QFile file(filePath);

	// 打开文件以供写入，如果文件不存在将创建新文件
	if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
		// 创建文本流，并设置编码为UTF-8
		QTextStream stream(&file);
		stream.setCodec("UTF-8");
		stream << luatext;
		// 关闭文件
		file.close();
		// 提示文件写入成功
		QMessageBox::information(nullptr, QString::fromUtf8(u8"提示"), QString::fromUtf8(u8"文件写入成功!\n%1").arg(filePath));
		qDebug() << "File written successfully.";
	}
	else {
		qDebug() << "Could not open file for writing.";
		QMessageBox::information(nullptr, QString::fromUtf8(u8"提示"), QString::fromUtf8(u8"文件写入失败"));
	}
	// 询问用户是否关闭窗口
	QMessageBox::StandardButton reply;
	reply = QMessageBox::question(this, QString::fromUtf8(u8"提示"), QString::fromUtf8(u8"是否关闭窗口?"),
		QMessageBox::Yes | QMessageBox::No);
	if (reply == QMessageBox::Yes) {
		this->close();
	}
	else {
		return;
	}
}

void QtSARAntModelSettingClass::on_pushButton_Cancel_clicked()
{
	// 询问用户是否关闭窗口
	QMessageBox::StandardButton reply;
	reply = QMessageBox::question(this, QString::fromUtf8(u8"提示"), QString::fromUtf8(u8"是否关闭窗口?"),
		QMessageBox::Yes | QMessageBox::No);
	if (reply == QMessageBox::Yes) {
		this->close();
	}
	else {
		return;
	}
}

void QtSARAntModelSettingClass::on_lineEdit_Range_editingFinished()
{
	// 传播计算
	this->simulationparams->setRefRange(this->ui.lineEdit_refRange->text().toDouble());
	QMessageBox::StandardButton reply = QMessageBox::question(this, u8"提示", u8"是否重新计算姿态", QMessageBox::Yes | QMessageBox::No);
	if (reply == QMessageBox::Yes) {
		this->generator_FEKOSatelliteParams();
	}
	else {
		return;
	}
}

void QtSARAntModelSettingClass::SelectFFESourcePath(size_t thetaPoints, size_t phiPoints, QString ffePath)
{
	if (!isExists(ffePath)) {
		// 警告文件不存在
	QMessageBox::information(nullptr, QString::fromUtf8(u8"错误"), QString::fromUtf8(u8"文件不存在"));
		return;
	}
	QString filename = getFileNameFromPath(ffePath);
	{
		QFile sourceFile(ffePath);

		QString fullpath = QDir::cleanPath(this->workSpace + QDir::separator() + filename);
		QFile destinationFile(fullpath);

		// 打开源文件以供读取
		if (sourceFile.open(QIODevice::ReadOnly)) {
			// 打开目标文件以供写入
			if (destinationFile.open(QIODevice::WriteOnly)) {
				// 将源文件内容复制到目标文件
				QByteArray data = sourceFile.readAll();
				destinationFile.write(data);
				// 关闭文件
				destinationFile.close();
			}
			else {
				qDebug() << "Could not open destination file for writing.";
			}

			// 关闭源文件
			sourceFile.close();
		}
		else {
			qDebug() << "Could not open source file for reading.";
		}

	}


	this->ui.lineEdit_farsourcePath->setText(filename);
	this->simulationparams->setAntennaRadiationFileName(filename);
	this->simulationparams->setFarsourceThetaPoints(thetaPoints);
	this->simulationparams->setFarsourcePhiPoints(phiPoints);
 
	
}

void QtSARAntModelSettingClass::FEKOSimulationDataparamsChanged_slots()
{
	qDebug() << u8"QtSARAntModelSettingClass::bandingsetFEKOSimulationDataparams()";
	



}

void QtSARAntModelSettingClass::bandingsetFEKOSimulationDataparams()
{
	QObject::connect(this->simulationparams.get(), SIGNAL(FEKOSimulationDataparamsChanged()), this, SLOT(FEKOSimulationDataparamsChanged_slots()));

	this->Widgetfreqsetting->setFEKOSimulationDataparams(this->simulationparams);
	this->WidgetImageSetting->setFEKOSimulationDataparams(this->simulationparams);
	// 添加成像模式
	this->WidgetISARMode->setFEKOSimulationDataparams(this->simulationparams);
	this->WidgetCirCleSARMode->setFEKOSimulationDataparams(this->simulationparams);
	this->WidgetScanMode->setFEKOSimulationDataparams(this->simulationparams);
	this->WidgetstriMode->setFEKOSimulationDataparams(this->simulationparams);
	emit this->simulationparams->FEKOSimulationDataparamsChanged();
 
}


