#include "EchoTableEditWindow.h"
#include "TableProcess/TableMainWindow.h"
#include "TableProcess/TableViewModel.h"
#include "SharedModuleLib/BaseUiTool.h"
#include "LAMPImageCreateClass.h"

#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <QFileDialog>
#include <QClipboard>
#include <QItemSelectionModel>
#include <QDebug>



EchoTableEditWindow::EchoTableEditWindow(QWidget* parent)
{
	this->FILEOPENLOCK = false;
	this->CheckFieldContextHasEmptyCeilLOCK = false;
	this->ui.setupUi(this);
	this->setWindowTitle(u8"FEKO回波数据解析与导出界面");
	this->initTableViewContextMenu();
	this->initTableViewStatusBarControl();

	// 定标常数界面关闭
	this->ui.tab_calibration->setEnabled(false); 
	this->ui.tabWidget->removeTab(1);// 删除定标常数界面


}

EchoTableEditWindow::~EchoTableEditWindow()
{
	delete this->statusprogressBar;
	delete this->tableViewContextMenu;
	delete this->m_undoStack;




}

int EchoTableEditWindow::initTableViewContextMenu()
{
	qDebug() << u8"正在初始化contextMenu";
	m_undoStack = new QUndoStack(this); //存放命令的栈

	this->ui.tableView->setContextMenuPolicy(Qt::CustomContextMenu);
	//this->ui.tableView->setFocusPolicy(Qt::NoFocus); // 允许快捷键
	this->tableViewContextMenu = new QMenu(this->ui.tableView); // 表格控件的右键菜单

	QAction* m_undoAction = m_undoStack->createUndoAction(this, u8"撤销");//添加QAction，Ctrl-Z作为回撤的快捷键
	m_undoAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z));
	QObject::connect(m_undoAction, SIGNAL(triggered()), this, SLOT(tableView_UndoAction()));

	QAction* m_redoAction = m_undoStack->createRedoAction(this, u8"重做");//添加QAction，Ctrl-Y左右前进的快捷键
	m_redoAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Y));
	QObject::connect(m_redoAction, SIGNAL(triggered()), this, SLOT(tableView_RedoAction()));

	this->tableViewContextMenu->addAction(m_undoAction);
	this->tableViewContextMenu->addAction(m_redoAction);


	QAction *copyAction= this->tableViewContextMenu->addAction(u8"复制"); // 复制
	copyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
	QObject::connect(copyAction, SIGNAL(triggered()), this, SLOT(tableView_CopyAction()));

	QAction* PasteAction = this->tableViewContextMenu->addAction(u8"粘贴"); // 粘贴
	PasteAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_V));
	QObject::connect(PasteAction, SIGNAL(triggered()), this, SLOT(tableView_PasteAction()));
	
	QAction* CheckFieldHasEmptyCeilAction = this->tableViewContextMenu->addAction(u8"检查单元格为空");
	QObject::connect(CheckFieldHasEmptyCeilAction, SIGNAL(triggered()), this, SLOT(tableView_CheckFieldHasEmptyCeilAction()));
	qDebug() << u8"初始化contextMenu结束";
	return 0;
}

void EchoTableEditWindow::ShowTableViewContextMenu(QPoint p)
{
	qDebug() << u8"正在展示tableview 右键菜单";
	//Q_UNUSED(pos);
	this->tableViewContextMenu->exec(QCursor::pos());
}

void EchoTableEditWindow::tableView_CopyAction()
{
	qDebug() << u8"正在启动tableview 右键复制代码";
	QItemSelectionModel* selectionModel = this->ui.tableView->selectionModel();
	QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
	if (selectedIndexes.count() == 0) { 
		return;
	}
	
	QTableView* tableView = this->ui.tableView; // Your table view object

	/*
	* a\tb\tc\n
	* d\tf\te\n
	**/
	int min_row, max_row, min_col, max_col;
	min_row = selectedIndexes.at(0).row();
	max_row = selectedIndexes.at(0).row();
	min_col = selectedIndexes.at(0).column();
	max_col = selectedIndexes.at(0).column();
	for (int i = 0; i < selectedIndexes.count(); i++) {
		min_row = min_row > selectedIndexes.at(i).row() ? selectedIndexes.at(i).row() : min_row;
		max_row = max_row < selectedIndexes.at(i).row() ? selectedIndexes.at(i).row() : max_row;
		min_col = min_col > selectedIndexes.at(i).column() ? selectedIndexes.at(i).column() : min_col;
		max_col = max_col < selectedIndexes.at(i).column() ? selectedIndexes.at(i).column() : max_col;
	}
	std::vector<std::vector<QString>> copylist(max_row-min_row+1);
	for (int i = min_row; i <= max_row; i++) {
		copylist[i - min_row] = std::vector<QString>(max_col - min_col + 1);
	}
	qDebug() << u8"minRow"<<min_row;
	qDebug() << u8"maxRow" << max_row;
	qDebug() << u8"minCol" << min_col;
	qDebug() << u8"maxCol" << max_col;
	for (int i = 0; i < selectedIndexes.count(); i++) {
		QString tempstring= selectedIndexes.at(i).data().toString();
		copylist[selectedIndexes.at(i).row() - min_row]
			[selectedIndexes.at(i).column() - min_col] = tempstring;
	}
	QString clipboardText = "";
	for (int i = 0; i < copylist.size(); i++) {
		for(int j=0;j<copylist[i].size()-1;j++){
			clipboardText = clipboardText + copylist[i][j]+u8"\t";
		}
		clipboardText = clipboardText + copylist[i][copylist[i].size() - 1] + u8"\n";
		//clipboardData.append("\n");
	}
	// Add header data
	//QHeaderView* header = tableView->horizontalHeader();
	//for (int i = 0; i < header->count(); i++) {
	//	QVariant headerData = header->model()->headerData(i, Qt::Horizontal);
	//	clipboardData.insert(i, headerData.toString());
	//}
	qDebug() << u8"============================";
	qDebug() << clipboardText;
	qDebug() << u8"============================";

	QApplication::clipboard()->setText(clipboardText);
}

int EchoTableEditWindow::setDragDropOverwriteMode(bool flag) {
	this->ui.tableView->setDragDropOverwriteMode(flag);
	return 0;
}

int EchoTableEditWindow::setTablCalibrationTab(bool flag)
{
	if (flag) {
		this->ui.tab_calibration->setEnabled(true);
		this->ui.tabWidget->insertTab(1, this->ui.tab_calibration, u8"定标常数");
	}
	else {
		this->ui.tab_calibration->setEnabled(false);
		this->ui.tabWidget->removeTab(1);// 删除定标常数界面
	}
	return 0;
}

void EchoTableEditWindow::tableView_PasteAction() {
	qDebug() << u8"正在启动tableview 右键粘贴代码";
	QTableView* tableview = this->ui.tableView;
	QClipboard* clipboard = QApplication::clipboard();
	QString clipboardData = QApplication::clipboard()->text();
	QItemSelectionModel* selectionModel = this->ui.tableView->selectionModel();
	QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
	this->m_undoStack->push(new PasteCommand(this->ui.tableView, selectedIndexes, clipboardData));
	tableview->show();
}

void EchoTableEditWindow::tableView_UndoAction()
{
	qDebug() << u8"正在撤销命令";
	int index = this->m_undoStack->index();
	this->m_undoStack->setIndex(index);
}

void EchoTableEditWindow::tableView_RedoAction()
{
	qDebug() << u8"正在重做命令";
	int index = this->m_undoStack->index();
	this->m_undoStack->setIndex(index );
}


// 检查存在空单元格的列，并修改展示
void EchoTableEditWindow::tableView_CheckFieldHasEmptyCeilAction()
{
	this->ui.statusbar->showMessage(u8"正在检查存在空数据的单元列");
	size_t colcount = this->ui.tableView->model()->columnCount();
	size_t rowcount = this->ui.tableView->model()->rowCount();
	this->statusprogressBar->setRange(0, colcount - 1);
	this->statusprogressBar->setValue(0);
	QList<QModelIndex> cellIndexes;
	for (int j = 0; j < colcount; j++) {
		for (int i = 0; i < rowcount; i++) {
			if (this->ui.tableView->model()->index(i, j).data().toString().count() < 1) {
				cellIndexes.append(this->ui.tableView->model()->index(i, j));
				break;
			}
		}
		this->statusprogressBar->setValue(j);
	}
	if (cellIndexes.count() == 0) {
		return;
	}
	else {}
	this->ui.statusbar->showMessage(u8"正在选择空格");
	this->statusprogressBar->setRange(0, cellIndexes.count()-1);
	this->statusprogressBar->setValue(0);
	QItemSelectionModel* selectionModel = this->ui.tableView->selectionModel();
	for (int i = 0; i < cellIndexes.count(); i++) {
		selectionModel->select(cellIndexes[i], QItemSelectionModel::Select);
		this->statusprogressBar->setValue(i);
	}
	this->ui.tableView->show();
	this->ui.tableView->scrollTo(cellIndexes[0], QAbstractItemView::EnsureVisible);
 

}

void EchoTableEditWindow::on_actionOpen_triggered()
{
	this->OpenCSVDialog();
}

void EchoTableEditWindow::on_actionSave_triggered()
{
	this->SaveCSVDialog();
}

void EchoTableEditWindow::on_actionSaveAs_triggered()
{
	this->SaveAsDialog();
}

void EchoTableEditWindow::on_actionEchoSplitExport_triggered()
{
	// 在窗口关闭事件中询问用户是否关闭
	QMessageBox::StandardButton reply;
	qDebug() << u8"检查乱码文件所在位置";
	reply = QMessageBox::question(this, u8"询问", u8"导出回波文件前，请保存文件", QMessageBox::Yes | QMessageBox::No);
	if (reply == QMessageBox::Yes) {
		// 用户点击了"Yes"按钮，关闭窗口
		this->SaveCSVDialog();
	}
	else {
		// 用户点击了"No"按钮，取消关闭操作
		return;
	}
	// 保存并导出回波文件

	this->ui.statusbar->showMessage(u8"正在分析回波文件");
	this->statusprogressBar->setRange(0,100);
	this->statusprogressBar->setValue(10);
	FEKOBase::NearFieldEchoCSVParser nearfilePraseclass;
	QString echocsvfilepath = this->model->getCSVPath();
	if (!nearfilePraseclass.parseCSV(echocsvfilepath)) {
		QMessageBox::warning(this, u8"警告", u8"回波文件结构解析错误，请检查文件");
		return;
	}
	this->statusprogressBar->setValue(25);
	QMessageBox::information(this, u8"信息", u8"请分别为theta极化、phi极化、R极化分量回波指定保存路径");

	QString thetafilepath = getSaveFilePath(
		this,
		QString::fromUtf8(u8"另存为"),
		QString::fromUtf8(u8"theta文件 (*.theta)"));//多组扩展名用双分号";;"隔开
 
	QString phifilepath = getSaveFilePath(
		this,
		QString::fromUtf8(u8"另存为"),
		QString::fromUtf8(u8"phi文件 (*.phi)"));//多组扩展名用双分号";;"隔开

	QString Rfilepath = getSaveFilePath(
		this,
		QString::fromUtf8(u8"另存为"),
		QString::fromUtf8(u8"R文件 (*.R)"));//多组扩展名用双分号";;"隔开


	this->ui.statusbar->showMessage(u8"正在导出theta极化");
	nearfilePraseclass.toThetapolar(thetafilepath);
	this->statusprogressBar->setValue(50);
	this->ui.statusbar->showMessage(u8"正在导出phi极化");
	nearfilePraseclass.toPhiPolar(phifilepath);
	this->statusprogressBar->setValue(75);

	this->ui.statusbar->showMessage(u8"正在导出R极化");
	nearfilePraseclass.toRPolar(Rfilepath);
	this->statusprogressBar->setValue(99);
	QMessageBox::information(this, u8"信息", u8"极化回波已经保存完毕");

	// 询问用户是否关闭窗口
 
	reply = QMessageBox::question(this,  u8"提示", u8"是否直接进行成像?",QMessageBox::Yes | QMessageBox::No);
	if (reply == QMessageBox::Yes) {
		LAMPImageCreateClass* imagewindows = new LAMPImageCreateClass;
		imagewindows->show();
	}
	else {
		return;
	}
}

void EchoTableEditWindow::on_actionCalibrationConst_triggered()
{

}

 


int EchoTableEditWindow::LockFileOpen(bool flag)
{
	this->FILEOPENLOCK = flag;
	return 0;
}

int EchoTableEditWindow::setCheckFieldContextHasEmptyCeilLOCK(bool flag)
{
	this->CheckFieldContextHasEmptyCeilLOCK = flag;
	return 0;
}

int EchoTableEditWindow::loadTablemode(std::shared_ptr<AbstractTableModel> mode)
{
	this->model = mode;
	this->ui.tableView->setModel(this->model.get());
	if (this->model->rowCount() > 1e4) {
		this->ui.tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
	}
	return 0;
}

int EchoTableEditWindow::setTableViewAutoSort(bool flag)
{
	this->ui.tableView->setSortingEnabled(flag);
	return flag;
}

int EchoTableEditWindow::initTableViewStatusBarControl()
{
	this->statusprogressBar = new QProgressBar();
	this->statusprogressBar->setRange(0, 100); // 设置进度条范围
	this->statusprogressBar->setValue(0); // 设置当前进度
	this->ui.statusbar->addPermanentWidget(this->statusprogressBar); // 在状态栏中添加进度条
	
	return 0;
}



int EchoTableEditWindow::OpenCSVDialog()
{
	if (this->FILEOPENLOCK) {
		return 0;
	}
	else {}
	QString tableFilepath = getOpenFilePath(
		this,
		QString::fromUtf8(u8"打开表格文件"),
		QString::fromUtf8(u8"csv文件 (*.csv);;xls文件(*.xls)"));
 

	this->ui.statusbar->showMessage(u8"正在打开文件....");
	std::shared_ptr< FEKOResultCsvTableModel> tablemode = std::make_shared< FEKOResultCsvTableModel>();
	tablemode->loadCSVFilePath(tableFilepath);
	this->loadTablemode(tablemode);
	this->setTableViewAutoSort(true);
	this->LockFileOpen();
	this->ui.statusbar->showMessage(u8"文件打开结束");
	return -1;
}


int EchoTableEditWindow::SaveCSVDialog()
{
	this->model->saveFilePath();
	return 0;
}

int EchoTableEditWindow::SaveAsDialog()
{
	QString filepath = getSaveFilePath(
		this,
		QString::fromUtf8(u8"另存为"),
		QString::fromUtf8(u8"csv文件 (*.csv)"));//多组扩展名用双分号";;"隔开
	this->model->saveAsFilePath(filepath);
	return 0;
}
