#include "TableViewModel.h"
#include <QColor>
#include <QFile>
#include <QTextStream>
#include "SharedModuleLib/BaseUiTool.h"
#include <stdlib.h>
#include <stdio.h>
#include <QRegularExpression>
#include <QDebug>
#include "SharedModuleLib/ProcessOn.h"

FEKOResultCsvTableModel::FEKOResultCsvTableModel(QObject* parent)
{
}

FEKOResultCsvTableModel::~FEKOResultCsvTableModel()
{
}

void FEKOResultCsvTableModel::loadFilePath(QString csvPath)
{
    return this->loadCSVFilePath(csvPath);
}

void FEKOResultCsvTableModel::saveFilePath()
{
    if (!isExists(this->csvPath)) {
        this->csvPath = getSaveFilePath(
            nullptr,
            QString::fromUtf8(u8"另存为"),
    
            QString::fromUtf8(u8"csv文件 (*.csv)"));//多组扩展名用双分号";;"隔开
    }
    return this->saveCSVFilePath(this->csvPath);
}

void FEKOResultCsvTableModel::saveAsFilePath(QString csvpath)
{
    return this->saveCSVFilePath(csvpath);
}

void FEKOResultCsvTableModel::loadCSVFilePath(QString csvPath)
{
    this->csvPath = csvPath;
    QFile inFile(csvPath);
    QStringList colnames;
    QVector<QVector<QVariant>> datamap(0);
    QStringList rowIDlist;
    bool hascolnames = true;
    size_t rowid = 0; 
    if (inFile.open(QIODevice::ReadOnly))
    {
        QTextStream stream_text(&inFile);
        while (!stream_text.atEnd())
        {
            QString line = stream_text.readLine();
            QStringList linesplit = line.split(QRegularExpression(",(?!\\s)")); // 字段切分
            if (hascolnames) { // 列名
                linesplit[0] = "id";
                for (int col = 0; col < linesplit.size(); col++) {
                    QString colname_temp = linesplit.at(col);
                    colnames.append(linesplit.at(col)); // 追加字段名称
                }
                hascolnames = false;
            }
            else { 
                QVector<QVariant> mapline(colnames.count()); // 单行数据
                mapline[0] =linesplit.at(0);
                for (int col = 1; col < colnames.size(); col++) {
                    mapline[col] = linesplit.at(col);
                }
                datamap.append(mapline);
                rowIDlist.append(QString::number(rowid));
                rowid = rowid + 1;
                //qDebug() << line;
            }
        }
        inFile.close();
    }
    this->SetData(datamap, colnames, rowIDlist);
}

void FEKOResultCsvTableModel::saveCSVFilePath(QString csvpath)
{
    qDebug() << u8"正在保存为 csv文件中";
    QFile file(csvpath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
    {
        QTextStream stream(&file);
        // 写入表头
        for (const QString& header : this->m_hor_hedlbls) // 写入表头
        {
            stream << header;
            if (&header != &this->m_hor_hedlbls.last()) // 如果不是最后一列，写入逗号
                stream << ",";
        }
        stream << "\n";
        // 写入数据
        for (int i = 0; i < this->m_vec_hedlbls.count(); i++) {
            for (int j = 0; j < this->m_hor_hedlbls.count()-1; j++) {
                stream << this->m_data_map[i][j].toString();
                stream << ",";
            }
            stream << this->m_data_map[i][this->m_hor_hedlbls.count() - 1].toString();
            stream << "\n";
        }
        file.close();
    }
    qDebug() << csvpath;
}

QStringList FEKOResultCsvTableModel::getColumnNames()
{
    return this->m_hor_hedlbls;
}

QStringList FEKOResultCsvTableModel::getItemDataByColumn(int colidx)
{
    QStringList result;
    for (size_t i = 0; i < this->rowCount(); i++) {
        result.append(this->m_data_map[i][colidx].toString());
    }
    return result;
}

QString  FEKOResultCsvTableModel::getCSVPath() {
    return this->csvPath;
}


int FEKOResultCsvTableModel::getColumnIdxByColumName(QString ColumnName) {
    for (int i = 0; i < this->colCount(); i++) {
        if (ColumnName == this->m_hor_hedlbls[i]) {
            return i;
        }
    }
    return -1;
}


void FEKOResultCsvTableModel::SetData(const QVector<QVector<QVariant>>& map,QStringList &colnames, QStringList& rowIds)
{
    beginResetModel();
    m_hor_hedlbls = colnames; // 列名
    m_data_map = map;
    m_vec_hedlbls = rowIds; // 行名
    this->colorData = QVector<QVector<QColor>>(m_vec_hedlbls.count(), QVector<QColor>(m_hor_hedlbls.count()));
    for (int i = 0; i < m_hor_hedlbls.count(); i++) {
        for (int j = 0; j < m_vec_hedlbls.count(); j++) {
            this->colorData[j][i] = QColor(255, 255, 255);
        }
    }
    endResetModel();
}

void FEKOResultCsvTableModel::setHignlightIndex(QVector<QPair<int, int> > vec_index)
{
    beginResetModel();
    m_highlight_indexs = vec_index;
    endResetModel();
}

Qt::ItemFlags FEKOResultCsvTableModel::flags(const QModelIndex& index) const
{
    Qt::ItemFlags flags = QAbstractItemModel::flags(index);
    flags |= Qt::ItemIsEditable;
    return flags;
}

QVariant FEKOResultCsvTableModel::data(const QModelIndex& _index, int role) const
{
    if (role == Qt::DisplayRole || role == Qt::EditRole)
    {
        return this->m_data_map[_index.row()][_index.column()];
    }
    else if (role == Qt::TextAlignmentRole)  return Qt::AlignCenter; // 文字居中
    else if (role == Qt::BackgroundColorRole)                        // 设置背景色
    {
        if (m_highlight_indexs.contains(qMakePair<int, int>(_index.row(), _index.column())))
        {
            return QColor(230, 247, 255);
        }
        else {
            return this->colorData[_index.row()][_index.column()];
        }
    }

    //    else if(role == Qt::DecorationRole)     // 为item添加图标
    //    {
    //        return QIcon(":/images/device.svg");
    //    }

    return QVariant();
}

QVariant FEKOResultCsvTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal)
    {
        if (role == Qt::DisplayRole)    return m_hor_hedlbls.at(section);
        else    return QVariant();
    }

    return QAbstractTableModel::headerData(section, orientation, role); // 垂直表头的序号
}

bool FEKOResultCsvTableModel::setData(const QModelIndex& _index, const QVariant& value, int role)
{
    if (_index.isValid() && role == Qt::EditRole)
    {
        this->isNeedExtendTable(_index.row(), _index.column());
        if (this->m_data_map[_index.row()][_index.column()]== value) {
            return false;
        }
        else {}
        this->m_data_map[_index.row()][_index.column()] = value;
        emit dataChanged(_index, _index);
        emit itemChanged(_index, value);
        return true;
    }
    else if (role == Qt::BackgroundColorRole) {
        this->colorData[_index.row()][_index.column()] = value.value<QColor>();
    }
    return false;
}

int FEKOResultCsvTableModel::rowCount(const QModelIndex& parent) const
{
    return this->m_vec_hedlbls.count();
}

int FEKOResultCsvTableModel::columnCount(const QModelIndex& parent) const
{
    return this->m_hor_hedlbls.count();
}

QString FEKOResultCsvTableModel::itemText(int row, int column) const
{
    return this->m_data_map[row][column].toString();
}

QString FEKOResultCsvTableModel::itemText(const QModelIndex& index) const
{
    return this->m_data_map[index.row()][index.column()].toString();
}

void FEKOResultCsvTableModel::setItemText(const QModelIndex& index, const QString& str)
{
    this->isNeedExtendTable(index.row(), index.column());
    this->m_data_map[index.row()][index.column()] = str;
}

void FEKOResultCsvTableModel::setItemText(int row, int column, const QString& str)
{
    this->isNeedExtendTable(row, column);
    this->m_data_map[row][column] = str;
}

QVariant FEKOResultCsvTableModel::ItemData(const QModelIndex& index) const
{
    return this->m_data_map[index.row()][index.column()];
}

QVariant FEKOResultCsvTableModel::ItemData(int row, int column) const
{
    return this->m_data_map[row][column];
}

void FEKOResultCsvTableModel::SetItemData(const QModelIndex& index, const QVariant& data)
{
    this->isNeedExtendTable(index.row(), index.column());
    this->m_data_map[index.row()][index.column()] = data;

}

void FEKOResultCsvTableModel::SetItemData(int row, int column, const QVariant& data)
{
    this->isNeedExtendTable(row, column);
    this->m_data_map[row][column] = data;
}

size_t FEKOResultCsvTableModel::rowCount()
{
    return this->m_data_map.count();
}


size_t FEKOResultCsvTableModel::colCount()
{
    return this->m_vec_hedlbls.count();
}

void FEKOResultCsvTableModel::isNeedExtendTable(size_t row, size_t column) {
    size_t max_colnum = this->m_hor_hedlbls.count() - 1 < column ? column + 1 : this->m_hor_hedlbls.count(); // 判断是否扩展列名
    if (this->m_hor_hedlbls.count() <= column) {
        for (int i = this->m_hor_hedlbls.count(); i <= column; i++) {
            this->m_hor_hedlbls.append(QString::number(i));
        }
    }
    if (0 > row || column < 0) {
        return;
    }
    else if (row > this->m_vec_hedlbls.count()-1 || column > this->m_hor_hedlbls.count()-1) {
        for (int i = 0; i <= row; i++) {
            if (i >= this->m_data_map.count()) {
                this->m_data_map.append(QVector<QVariant>(max_colnum));
                this->colorData.append(QVector<QColor>(max_colnum));
                this->m_vec_hedlbls.append(QString::number(i));
            }
            else {
                if (this->m_data_map[i].count() < column + 1) { // 扩充
                    this->m_data_map[i].reserve(max_colnum);
                    //this->colorData[i].reserve(max_colnum);
                    for (size_t ci = this->colorData[i].count(); ci < max_colnum; ci++) {
                        this->colorData[i].append(QColor(255, 255, 255));
                    }
                }
                else {

                }
            }
        }
    }
}

void FEKOResultCsvTableModel::clear()
{
    beginResetModel();
    //m_table_map.clear();
    m_data_map.clear();
    m_hor_hedlbls.clear();
    m_vec_hedlbls.clear();
    m_highlight_indexs.clear();
    endResetModel();
}

QVariant* FEKOResultCsvTableModel::getVariantPtr(size_t row, size_t col)
{
    return &(this->m_data_map[row][col]);
    //return nullptr;
}

void AbstractTableModel::loadFilePath(QString csvPath)
{
}

void AbstractTableModel::saveFilePath()
{

}

void AbstractTableModel::saveAsFilePath(QString csvpath)
{
}

QString AbstractTableModel::getCSVPath()
{
    return QString();
}
