#include "piechart.h"

#include <QVBoxLayout>

PieChart::PieChart(QWidget *parent)
    : QWidget(parent)
{
    initChart();
}

PieChart::~PieChart()
{
}

void PieChart::initChart()
{
    // 饼状图
    pie_series = new QPieSeries(this);
    connect(pie_series, SIGNAL(clicked(QPieSlice *)), this, SLOT(onPieSeriesClicked(QPieSlice *)));

    // 定义各扇形切片的颜色
    static const QStringList list_pie_color = {
        "#6480D6",
        "#A1DC85",
        "#FFAD25",
        "#FF7777",
    };

    // 设置数据
    QList<qreal> list_data = {3.1, 3.2, 3.3, 3.4};
    QStringList labels = {"良品", "坏品", "未知", "总数"};

    // 扇形
    for (int i = 0; i < list_pie_color.size(); i++)
    {
        QPieSlice *pie_slice = new QPieSlice(this);
        pie_slice->setLabelVisible(true);
        pie_slice->setValue(list_data[i]);
        pie_slice->setLabel(labels[i]);
        pie_slice->setColor(list_pie_color[i]);
        pie_slice->setLabelColor(list_pie_color[i]);
        pie_slice->setBorderColor(list_pie_color[i]);
        pie_series->append(pie_slice);
    }

    // 图表视图
    QChart *chart = new QChart;
    chart->setBackgroundVisible(false);
    chart->setObjectName("PieChartChart");
    chart->setTitle("XXX统计饼图");
    // 设置暗黑主题
    chart->setTheme(QChart::ChartThemeDark);

    // 标题字体
    QFont font = qApp->font();
    font.setBold(true);
    font.setPointSize(16);
    chart->setTitleFont(font);

    // 加入饼图
    chart->addSeries(pie_series);
    chart->setAnimationOptions(QChart::SeriesAnimations);

    // 图例
    chart->legend()->setAlignment(Qt::AlignBottom);
    chart->legend()->setBackgroundVisible(false);

    // 加入绘画视图
    QChartView *chartView = new QChartView(this);    
    chartView->setObjectName("PieChartView");
    chartView->setRenderHint(QPainter::Antialiasing);
    chartView->setChart(chart);
//    chartView->setStyleSheet(R"(border:none;)");

    // 加入布局
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(chartView);

    this->setLayout(layout);
}

// 点击饼图
void PieChart::onPieSeriesClicked(QPieSlice *slice)
{
    slice->setExploded(!slice->isExploded());
}
