#include "TableMainWindow.h"
#include "TableViewModel.h"
#include "SharedModuleLib/BaseUiTool.h"
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <QFileDialog>
#include <QClipboard>
#include <QItemSelectionModel>
#include <QDebug>

TableMainWindow::TableMainWindow(QWidget* parent)
{
	this->FILEOPENLOCK = false;
	this->CheckFieldContextHasEmptyCeilLOCK = false;
	this->ui.setupUi(this);
	this->initTableViewContextMenu();
	this->initTableViewStatusBarControl();
}

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

int TableMainWindow::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); // 表格控件的右键菜单

	QAction* m_undoAction = m_undoStack->createUndoAction(this, u8"撤销");//添加QAction，Ctrl-Z作为回撤的快捷键
	m_undoAction->setShortcut(QKeySequence("Ctrl+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("Ctrl+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("Ctrl+C"));
	QObject::connect(copyAction, SIGNAL(triggered()), this, SLOT(tableView_CopyAction()));

	QAction* PasteAction = this->tableViewContextMenu->addAction(u8"粘贴"); // 粘贴
	PasteAction->setShortcut(QKeySequence("Ctrl+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()));

	return 0;
}

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

void TableMainWindow::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 TableMainWindow::setDragDropOverwriteMode(bool flag) {
	this->ui.tableView->setDragDropOverwriteMode(flag);
	return 0;
}

void TableMainWindow::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 TableMainWindow::tableView_UndoAction()
{
	qDebug() << u8"正在撤销命令";
	int index = this->m_undoStack->index();
	this->m_undoStack->setIndex(index);
}

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


// 检查存在空单元格的列，并修改展示
void TableMainWindow::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);
	
}


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

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

int TableMainWindow::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 TableMainWindow::setTableViewAutoSort(bool flag)
{
	this->ui.tableView->setSortingEnabled(flag);
	return flag;
}

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



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

	return -1;
}


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

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


/*
* 粘贴命令
***/
PasteCommand::PasteCommand(QTableView* tableItem, QModelIndexList selectedIndexes, QString clipboardData, QUndoCommand* parent) : QUndoCommand(parent)
{
	qDebug() << u8"============================";
	qDebug() << clipboardData;
	qDebug() << u8"============================";
	this->tableItem = tableItem;
	// 将clipboardData -> 二维矩阵
	QStringList clipboardList = clipboardData.split("\n");
	if (clipboardList[clipboardList.count() - 1] == u8"") {
		clipboardList.removeAt(clipboardList.count() - 1);
	}
	std::vector<std::vector<QString>> clipboardVec(clipboardList.count());
	for (int i = 0; i < clipboardVec.size(); i++) {
		QStringList lineList = clipboardList[i].split("\t");
		clipboardVec[i] = std::vector<QString>(lineList.size());
		for (int j = 0; j < lineList.count(); j++) {
			clipboardVec[i][j] = lineList[j];
		}
	}
	this->newText = clipboardVec;

	if (selectedIndexes.count() == 0) {
		messageLog(u8"请选中要粘贴的单元格区域", 1);
	}
	else if (selectedIndexes.count() == 1) { //
		this->start_row = selectedIndexes.at(0).row();
		this->start_col = selectedIndexes.at(0).column();
	}
	else { //  
		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;
		}
		if (max_col - min_col + 1 != clipboardVec[0].size() || max_row - min_row + 1 != clipboardVec.size()) {
			messageLog(u8"选中单元格范围大小不匹配", 1);
		}
		else {}
		this->start_row = selectedIndexes.at(0).row();
		this->start_col = selectedIndexes.at(0).column();
	}
	this->oldText = std::vector<std::vector<QString>>(this->newText.size());
	for (int i = 0; i < this->newText.size(); i++) {
		this->oldText[i] = std::vector<QString>(this->newText[i].size());
		for (int j = 0; j < this->newText[i].size(); j++) {
			this->oldText[i][j] = tableItem->model()->index(i + start_row, j + start_col).data().toString();
		}
	}
}

PasteCommand::~PasteCommand()
{
}

// 撤销
void PasteCommand::undo()
{
	qDebug() << u8"正在撤销命令：PasteCommand";
	for (int i = 0; i < this->newText.size(); i++) {
		this->oldText[i] = std::vector<QString>(this->newText[i].size());
		for (int j = 0; j < this->newText[i].size(); j++) {
			this->tableItem->model()->setData(tableItem->model()->index(i + start_row, j + start_col), this->oldText[i][j]);
		}
	}
	this->tableItem->show();
}

// 重做
void PasteCommand::redo()
{
	qDebug() << u8"正在重做命令：PasteCommand";
	for (int i = 0; i < this->newText.size(); i++) {
		this->oldText[i] = std::vector<QString>(this->newText[i].size());
		for (int j = 0; j < this->newText[i].size(); j++) {
			this->tableItem->model()->setData(tableItem->model()->index(i + start_row, j + start_col), this->newText[i][j]);
		}
	}
	this->tableItem->show();
}
