#include "titlebar.h"

#include <QToolButton>
#include <QLabel>
#include <QHBoxLayout>
#include <QDebug>
#include <QLinearGradient>
#include <QPainter>

TitleBar::TitleBar(QMainWindow *parent)
    : FramelessTitleBar(parent)
    , QWidget(parent)
{
    parent->setAttribute(Qt::WA_StyledBackground, true);
    parent->setWindowFlags(Qt::WindowSystemMenuHint |
                           Qt::WindowMinimizeButtonHint |
                           Qt::WindowMaximizeButtonHint |
                           Qt::FramelessWindowHint |
                           Qt::Window
                           );

    parent->setMenuWidget(this);
    parent->setMouseTracking(true);
    parent->raise();
    parent->activateWindow();

    initUI();
}

void TitleBar::setTitleBarBgColor(const QColor &color)
{
    QString style = QString("QWidget#TitleWidget, QToolBar#qtc_sys_toolbar {"
                            "background: %1;"
                            "}").arg(color.name());
    this->setStyleSheet(style);
}

void TitleBar::paintEvent(QPaintEvent* e)
{
    // 不知道为什么样式表不起作用，所以只能重写paintEvent函数，实现标题栏的颜色
    QPainter p(this);

    QLinearGradient graient(0, 0, this->rect().width(), this->rect().height());
    graient.setColorAt(0, "949B8D");
    graient.setColorAt(0.5, "#475048");
    graient.setColorAt(1, "#8D9487");
    p.setBrush(graient);
    p.setPen(Qt::transparent);

    p.drawRect(this->rect());
    p.end();
}

void TitleBar::resizeEvent(QResizeEvent *e)
{
    int w1 = this->rect().width();
    int h1 = this->rect().height();
    int w2 = menuButton->rect().width();
    int h2 = menuButton->rect().height();
    int x = w1 - w2 - 120;
    int y = h1 - h2 - 5;
    menuButton->move(x, y);
}

void TitleBar::initUI()
{
    FramelessTitleBar::setTitleWidget(this);

    FramelessTitleBar::setCloseBySystemButton(true);
    FramelessTitleBar::logoButton()->setIconSize(QSize(50, 50));

    QHBoxLayout *layout = new QHBoxLayout();
    layout->setContentsMargins(1, 1, 1, 1);
    layout->setSpacing(0);
    layout->addWidget(FramelessTitleBar::logoButton());
    //layout->addStretch();
    layout->addWidget(FramelessTitleBar::titleLabel());
    layout->addStretch();
    layout->addWidget(FramelessTitleBar::systemToolBar());
    this->setLayout(layout);

    QWidget::setObjectName("TitleWidget");

    menuButton = new QPushButton(this);
    menuButton->setObjectName("MenuButton");
    menuButton->setFixedSize(20, 20);
    menuButton->setToolTip("菜单显示");
}
