// colorlistwidget.cpp
#include "colorlistwidget.h"
#include <QHeaderView>
#include <QPainter>
#include <QStyledItemDelegate>
#include <QTableWidget>
#include <QVBoxLayout>

// 自定义的ColorDelegate用于绘制颜色块
class ColorDelegate : public QStyledItemDelegate
{
public:
    explicit ColorDelegate(QObject *parent = nullptr)
        : QStyledItemDelegate(parent)
    {}

    void paint(QPainter *painter,
               const QStyleOptionViewItem &option,
               const QModelIndex &index) const override
    {
        if (index.column() == 1) {
            QColor color = index.data(Qt::DisplayRole).value<QColor>();

            // 绘制背景
            painter->save();
            painter->setRenderHint(QPainter::Antialiasing);

            // 绘制颜色块
            QRect rect = option.rect.adjusted(2, 2, -2, -2);
            painter->setPen(Qt::darkGray);
            painter->setBrush(color);
            painter->drawRoundedRect(rect, 4, 4);

            // 显示颜色值文本
            painter->setPen(color.lightness() > 128 ? Qt::black : Qt::white);
            painter->drawText(rect,
                              Qt::AlignCenter,
                              color.name(QColor::NameFormat::HexArgb).toUpper());

            painter->restore();
        } else {
            QStyledItemDelegate::paint(painter, option, index);
        }
    }

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
    {
        return QSize(120, 28); // 统一单元格尺寸
    }
};

ColorListWidget::ColorListWidget(QWidget *parent)
    : QWidget(parent)
    , table(new QTableWidget(this))
{
    setupUI();
}

void ColorListWidget::setupUI()
{
    // 表格设置
    table->setColumnCount(2);
    table->setHorizontalHeaderLabels({"Color Name", "Color Value"});
    table->verticalHeader()->setVisible(false);
    table->horizontalHeader()->setStretchLastSection(true);
    table->setSelectionMode(QAbstractItemView::NoSelection);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 设置列宽
    table->setColumnWidth(0, 150);
    table->setColumnWidth(1, 200);

    // 设置颜色列代理
    table->setItemDelegateForColumn(1, new ColorDelegate(this));

    // 布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(table);
    layout->setContentsMargins(0, 0, 0, 0);
}

void ColorListWidget::setColors(const QHash<QString, QColor> &colors)
{
    table->setRowCount(colors.size());

    // 获取排序后的颜色名称列表
    QStringList colorNames = colors.keys();
    std::sort(colorNames.begin(), colorNames.end(), [](const QString &a, const QString &b) {
        // 先按字母顺序排序
        // 特殊处理带数字的键（如primary_1, primary_2）
        return QString::compare(a, b, Qt::CaseInsensitive) < 0;

        // 如果需要数字顺序排序（primary_1 < primary_2），可以使用：
        // return a.compare(b, Qt::CaseInsensitive) < 0;
    });

    int row = 0;
    for (const QString &name : colorNames) {
        const QColor color = colors.value(name);

        // 颜色名称
        QTableWidgetItem *nameItem = new QTableWidgetItem(name);
        nameItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        table->setItem(row, 0, nameItem);

        // 颜色值（存储QColor对象）
        QTableWidgetItem *colorItem = new QTableWidgetItem;
        colorItem->setData(Qt::DisplayRole, color);
        table->setItem(row, 1, colorItem);

        ++row;
    }

    // 自动调整行高
    table->resizeRowsToContents();
}
