#include "MultipleTableView.h"
#include "charcode.h"

#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QScrollBar>
#include <QMenu>
#include <QDebug>

#define OFFRET 20
MultipleTableView::MultipleTableView(QWidget* parent)
    : TableView(parent)
    , wgtContainer(nullptr)
    , lblCounter(nullptr)
    , btnExpand(nullptr)
    , btnCollapse(nullptr)
    , selectedViewState(SelectedViewState::Normal)
    , multipleSelect(false)
    , twSelected(nullptr)
    , inited(false)
    , pkFieldIndex(0)
{
    // 设置默认样式
	verticalHeader()->hide();
}

void MultipleTableView::initSelectView()
{
	if (inited)
		return;

	wgtContainer = new QWidget(this);
	layout = new QHBoxLayout(this);
	QVBoxLayout* layoutButtn = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->setSpacing(0);
	layoutButtn->setContentsMargins(0, 0, 0, 3);
	layoutButtn->setSpacing(3);
	wgtContainer->setLayout(layout);

	lblCounter = new QLabel(this);
	btnExpand = new QPushButton(this);
	btnCollapse = new QPushButton(this);
	btnExpand->setToolTip("展开");
	btnCollapse->setToolTip("收起");
	btnExpand->setFixedSize(25, 16);
	btnCollapse->setFixedSize(25, 16);
	lblCounter->setAlignment(Qt::AlignCenter);
	lblCounter->setFixedSize(20, 20);
	lblCounter->setStyleSheet("QLabel{ border-radius:10px; border:1px solid gray; background-color:white; font-size:10px; }");
	lblCounter->hide();

	lblCounter->setText("0");
	btnExpand->setStyleSheet("QPushButton{border-image:url(Resources/arrow_left.png); background-color:white; min-width:30px;min-height:10px;} QPushButton:hover{border-image:url(Resources/arrow_left_hover.png)}");
	btnCollapse->setStyleSheet("QPushButton{border-image:url(Resources/arrow_right.png); background-color:white; min-width:30px;min-height:10px;}  QPushButton:hover{border-image:url(Resources/arrow_right_hover.png)}");
	layoutButtn->addStretch();
	layoutButtn->addWidget(lblCounter);
	layoutButtn->addWidget(btnExpand);
	layoutButtn->addWidget(btnCollapse);
	layoutButtn->addSpacing(16);
	connect(btnExpand, &QPushButton::pressed, this, &MultipleTableView::expandSelectedView);
	connect(btnCollapse, &QPushButton::pressed, this, &MultipleTableView::collapseSelectedView);

	twSelected = new QTableView(this);
	twSelected->setEditTriggers(QAbstractItemView::NoEditTriggers);
	twSelected->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
	twSelected->setSelectionBehavior(QAbstractItemView::SelectRows);
	twSelected->setAlternatingRowColors(true);
	twSelected->setContextMenuPolicy(Qt::CustomContextMenu);
	twSelected->verticalHeader()->hide();

	QMenu* menu = new QMenu(this);
	menu->addAction("删除", this, SLOT(removeRow()));
	connect(twSelected, &QTableView::customContextMenuRequested, [=](const QPoint&) {
		menu->exec(QCursor::pos());
		});

	layout->addLayout(layoutButtn);
	layout->addWidget(twSelected);
	wgtContainer->raise();
	wgtContainer->show();
	inited = true;
}

void MultipleTableView::setMultipleSelect(bool value)
{
    if (value)
    {
		multipleSelect = true;
        initSelectView();
    }
}

void MultipleTableView::checkStateChanged(Qt::CheckState state, int row)
{
	if (state == Qt::Checked)
		selectRecord(row);
	else if (state == Qt::Unchecked)
		unselectRecord(row);
}

void MultipleTableView::selectRecord(int row)
{
    Q_ASSERT(selectedModel);

	void* pOwner = mainModel->getRowItemAsVoidPtr(row);
	if (isSelected(selectedModel, pOwner) != -1)   
		return;
    int rowCount = selectedModel->getRowCount();
    selectedModel->insertRow(rowCount);
    int columnCount = selectedModel->columnCount();
    for (int column = 0; column < columnCount; ++column)
    {
        selectedModel->setData(selectedModel->index(rowCount,column),selectedModel->getDataMember(column)->toVariant(pOwner));
    }
    lblCounter->setText((QString::number(rowCount + 1)));
	lblCounter->show();
	//wgtContainer->show();
}


void MultipleTableView::unselectRecord(int row)
{
    Q_ASSERT(selectedModel);
	void* pOwner = mainModel->getRowItemAsVoidPtr(row);
    int selectedModelRow = isSelected(selectedModel, pOwner);
    if(selectedModelRow == -1)
		return;
    selectedModel->removeRow(selectedModelRow);
	int count = selectedModel->getRowCount();
	lblCounter->setText(QString::number(count));
	if (count == 0)
	{
		lblCounter->hide();
		//wgtContainer->hide();
	}
}

int MultipleTableView::isSelected(const qx::IxModel *model, void *pOwner)
{
    QVariant pkFieldValue = model->getDataMember(pkFieldIndex)->toVariant(pOwner);

    for (int row = 0; row < model->rowCount(); ++row)
    {
        if(model->data(model->index(row,pkFieldIndex)) == pkFieldValue)
            return row;
    }
    return -1;
}

void MultipleTableView::expandSelectedView()
{
    if (selectedViewState == SelectedViewState::Normal)
    {
        int w = width() / 2;
		wgtContainer->setGeometry(w, 0, w, height() - OFFRET);
        selectedViewState = SelectedViewState::Max;
    }
    else if (selectedViewState == SelectedViewState::Min)
    {
		wgtContainer->setGeometry(width() - SELECTED_VIEW_DEFAULT_WIDTH, 0, SELECTED_VIEW_DEFAULT_WIDTH, height() - OFFRET);
        selectedViewState = SelectedViewState::Normal;
        twSelected->show();
    }
}

void MultipleTableView::collapseSelectedView()
{
    if (selectedViewState == SelectedViewState::Normal)
    {
        int w = 25;
        if (verticalScrollBar()->isVisible())
            w += verticalScrollBar()->width() + 10;

		wgtContainer->setGeometry(width() - w, 0, w, height() - OFFRET);
        selectedViewState = SelectedViewState::Min;
        twSelected->hide();
    }
    else if (selectedViewState == SelectedViewState::Max)
    {
		wgtContainer->setGeometry(width() - SELECTED_VIEW_DEFAULT_WIDTH, 0, SELECTED_VIEW_DEFAULT_WIDTH, height() - OFFRET);
        selectedViewState = SelectedViewState::Normal;
    }
}

void MultipleTableView::removeRow()
{
    if (twSelected == nullptr || mainModel == nullptr)
        return;

    int row = twSelected->currentIndex().row();
    selectedModel->removeRows(row,1);
    lblCounter->setText(QString::number(selectedModel->getRowCount()));
	if (selectedModel->rowCount() == 0)
	{
		//wgtContainer->hide();
		lblCounter->hide();
	}
}

void MultipleTableView::resizeEvent(QResizeEvent* event)
{
    if (wgtContainer != nullptr)
    {
		wgtContainer->setGeometry(width() - SELECTED_VIEW_DEFAULT_WIDTH, 0, SELECTED_VIEW_DEFAULT_WIDTH, height() - OFFRET);
        selectedViewState = SelectedViewState::Normal;
    }

    QTableView::resizeEvent(event);
}

uint MultipleTableView::getPkFieldIndex() const
{
    return pkFieldIndex;
}

void MultipleTableView::setPkFieldIndex(const uint &value)
{
    pkFieldIndex = value;
}

void MultipleTableView::hideSelectTv(bool hide)
{
	wgtContainer->setHidden(hide);
}

qx::IxCollection *MultipleTableView::getSelectedRecord()
{
    Q_ASSERT(selectedModel);
    return selectedModel->getCollection();
}
