#include"ImmuBaseItemDelegate.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

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

QSize ImmuBaseItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    // 先调用父类获取基础size，再强制设置高度为30px（覆盖父类的std::max逻辑）
    QSize size = BaseItemDelegate::sizeHint(option, index);
    size.setHeight(30);  // 强制固定为30px
    return size;
}

void ImmuBaseItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
{
    if (!index.isValid()) {
        BaseItemDelegate::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) + 10;
    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();
            BaseItemDelegate::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();
}
