#include "attribute_edit.h"

#include "ui_attribute_edit.h"

CAttributeEdit::CAttributeEdit(QWidget* parent) : QDialog(parent), ui(new Ui::CAttributeEdit)
{
    ui->setupUi(this);

    setWindowTitle(u8"属性编辑");
    setMinimumSize(600, 760);

    connect(ui->btnOk, &QPushButton::clicked, this, &CAttributeEdit::handle_ok);
    connect(ui->btnCancel, &QPushButton::clicked, this, [&]() {
        is_ok_ = false;
        close();
    });
}

void CAttributeEdit::handle_ok()
{
    property_.clear();
    int row = table_->rowCount();
    for (int i = 0; i < row; ++i) {
        QString key = table_->item(i, 0)->text();
        QString value = table_->item(i, 1)->text();
        property_.emplace_back(key.toStdString().c_str(), value.toStdString().c_str());
    }
    is_ok_ = true;
    close();
}

CAttributeEdit::~CAttributeEdit()
{
    delete ui;
}

void CAttributeEdit::showEvent(QShowEvent* event)
{
    show_before();
    QDialog::showEvent(event);
}

void CAttributeEdit::set_attribute(const Property_t& property, bool is_key_edit)
{
    property_.clear();
    property_ = property;
    is_key_edit_ = is_key_edit;
}

void CAttributeEdit::get_attribute(Property_t& property)
{
    property.clear();
    property = property_;
}

void CAttributeEdit::show_before()
{
    init_table();

    is_ok_ = false;

    for (auto i = 0; i < property_.size(); ++i) {
        int row = table_->rowCount();
        table_->insertRow(row);

        QTableWidgetItem* pkey = new QTableWidgetItem();
        pkey->setText(property_[i].key.c_str());
        pkey->setFlags(pkey->flags() & ~Qt::ItemIsEditable);
        table_->setItem(row, 0, pkey);

        QTableWidgetItem* pvalue = new QTableWidgetItem();
        pvalue->setText(property_[i].value.c_str());
        table_->setItem(row, 1, pvalue);

        if (!is_key_edit_ && i == 0) {
            pvalue->setFlags(pvalue->flags() & ~Qt::ItemIsEditable);
        }
    }
}

void CAttributeEdit::init_table()
{
    if (table_ == nullptr) {
        QStringList list;
        list << u8"属性" << u8"值";
        table_ = new QTableWidget();
        table_->setColumnCount(list.size());
        table_->setHorizontalHeaderLabels(list);
        table_->setSelectionBehavior(QAbstractItemView::SelectRows);
        table_->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
        table_->setColumnWidth(0, 100);
        table_->setColumnWidth(1, 550);
        QHBoxLayout* ly = new QHBoxLayout();
        ly->addWidget(table_);
        ui->widget->setLayout(ly);
    } else {
        table_->clearContents();
        table_->setRowCount(0);
    }
}