#include "buttondelegate.h"
#include <QStyledItemDelegate>
#include <qDebug>

ButtonDelegate::ButtonDelegate(int buttonColumn,QObject *parent) : QStyledItemDelegate(parent),buttonColumn(buttonColumn){
    // 构造函数实现（如果需要）
}

void ButtonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    if (index.column() == buttonColumn) {
        QStyleOptionButton buttonOption1;
        QStyleOptionButton buttonOption2;
        QRect rect = option.rect;
        rect.adjust(0, 0, -1, -1); // 调整大小以适应边框

        // 第一个按钮
        buttonOption1.rect = rect.adjusted(0, 0, -rect.width() / 2, 0);
        buttonOption1.text = "删除"; // 按钮文本
        buttonOption1.state = QStyle::State_Enabled;
        QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption1, painter);

        // 第二个按钮
        buttonOption2.rect = rect.adjusted(rect.width() / 2, 0, 0, 0);
        buttonOption2.text = "编辑"; // 按钮文本
        buttonOption2.state = QStyle::State_Enabled;
        QApplication::style()->drawControl(QStyle::CE_PushButton, &buttonOption2, painter);
    } else {
        QStyledItemDelegate::paint(painter, option, index);
    }
}


bool ButtonDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)  {
    if (index.column() == buttonColumn && event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        QRect rect = option.rect;
        rect.adjust(0, 0, -1, -1); // 调整大小以适应边框

        // 检测第一个按钮的点击
        QRect button1Rect = rect.adjusted(0, 0, -rect.width() / 2, 0);
        if (button1Rect.contains(mouseEvent->pos())) {
            handleButtonClick (index.row(),1); // 处理第一个按钮点击
            return true;
        }

        // 检测第二个按钮的点击
        QRect button2Rect = rect.adjusted(rect.width() / 2, 0, 0, 0);
        if (button2Rect.contains(mouseEvent->pos())) {
            handleButtonClick(index.row(), 2); // 处理第二个按钮点击
            return true;
        }
    }
    return QStyledItemDelegate::editorEvent(event, model, option, index);
}


void ButtonDelegate::handleButtonClick(int row,int button) {
    // qDebug() << "行号: " << row << ", 按钮: " << button;
    emit buttonClicked(row, button); // 发射信号
    }
