#include "InjuryAnalysisUI.h"
#include "InjuryDatabase.h"
#include "ui_InjuryAnalysisUI.h"
#include <QMessageBox>
#include <QWidget>
#include <QVBoxLayout>

// 使用QtCharts命名空间
QT_CHARTS_USE_NAMESPACE

InjuryAnalysisUI::InjuryAnalysisUI(QWidget* parent):
    QWidget(parent),
    ui(new Ui::InjuryAnalysisUI),
    chart(nullptr),
    chartView(nullptr)
{
    ui->setupUi(this);
    setWindowTitle("伤情态势分析界面");
    //resize(600,400);

    InjuryDatabase injurydatabase;
    QList<Injury> resultNow;
    injurydatabase.select_all(resultNow);//获取所有伤员数据
    result = resultNow;

    //添加一个scrollArea来将信息显示出来
    ui->scrollArea->setWidgetResizable(true);//可以拖动滚动条
    //竖滚动条和横滚动条都可以一直显示
    ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    //设置主界面的实际界面
    ui->scrollArea->setWidget(ui->scrollAreaWidgetContents);
    
    // 移除表格相关部分，只保留柱状图

    //对信息进行分类统计分析
    int sum = result.length();
    ui->sumLabel->setText(QString::number(sum));
    int rank0Sum = 0;
    int rank1Sum = 0;
    int rank2Sum = 0;
    for(int i = 0; i<sum; i++)
    {
        if(result[i].rank==0)
            rank0Sum++;
        else if(result[i].rank==1)
            rank1Sum++;
        else if(result[i].rank==2)
            rank2Sum++;
    }
    ui->rank0Label->setText(QString::number(rank0Sum));
    ui->rank1Label->setText(QString::number(rank1Sum));
    ui->rank2Label->setText(QString::number(rank2Sum));

    // 创建并显示柱状图
    createBarChart();
}

InjuryAnalysisUI::~InjuryAnalysisUI()
{
    delete ui;
    if (chart) {
        delete chart;
    }
    // chartView会被自动删除，因为它作为布局的一部分
}

void InjuryAnalysisUI::createBarChart()
{
    // 创建柱状图数据集
    QBarSet *lightSet = new QBarSet("轻微");
    QBarSet *moderateSet = new QBarSet("一般");
    QBarSet *severeSet = new QBarSet("严重");
    
    // 设置柱状图的颜色
    lightSet->setColor(QColor(0, 255, 0));  // 绿色
    moderateSet->setColor(QColor(255, 255, 0));  // 黄色
    severeSet->setColor(QColor(255, 0, 0));  // 红色
    
    // 获取各等级伤员数量
    int rank0Sum = 0;
    int rank1Sum = 0;
    int rank2Sum = 0;
    for(int i = 0; i < result.length(); i++) {
        if(result[i].rank == 0)
            rank0Sum++;
        else if(result[i].rank == 1)
            rank1Sum++;
        else if(result[i].rank == 2)
            rank2Sum++;
    }
    
    // 添加数据到柱状图
    *lightSet << rank0Sum;
    *moderateSet << rank1Sum;
    *severeSet << rank2Sum;
    
    // 创建柱状图系列
    QBarSeries *series = new QBarSeries();
    series->append(lightSet);
    series->append(moderateSet);
    series->append(severeSet);
    
    // 增加柱子宽度
    series->setBarWidth(0.8);
    
    // 创建柱状图
    chart = new QChart();
    chart->addSeries(series);
    // 移除标题
    chart->setTitle("");
    chart->setAnimationOptions(QChart::SeriesAnimations);
    
    // 创建坐标轴
    QStringList categories;
    categories << "";  // 使用空字符串替代"伤情等级"
    QBarCategoryAxis *axisX = new QBarCategoryAxis();
    axisX->append(categories);
    chart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);
    
    QValueAxis *axisY = new QValueAxis();
    // 设置Y轴范围，留出一些顶部空间
    int maxValue = qMax(qMax(rank0Sum, rank1Sum), rank2Sum);
    axisY->setRange(0, maxValue + 1);
    // 显示Y轴刻度但不显示标题
    axisY->setTitleText("");
    axisY->setLabelsVisible(true);  // 确保显示Y轴标签
    // 设置Y轴刻度数量，使刻度更合理
    axisY->setTickCount(maxValue <= 5 ? maxValue + 2 : 6);
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);
    
    // 设置图例
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);
    chart->legend()->setMarkerShape(QLegend::MarkerShapeRectangle);
    // 减小图例的大小，使其更紧凑
    QFont legendFont = chart->legend()->font();
    legendFont.setPointSize(8);
    chart->legend()->setFont(legendFont);
    
    // 创建图表视图并添加到布局中
    chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
    
    // 设置适当的图表边距，左侧留出空间显示数字
    chart->setMargins(QMargins(5, 5, 5, 5));
    chart->setBackgroundVisible(false);  // 移除背景
    
    // 将chartView直接添加到scrollAreaWidgetContents中
    QVBoxLayout *chartLayout = new QVBoxLayout(ui->scrollAreaWidgetContents);
    chartLayout->addWidget(chartView);
    chartLayout->setContentsMargins(0, 0, 0, 0);  // 移除布局边距
    
    // 增加顶部空间，减少底部空间
    ui->scrollAreaWidgetContents->setMinimumHeight(250);  // 设置足够的高度
    ui->scrollAreaWidgetContents->setLayout(chartLayout);
}

void InjuryAnalysisUI::updateBarChart()
{
    // 如果已经创建了图表，则更新数据
    if (chart) {
        // 获取各等级伤员数量
        int rank0Sum = 0;
        int rank1Sum = 0;
        int rank2Sum = 0;
        for(int i = 0; i < result.length(); i++) {
            if(result[i].rank == 0)
                rank0Sum++;
            else if(result[i].rank == 1)
                rank1Sum++;
            else if(result[i].rank == 2)
                rank2Sum++;
        }
        
        // 获取图表的系列
        QBarSeries *series = qobject_cast<QBarSeries*>(chart->series().at(0));
        if (series && series->count() >= 3) {
            // 更新三个柱状图的数据
            series->barSets().at(0)->replace(0, rank0Sum);
            series->barSets().at(1)->replace(0, rank1Sum);
            series->barSets().at(2)->replace(0, rank2Sum);
            
            // 更新Y轴范围
            QValueAxis *axisY = qobject_cast<QValueAxis*>(chart->axes(Qt::Vertical).at(0));
            if (axisY) {
                axisY->setRange(0, qMax(qMax(rank0Sum, rank1Sum), rank2Sum) + 1);
            }
        }
    }
}

void InjuryAnalysisUI::on_searchButton_clicked()
{
    QString userInput = ui->searchInput->text();
    int searchIndex = -1;
    if(!userInput.isEmpty())
    {
        for(int i = 0; i<result.length(); i++)
        {
            if(QString::compare(userInput,result[i].id)==0)
            {
                searchIndex = i;
                break;
            }
        }
    }
    
    if(searchIndex == -1)
    {
        QMessageBox::warning(this, tr("查找"), tr("找不到id为 %1 的伤员！").arg(userInput));
    }
    else
    {
        QString rank = QString::number(result[searchIndex].rank);
        QString lon = QString::number(result[searchIndex].lon);
        QString lat = QString::number(result[searchIndex].lat);
        QMessageBox::information(this, tr("查找"), tr("伤员id：%1  伤情等级：%2  位置经纬度：%3 ，%4 ").arg(userInput,rank,lon,lat));
    }
}



