#include"BaseItemDelegate.h"
#include "utils/Utils.h"
#include <DApplication>
#include <DGuiApplicationHelper>
#include <DPaletteHelper>
#include <DPalette>
#include <DStyle>
#include <DStyleHelper>

#include <QAbstractItemView>
#include <QDebug>
#include <QFontMetrics>
#include <QHelpEvent>
#include <QModelIndex>
#include <QPainter>
#include <QStyleOptionViewItem>
#include <QToolTip>

DWIDGET_USE_NAMESPACE

BaseItemDelegate::BaseItemDelegate(QObject *parent)
        : QItemDelegate(parent)
{
}

void BaseItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
{
    if (!index.isValid()) {
        QItemDelegate::paint(painter, option, index);
        return;
    }

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing);
    painter->setOpacity(1);

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);

#ifdef ENABLE_INACTIVE_DISPLAY
    QWidget *wnd = DApplication::activeWindow();
#endif
    DPalette::ColorGroup cg;
    if (!(opt.state & DStyle::State_Enabled)) {
        cg = DPalette::Disabled;
    } else {
#ifdef ENABLE_INACTIVE_DISPLAY
        if (!wnd) {
            cg = DPalette::Inactive;
        } else {
            if (wnd->isModal()) {
                cg = DPalette::Inactive;
            } else {
                cg = DPalette::Active;
            }
        }
#else
        cg = DPalette::Active;
//        cg = DPalette::Current;
#endif
    }

    auto *style = dynamic_cast<DStyle *>(DApplication::style());

    auto margin = style->pixelMetric(DStyle::PM_ContentsMargins, &option);
    auto iconSize = style->pixelMetric(DStyle::PM_ListViewIconSize, &option);

    auto palette = DGuiApplicationHelper::instance()->applicationPalette();

    QPen forground;
    if (index.data(Qt::UserRole + 2).isValid()) {
        forground.setColor(palette.color(cg, static_cast<DPalette::ColorType>(index.data(Qt::UserRole + 2).toInt())));
    } else {
        forground.setColor(palette.color(cg, DPalette::Text));
    }
    if (opt.state & DStyle::State_Enabled) {
        if (opt.state & DStyle::State_Selected) {
            forground.setColor(palette.color(cg, DPalette::TextLively));
            if (opt.state & DStyle::State_Sunken) {
                auto hlColor = opt.palette.highlight().color();
                hlColor.setAlphaF(.1);
                auto newColor = style->adjustColor(forground.color(), 0, 0, 0, 0, 0, 0, -40);
                forground = style->blendColor(newColor, hlColor);
            } else if (opt.state & DStyle::State_MouseOver) {
                forground = style->adjustColor(forground.color(), 0, 0, 20);
            }
        } else {
            if (opt.state & DStyle::State_MouseOver) {
                auto type = DGuiApplicationHelper::instance()->themeType();
                forground = style->adjustColor(forground.color(), 0, 0, type == DGuiApplicationHelper::DarkType ? 20 : -50);
            }
        }
    }

    QRect rect = opt.rect;
    QFontMetrics fm(opt.font);
    QRect textRect = rect;

    switch (opt.viewItemPosition) {
        case QStyleOptionViewItem::Beginning: {
            rect.setX(rect.x() + margin);  // left margin
        } break;
        case QStyleOptionViewItem::Middle: {
            // whole rect
        } break;
        case QStyleOptionViewItem::End: {
            rect.setWidth(rect.width() - margin);  // right margin
        } break;
        case QStyleOptionViewItem::OnlyOne: {
            rect.setX(rect.x() + margin);
            rect.setWidth(rect.width() - margin);
        } break;
        default: {
            painter->restore();
            QItemDelegate::paint(painter, option, index);
            return;
        }
    }

    QVariant value;

    QRect checkRect;
    Qt::CheckState checkState = Qt::Unchecked;
    value = index.data(Qt::CheckStateRole);
    if (value.isValid()) {
        checkState = static_cast<Qt::CheckState>(value.toInt());
        checkRect = doCheck(opt, opt.rect, value);
    }
    //图标的直径是16所以要加上半径
    checkRect.moveRight(opt.rect.right() - checkRect.width() + 8);
    drawCheck(painter, opt, checkRect, checkState);

    QString text;
    QRect iconRect;
    if (opt.viewItemPosition == QStyleOptionViewItem::Beginning ||
        opt.viewItemPosition == QStyleOptionViewItem::OnlyOne) {
        if (opt.features & QStyleOptionViewItem::HasDecoration) {
            textRect = rect;
            // | margin - icon - spacing - text - margin |
            textRect.setX(textRect.x());
            textRect.setWidth(textRect.width() - margin);
            text = fm.elidedText(opt.text, opt.textElideMode, textRect.width());

            iconRect = rect;
            iconRect.setX(rect.x() + margin);
            iconRect.setWidth(iconSize);
        } else {
            // | margin - text - margin |
            textRect = rect;
            textRect.setX(textRect.x());
            textRect.setWidth(textRect.width() - margin);
            text = fm.elidedText(opt.text, opt.textElideMode, textRect.width());
        }
    } else {
        // | margin - text - margin |
        textRect = rect;
        textRect.setX(textRect.x() + margin);
        textRect.setWidth(textRect.width() - margin);
        text = fm.elidedText(opt.text, opt.textElideMode, textRect.width());
    }

    if (opt.features & QStyleOptionViewItem::HasDecoration &&
        (opt.viewItemPosition == QStyleOptionViewItem::Beginning ||
         opt.viewItemPosition == QStyleOptionViewItem::OnlyOne)) {
        auto diff = (iconRect.height() - iconSize) / 2;
        opt.icon.paint(painter, iconRect.adjusted(0, diff, 0, -diff));
    }
    painter->setPen(forground);
    painter->drawText(textRect, static_cast<int>(opt.displayAlignment), text);

    painter->restore();
}


QSize BaseItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QSize size = QItemDelegate::sizeHint(option, index);
    size.setHeight(std::max(DEFAULT_ROW_HEIGHT, size.height()));
    return size;
}

bool BaseItemDelegate::helpEvent(QHelpEvent *e, QAbstractItemView *view,
                                 const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if (!e || !view)
        return false;

    if (e->type() == QEvent::ToolTip) {
        QToolTip::hideText();
        QRect rect = view->visualRect(index);
        QRect textRect = rect;

        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);

        auto margin = DStyle::pixelMetric(view->style(), DStyle::PM_ContentsMargins);

        // textRect
        if (index.column() == 0) {
            if (opt.features & QStyleOptionViewItem::HasDecoration) {
                textRect.setX(textRect.x());
            } else {
                textRect.setX(textRect.x());
            }
        } else {
            textRect.setX(textRect.x() + margin);
        }

        if (rect.x() + rect.width() >= view->width()) {
            textRect.setWidth(textRect.width());
        } else {
            textRect.setWidth(textRect.width());
        }

        // textWidth
        QFontMetrics fm(opt.font);
        int w = fm.size(Qt::TextSingleLine, opt.text).width();
        if (textRect.width() < w + 15) {
            QVariant tooltip = index.data(Qt::DisplayRole);
            if (tooltip.canConvert<QString>()) {
                QToolTip::showText(e->globalPos(),
                                   QString("<div>%1</div>").arg(tooltip.toString().toHtmlEscaped()),
                                   view);
                return true;
            }
        }
    }
    if (!QItemDelegate::helpEvent(e, view, option, index))
        QToolTip::hideText();

    //    return QStyledItemDelegate::helpEvent(e, view, option, index);
    return false;
}

void BaseItemDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const
{
    option->showDecorationSelected = true;
    bool ok = false;
    if (index.data(Qt::TextAlignmentRole).isValid()) {
        uint value = index.data(Qt::TextAlignmentRole).toUInt(&ok);
        option->displayAlignment = static_cast<Qt::Alignment>(value);
    }
    if (!ok)
        option->displayAlignment = Qt::AlignLeft | Qt::AlignVCenter;
    option->textElideMode = Qt::ElideRight;
    option->features = QStyleOptionViewItem::HasDisplay;
    if (index.data(Qt::DisplayRole).isValid())
        option->text = index.data().toString();

    if (index.data(Qt::DecorationRole).isValid()) {
        option->features |= QStyleOptionViewItem::HasDecoration;
        option->icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
    }

    if(option->decorationPosition != QStyleOptionViewItem::Right) {
        option->decorationPosition=QStyleOptionViewItem::Right;
    }
}



