#include "FEKOResultImport.h"
#include "BaseToolLib/FileOperator.h"
#include "SharedModuleLib/BaseUiTool.h"
#include "TaskXml/TaskTreeClass.h"
#include "EchoTableEditWindow.h"
#include <QFileDialog>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include <boost/filesystem.hpp>
#include <QStandardItemModel>
#include <QStringListModel>
#include <QMessageBox>
#include <unordered_set>
#include <QProcess>
#include <QDebug>
#include "CMDExcuteApp.h"
#include <QtCore>
#include <QtXml>
#include <QDomDocument>

FEKOResultImport::FEKOResultImport(QWidget* parent)
{
	//this->setAttribute(Qt::WidgetAttribute::WA_DeleteOnClose);
	//this->setWindowModality(Qt::WindowModality::WindowModal);
	this->ui.setupUi(this);
	this->ListViewmodel = new QStandardItemModel(this);
	this->ui.listView->setModel(this->ListViewmodel);
	this->selectListViewmodel = new QStandardItemModel(this);
	this->selectListViewmodel->clear();
	this->ListViewmodel->clear();
	this->p = nullptr;
}

FEKOResultImport::~FEKOResultImport()
{
	if (nullptr == this->ListViewmodel || NULL == this->ListViewmodel) {}
	else {
		this->ListViewmodel->clear();
		delete this->ListViewmodel;
		this->ListViewmodel = nullptr;
	}
	if (nullptr == this->selectListViewmodel || NULL == this->selectListViewmodel) {}
	else {
		this->selectListViewmodel->clear(); // 释放所有对象的内存
		delete this->selectListViewmodel;
		this->selectListViewmodel = nullptr;
	}
	if (nullptr == this->p) {}
	else {
		this->p->close();
		//delete this->p;
		this->p = nullptr;
	}
}

QString FEKOResultImport::getFEKOPreFileName()
{
	return this->FEKOPreFileName;
	return QString();
}

int FEKOResultImport::setFEKOPreFileName(QString preFileName)
{
	this->FEKOPreFileName = preFileName;
	return 0;
}

int FEKOResultImport::setNearFieldNames(std::vector<QString> nearFieldNames)
{
	this->nearFieldNames.clear();
	this->nearFieldNames.shrink_to_fit();
	this->nearFieldNames = nearFieldNames;
	return 0;
}

std::vector<QString> FEKOResultImport::getNearFieldNames()
{
	return this->nearFieldNames;
}

int FEKOResultImport::setFarFieldNames(std::vector<QString> farFieldNames)
{
	this->farFieldNames.clear();
	this->farFieldNames.shrink_to_fit();
	this->farFieldNames = farFieldNames;
	return 0;
}

std::vector<QString> FEKOResultImport::getFarFieldNames()
{
	return this->farFieldNames;
}

int FEKOResultImport::setSelectFieldNames(std::vector<QString> SelectFieldNames, bool nearOrfar)
{
	if (nearOrfar) {
		this->ui.NearradioButton->setChecked(1);
		this->ui.FarradioButton->setChecked(0);
	}
	else {
		this->ui.NearradioButton->setChecked(0);
		this->ui.FarradioButton->setChecked(1);
	}
	// 剔除数据
	this->ListViewmodel->clear();
	this->selectListViewmodel->clear();
	// 重新分配数据
	for (int i = 0; i < SelectFieldNames.size(); i++) {
		QStandardItem* item = new QStandardItem(QString::QString(SelectFieldNames[i]));
		this->selectListViewmodel->appendRow(item);
	}
	std::unordered_set<QString> selectSET;
	for (int i = 0; i < SelectFieldNames.size(); i++) {
		selectSET.insert(SelectFieldNames[i]);// 插入
	}
	if (nearOrfar) {

		for (int i = 0; i < this->nearFieldNames.size(); i++)
		{
			if (selectSET.insert(this->nearFieldNames[i]).second)//判断是否能插入成功
			{
				QStandardItem* item = new QStandardItem(QString::QString(this->nearFieldNames[i]));
				this->ListViewmodel->appendRow(item);
			}
			else {
				
			}
		}

	}
	else {

		for (int i = 0; i < this->farFieldNames.size(); i++)
		{
			if (selectSET.insert(this->farFieldNames[i]).second)//判断是否能插入成功
			{
				QStandardItem* item = new QStandardItem(QString::QString(this->farFieldNames[i]));
				this->ListViewmodel->appendRow(item);
			}
			else {

			}
		}
	}
	this->ui.listView->setModel(this->ListViewmodel);
	this->ui.SelectlistView->setModel(this->selectListViewmodel);
	return 0;
}

std::vector<QString> FEKOResultImport::getSelectFieldNames()
{
	std::vector<QString> result(0);
	this->selectListViewmodel = (QStandardItemModel*)(this->ui.SelectlistView->model());
	int selectCount = this->ui.SelectlistView->model()->rowCount();
	for (int i = 0; i < selectCount; i++) {
		QStandardItem* listItem = this->selectListViewmodel->item(i);
		result.push_back(listItem->text());
	}
	return result;
}

int FEKOResultImport::setFEKOResultCSVPath(QString csvPath)
{
	this->FEKOResultCSVPath = csvPath;
	return 0;
}

QString FEKOResultImport::getFEKOResultCSVPath()
{
	return this->FEKOResultCSVPath;
}

int FEKOResultImport::setFEKOPreProjectFolderPath(QString FolderPath)
{
	this->FEKOProjectFolderPath = FolderPath;
	return 0;
}

QString FEKOResultImport::getFEKOPreProjectFolderPath()
{
	return this->FEKOProjectFolderPath;
}

int FEKOResultImport::initView()
{
	this->ui.FolderPathtextEdit->setText(this->FEKOProjectFolderPath);
	this->ui.PreFileNametextEdit->setText(this->FEKOPreFileName);
	this->ui.csvPathText->setText(this->FEKOResultCSVPath);
	this->ui.NearradioButton->setChecked(this->getNearChecked());
	this->ui.FarradioButton->setChecked(this->getFarChecked());
	this->InitListView();
	return 0;
}

int FEKOResultImport::InitListView()
{
	this->ListViewmodel->clear();
	this->selectListViewmodel->clear();
	if (this->ui.FarradioButton->isChecked()) {
		for (int i = 0; i < this->farFieldNames.size(); i++) {
			QStandardItem* item = new QStandardItem(QString::QString(this->farFieldNames[i]));
			this->ListViewmodel->appendRow(item);
		}
	}
	else {
		this->ui.NearradioButton->setChecked(true);
		for (int i = 0; i < this->nearFieldNames.size(); i++) {
			QStandardItem* item = new QStandardItem(QString::QString(this->nearFieldNames[i]));
			this->ListViewmodel->appendRow(item);
		}
	}
	this->ui.listView->setModel(this->ListViewmodel);
	this->ui.SelectlistView->setModel(this->selectListViewmodel);

	return 0;
}

bool FEKOResultImport::getNearChecked()
{
	return this->ui.NearradioButton->isChecked();
	
}

bool FEKOResultImport::getFarChecked()
{
	return this->ui.FarradioButton->isChecked();
	
}

bool FEKOResultImport::getSaveSucessfully()
{
	return this->saveSucessfully;
}

QString FEKOResultImport::getSaveCsvFilePath()
{
	return this->FEKOResultCSVPath;
	
}

// 打开文件，并寻找pre文件
int FEKOResultImport::OpenPrejectFolderPath() {
	//打开单个文件
	QString prefileNamePath = getOpenFilePath(
		this,
		QString::fromUtf8(u8"选择.pre 文件"),
		QString::fromUtf8(u8"pre文件 (*.pre)"));//多组扩展名用双分号";;"隔开
	this->FEKOProjectFolderPath = getParantFromPath(prefileNamePath);
	this->FEKOPreFileName = getFileNameFromPath(prefileNamePath);
	this->farFieldNames = getFilelist(this->FEKOProjectFolderPath, ".ffe");
	this->nearFieldNames = getFilelist(this->FEKOProjectFolderPath, ".efe");
	// 修改显示
	this->ListViewmodel->clear();
	this->ui.FolderPathtextEdit->setText(this->FEKOProjectFolderPath);
	this->ui.PreFileNametextEdit->setText(this->FEKOPreFileName);
	if (this->ui.FarradioButton->isChecked()) {
		for (int i = 0; i < this->farFieldNames.size(); i++) {
			QStandardItem* item = new QStandardItem(QString::QString(this->farFieldNames[i]));
			this->ListViewmodel->appendRow(item);
		}
	}
	else {
		this->ui.NearradioButton->setChecked(true);
		for (int i = 0; i < this->nearFieldNames.size(); i++) {
			QStandardItem* item = new QStandardItem(QString::QString(this->nearFieldNames[i]));
			this->ListViewmodel->appendRow(item);
		}
	}

	this->ui.listView->setModel(this->ListViewmodel);
	qDebug()<<(u8"farField Number:"+QString::number(this->farFieldNames.size()) + "\n" + u8"NearField Number:" + QString::number(this->nearFieldNames.size()) + "\n");
	return -1;
}



void FEKOResultImport::waitCMDExcute()
{
	qDebug() << u8"转换程序执行结束";
	if (isExists(this->FEKOResultCSVPath)) {
		messageLog(u8"FEKOResult 保存成功\n路径：\t" + this->FEKOResultCSVPath, 1);
		this->saveSucessfully = true;
		this->p->close();
		delete p;
		this->p = nullptr;
	}
	else {
		messageLog(u8"FEKOResult 保存失败\n路径：\t" + this->FEKOResultCSVPath, 1);
		this->saveSucessfully = false;
	}

	// 触发结果时间
	qDebug() <<  u8"准备执行转换结果编辑功能";
	emit this->callbackFekoResultImport(this);

}

int FEKOResultImport::closeWindows()
{
	this->close();
	return 0;
}

int FEKOResultImport::NearRadioButtonSelect(bool selectTrue)
{
	this->ui.NearradioButton->setChecked(selectTrue);
	this->ui.FarradioButton->setChecked(!selectTrue);
	this->InitListView();
	return 0;
}

int FEKOResultImport::FarRadioButtonSelect(bool selectsign)
{
	this->ui.NearradioButton->setChecked(!selectsign);
	this->ui.FarradioButton->setChecked(selectsign);
	this->InitListView();
	return 0;
}

int FEKOResultImport::FEKOResultImportButtonClick()
{
	if (isExists(this->FEKOResultCSVPath)) {
		QFile file(this->FEKOResultCSVPath);
		if (!file.open(QIODevice::ReadWrite)) {
			QMessageBox::information(nullptr, u8"文件被占用", this->FEKOResultCSVPath);
			return 2;
		}
		else {
			file.close();
			removeFile(this->FEKOResultCSVPath);
		}
		
	}

	QString csvpramarPath = this->FEKOResultCSVPath;
	csvpramarPath= csvpramarPath.replace(this->FEKOResultCSVPath.size() - 4, 4, ".params");
	// 获取选择文件
	std::vector<QString> selectfiles = this->getSelectFieldNames();
	QString parmas_text = this->FEKOResultCSVPath +"\n";// 输出路径
	for (int i = 0; i < selectfiles.size(); i++) {
		parmas_text = parmas_text + selectfiles[i] + "\n";
	}
	if (isExists(csvpramarPath)) {
		removeFile(csvpramarPath);
	}


	writeUTF8StringFile(csvpramarPath, (parmas_text));
	// 拼接命令行
	QString cmdtext = u8"";
	if (this->ui.NearradioButton->isChecked()) {
		cmdtext = cmdtext + u8"NearField2csvTool.exe";
	}
	else {
		cmdtext = cmdtext + u8"FarField2csvTool.exe";
	}
	if (nullptr != this->p) {
		this->p->close();
		delete this->p;
		this->p = nullptr;
	}
	this->p = new CMDExcuteApp();
	QObject::connect(this->p, SIGNAL(callbackExcuteResult()), this, SLOT(waitCMDExcute()));
	this->p->setAttribute(Qt::WA_DeleteOnClose);;
	this->p->show();
	this->p->excuteCmd(cmdtext, csvpramarPath);

	return 0;
}

int FEKOResultImport::AddFekoResultClick()
{
	QModelIndexList sourcelist=this->ui.listView->selectionModel()->selectedIndexes();
	std::vector<int> deleteRowids(0);
	for (int i = 0; i < sourcelist.count(); i++) {
		deleteRowids.push_back(sourcelist[i].row());
		qDebug() << ("deletaRowids add :"+QString::number(sourcelist[i].row())+"\n");
	}
	std::sort(deleteRowids.begin(), deleteRowids.end());
	for (int i = deleteRowids.size() - 1; i >= 0; i--) {
		int select_Idx = deleteRowids[i];
		QList<QStandardItem*> listItem = this->ListViewmodel->takeRow(select_Idx);
		int nRightCount = this->selectListViewmodel->rowCount();
		this->selectListViewmodel->insertRow(nRightCount, listItem);
		qDebug() << ("selectListViewmodel insertRow :  "+ QString::number(select_Idx) +"-->" + QString::number(nRightCount) + "\n");
	}

	this->ui.listView->setModel(this->ListViewmodel);
	this->ui.SelectlistView->setModel(this->selectListViewmodel);
	return 0;
}

int FEKOResultImport::DeleteFekoResultClick()
{

	QModelIndexList sourcelist = this->ui.SelectlistView->selectionModel()->selectedIndexes();
	std::vector<int> deleteRowids(0);
	for (int i = 0; i < sourcelist.count(); i++) {
		deleteRowids.push_back(sourcelist[i].row());
	}
	std::sort(deleteRowids.begin(), deleteRowids.end());
	for (int i = deleteRowids.size() - 1; i >= 0; i--) {
		int select_Idx = deleteRowids[i];
		QList<QStandardItem*> listItem = this->selectListViewmodel->takeRow(select_Idx);
		int nRightCount = this->ListViewmodel->rowCount();
		this->ListViewmodel->insertRow(nRightCount, listItem);
		qDebug() << ("ListViewmodel insertRow :  " + QString::number(select_Idx) + "-->" + QString::number(nRightCount) + "\n");
	}
	this->ui.listView->setModel(this->ListViewmodel);
	this->ui.SelectlistView->setModel(this->selectListViewmodel);

	return 0;
}

int FEKOResultImport::SaveCsvFilePath()
{
	//打开单个文件
	QString csvfileNamePath = getSaveFilePath(
		this,
		QString::fromUtf8(u8"保存FEKO解析结果 csv "),
		QString::fromUtf8(u8"csv文件 (*.csv)"));//多组扩展名用双分号";;"隔开
	this->FEKOResultCSVPath = csvfileNamePath;
	this->ui.csvPathText->setPlainText(csvfileNamePath);
	return 0;
}
