#include "AutoCompleteTagEditWidget.h"

#include <QCompleter>
#include <QStringListModel>
#include <QTimer>
#include <QMessageBox>
#include <QEvent>
#include <QDebug>

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif


const QString AutoCompleteTagEditWidget::type = "AutoCompleteTagEdit";

AutoCompleteTagEditWidget::AutoCompleteTagEditWidget(QWidget *parent)
: TagEditWidget(parent)
{
    init();
}

void AutoCompleteTagEditWidget::init()
{
    QCompleter *completer = new QCompleter(this);
    QStringListModel *slm = new QStringListModel(this);
    completer->setModel(slm);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    setCompleter(completer);

    connect(completer, SIGNAL(activated(const QString &)), this, SLOT(onItemSlected(const QString &)));
	disconnect(this, &QLineEdit::returnPressed, this, &TagEditWidget::onEnter);

	installEventFilter(this);
}

void AutoCompleteTagEditWidget::setOptions(QVariantMap options)
{
    QStringListModel *slm = (QStringListModel*)this->completer()->model();

    if(!options.isEmpty())
    {
        QStringList texts;
		for (auto iterOption = options.begin(); iterOption != options.end(); iterOption++)
		{
			texts << iterOption.key();
        }
        slm->setStringList(texts);
		this->options = options;
    }
}

void AutoCompleteTagEditWidget::onEnter()
{
	QString str = text().trimmed();
	if (str.isEmpty())
		return;

	if (!options.contains(str))
	{
		QMessageBox::warning(nullptr, "提示", QString("输入的值无效，请从检索结果中选择！"));
		clear();
		return;
	}

	addTag(str);
}

void AutoCompleteTagEditWidget::onItemSlected(const QString &text)
{
    addTag(text);
    QTimer::singleShot(100, this, SLOT(clear()));
}

bool AutoCompleteTagEditWidget::eventFilter(QObject * watched, QEvent * event)
{
	if (event->type() == QEvent::FocusOut) {
		onEnter();
		return true;
	}

	return QLineEdit::eventFilter(watched, event);
}

void AutoCompleteTagEditWidget::addTag(const QString &text)
{
	TagEditWidget::addTag(text);
}

QStringList AutoCompleteTagEditWidget::getTextList()
{
    QStringList texts;
    Tag *tag;

    foreach(tag, tags)
    {
        texts << tag->text();
    }

    return texts;
}

QStringList AutoCompleteTagEditWidget::getValueList()
{
    QStringList values;
    Tag *tag;

    foreach(tag, tags)
    {
        values << options[tag->text()].toString();
    }

    return values;
}

void AutoCompleteTagEditWidget::setValueList(const QStringList &values)
{
	clear();
	for (int i = 0; i < values.length(); i++)
	{
		for (auto iterOption = options.begin(); iterOption != options.end(); iterOption++)
		{
			if (iterOption.value() == values[i])
			{
				addTag(iterOption.key());
				break;
			}
		}
	}
}


QVariant AutoCompleteTagEditWidget::getValue()
{
	return getValueList().join(",");
}

void AutoCompleteTagEditWidget::setValue(const QVariant &value)
{
	setValueList(value.toString().split(","));
}
