#include "GreyClusteringItemDelegate.h"

#include <QMessageBox>

GreyClusteringItemRangeDelegate::GreyClusteringItemRangeDelegate(QObject *parent) : QStyledItemDelegate(parent) { }

QWidget *GreyClusteringItemRangeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */,
                                                       const QModelIndex & /* index */) const
{
    RangeSpin *editor = new RangeSpin(parent);

    return editor;
}

void GreyClusteringItemRangeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString value      = index.model()->data(index, Qt::EditRole).toString();
    RangeSpin *spinBox = static_cast<RangeSpin *>(editor);
    spinBox->setValue(value);
}

void GreyClusteringItemRangeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                                   const QModelIndex &index) const
{
    RangeSpin *spinBox = static_cast<RangeSpin *>(editor);
    if (!spinBox->valid()) {
        QMessageBox::warning(nullptr, "警告", QString("设置的值%1区间错误,请重新设置!").arg(spinBox->result()));
        return;
    }
    QString value = spinBox->result();

    model->setData(index, value, Qt::EditRole);
}

void GreyClusteringItemRangeDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                                                           const QModelIndex & /* index */) const
{
    QRect rect = option.rect;
    rect.adjust(-20, -10, 20, 10);
    editor->setGeometry(rect);
}

GreyClusteringItemSpinDelegate::GreyClusteringItemSpinDelegate(QObject *parent) : QStyledItemDelegate(parent) { }

QWidget *GreyClusteringItemSpinDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */,
                                                      const QModelIndex & /* index */) const
{
    QDoubleSpinBox *editor = new QDoubleSpinBox(parent);

    editor->setFrame(false);
    editor->setMinimum(-1000000);
    editor->setMaximum(1000000);
    return editor;
}

void GreyClusteringItemSpinDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    double value = index.model()->data(index, Qt::EditRole).toDouble();

    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox *>(editor);
    spinBox->setValue(value);
}

void GreyClusteringItemSpinDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                                  const QModelIndex &index) const
{
    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox *>(editor);
    spinBox->interpretText();
    double value = spinBox->value();

    model->setData(index, value, Qt::EditRole);
}

void GreyClusteringItemSpinDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                                                          const QModelIndex & /*index*/) const
{
    editor->setGeometry(option.rect);
}