#include "coalstaticwidget.h"
#include "ui_coalstaticwidget.h"

#include <QHttpPart>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include <QUrlQuery>

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

    m_systemSetting = new QSettings("system.ini", QSettings::IniFormat);

    ui->dateTimeEdit_startTime->setDateTime(QDateTime::currentDateTime().addSecs(-8 * 3600));

    initCoalStatisticsBarChart();
}

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

void CoalStaticWidget::initCoalStatisticsBarChart()
{
    // 创建图表
    m_chart = new QChart();
    m_chart->setBackgroundBrush(Qt::transparent);
    m_chart->setMargins(QMargins(0, 0, 0, 0));
    m_chart->legend()->hide();

    // 创建图表视图并设置
    m_chartView = new QChartView(m_chart);
    m_chartView->setBackgroundBrush(Qt::transparent);
    m_chartView->setStyleSheet("background: transparent;");
    m_chartView->setRenderHint(QPainter::Antialiasing);
    m_chartView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 创建柱状图
    m_series = new QBarSeries();
    m_chart->addSeries(m_series);

    // 设置X轴为时间
    m_axisX = new QBarCategoryAxis();
    m_axisX->setTitleBrush(QBrush(QColor(151, 151, 151)));
    m_axisX->setLinePen(QPen(QColor(40, 46, 48)));
    m_axisX->setLabelsColor(QColor(151, 151, 151));

    m_axisX->setGridLineVisible(false);

    QDateTime currentTime = QDateTime::currentDateTime();
    QList<QString> timeList = getLastSixFullHours(currentTime);
    m_axisX->append(timeList);

    m_chart->addAxis(m_axisX, Qt::AlignBottom);
    m_series->attachAxis(m_axisX);

    // 设置Y轴为百分比
    m_axisY = new QValueAxis;
    m_axisY->setTitleText("吨");
    m_axisY->setTitleBrush(QBrush(QColor(151, 151, 151)));
    m_axisY->setLinePen(QPen(QColor(40, 46, 48)));
    m_axisY->setLabelsColor(QColor(151, 151, 151));
    m_axisY->setGridLineColor(QColor(40, 46, 48));
    m_axisY->setRange(0, 100);
    m_axisY->setTitleFont(QFont("Arial", 10));
    m_axisY->setTitleVisible(true);

    m_chart->addAxis(m_axisY, Qt::AlignLeft);
    m_series->attachAxis(m_axisY);

    // 获取 widget_coalChart 的布局
    QVBoxLayout* layout = static_cast<QVBoxLayout*>(ui->widget_coalStatisticsChart->layout());
    if (!layout) {
        // 如果没有布局，创建一个新的布局并设置
        layout = new QVBoxLayout(ui->widget_coalStatisticsChart);
        ui->widget_coalStatisticsChart->setLayout(layout);
    }

    // 设置布局参数
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    // 确保视图只添加一次
    if (!layout->indexOf(m_chartView) != -1) {
        layout->addWidget(m_chartView);
    }
}

QList<QString> CoalStaticWidget::getLastSixFullHours(const QDateTime& currentTime)
{
    // 将当前时间设置为整点
    QDateTime roundedTime = currentTime;
    roundedTime.setTime(QTime(currentTime.time().hour(), 0)); // 设置时间到整点

    bool insertTime = false; // 用于控制每隔一个插入时间，其他插入0

    // 计算距当前整点数的前六个小时
    QList<QString> timeList;
    for (int i = 8; i >= 1; --i) {
        QDateTime prevHour = roundedTime.addSecs(-i * 3600); // 向前推算每个整点
        timeList.append(prevHour.toString("HH:mm"));
    }

    return timeList;
}

void CoalStaticWidget::updateCoalStatisticsChart(const QMap<QString, double>& volumeDataMap)
{

    // 清除旧数据
    m_series->clear();

    // 创建新的数据集
    QBarSet* set = new QBarSet("煤量");

    // 用于存储时间标签
    QList<QString> categories;

    // 将字符串格式的时间转换为 QDateTime，并准备时间标签
    for (auto it = volumeDataMap.begin(); it != volumeDataMap.end(); ++it) {

        // 根据选择的时间单位，格式化时间标签
        QString label;
        if (ui->comboBox_unit->currentText() == QStringLiteral("时")) {
            QDateTime time = QDateTime::fromString(it.key(), "yyyy-MM-dd HH");
            label = time.toString("H");
        } else if (ui->comboBox_unit->currentText() == QStringLiteral("日")) {
            QDateTime time = QDateTime::fromString(it.key(), "yyyy-MM-dd");
            label = time.toString("dd"); // 使用 'dd' 来格式化日期
        } else if (ui->comboBox_unit->currentText() == QStringLiteral("月")) {
            QDateTime time = QDateTime::fromString(it.key(), "yyyy-MM");
            label = time.toString("MM"); // 使用 'MM' 来格式化月份
        } else if (ui->comboBox_unit->currentText() == QStringLiteral("年")) {
            QDateTime time = QDateTime::fromString(it.key(), "yyyy");
            label = time.toString("yyyy"); // 使用 'yyyy' 来格式化年份
        }

        *set << it.value(); // 将数据量加入到数据集

        //        emit querySuccessInfo(QString::number(it.value()));

        categories.append(label); // 将时间标签添加到列表
    }

    // 将数据集添加到 series
    m_series->append(set);

    // 使用 QCategoryAxis 设置 X 轴为字符串格式的时间标签
    m_axisX->clear(); // 清除之前的标签
    m_axisX->append(categories); // 将新的时间标签添加到 X 轴

    // 更新 Y 轴范围
    double maxValue = *std::max_element(volumeDataMap.begin(), volumeDataMap.end());
    m_axisY->setRange(0, maxValue + 10); // 设置为最大值并留出余量
}

void CoalStaticWidget::getCoalStatisInfoByHttpRequest(const QString& beginTime, const QString& endTime, const QString& statisticUnit)
{
    // 使用类成员变量 QNetworkAccessManager
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);
    QString coalStaticUrl = m_systemSetting->value("coalStaticInterface/url").toString();

    // URL
    QUrl url(coalStaticUrl);
    QNetworkRequest request(url);

    // Form data
    QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    // begin_time 参数
    QHttpPart beginTimePart;
    beginTimePart.setHeader(QNetworkRequest::ContentDispositionHeader,
        QVariant("form-data; name=\"begin_time\""));
    beginTimePart.setBody(beginTime.toUtf8());

    // end_time 参数
    QHttpPart endTimePart;
    endTimePart.setHeader(QNetworkRequest::ContentDispositionHeader,
        QVariant("form-data; name=\"end_time\""));
    endTimePart.setBody(endTime.toUtf8());

    // 统计单位参数
    QHttpPart statisticUnitPart;
    statisticUnitPart.setHeader(QNetworkRequest::ContentDispositionHeader,
        QVariant("form-data; name=\"statistic_unit\""));
    statisticUnitPart.setBody(statisticUnit.toUtf8());

    // 将表单字段附加到 multipart 请求体中
    multiPart->append(beginTimePart);
    multiPart->append(endTimePart);
    multiPart->append(statisticUnitPart);

    // 发送 POST 请求
    QNetworkReply* reply = manager->post(request, multiPart);

    // 连接信号和槽
    QObject::connect(reply, &QNetworkReply::finished, [this, reply, multiPart]() {
        if (reply->error() == QNetworkReply::NoError) {
            // 处理成功的响应
            QByteArray responseData = reply->readAll();
            QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
            QJsonObject jsonObj = jsonResponse.object();

            int code = jsonObj["code"].toInt();
            QString message = jsonObj["message"].toString();
            QJsonObject data = jsonObj["data"].toObject();
            m_toalValue = data["total_volum"].toDouble();
            QJsonObject statisticUnitVolum = data["statistic_unit_volum"].toObject();

            // int statisticUnitVolumSize = statisticUnitVolum.count();
            // QString statisticUnitVolumSizeString = "查询结果数" + QString::number(statisticUnitVolumSize);
            // emit querySuccessInfo(statisticUnitVolumSizeString);
            // QString totalVolumeString = "总吨数" + QString::number(m_toalValue);
            // emit querySuccessInfo(totalVolumeString);

            ui->label_totalVolume->clear();
            ui->label_totalVolume->setText(QString("煤量总计:%1吨").arg(m_toalValue * m_systemSetting->value("system/different").toDouble()));

            m_volumeDataMap.clear();

            // 计算整体需要减少的总量
            double reduction = m_toalValue * m_systemSetting->value("system/different").toDouble(); // 减去50%

            // 计算每个值应该减少的比例
            //  double currentReduction = 0;

            // 遍历 statistic_unit_volum 中的键值对并存入 volumeDataMap
            for (const QString& key : statisticUnitVolum.keys()) {
                double value = statisticUnitVolum.value(key).toDouble();
                // 计算每个值所减少的比例
                //  double proportionalReduction = (value / m_toalValue) * reduction;
                m_volumeDataMap.insert(key, value /*- proportionalReduction*/);
                //  currentReduction += proportionalReduction;
            }

            // 更新查询的数据至图表
            if (!m_volumeDataMap.isEmpty()) {
                updateCoalStatisticsChart(m_volumeDataMap);
            }

        } else {
            // 处理错误
            QString errorString = reply->errorString();

            emit querySuccessInfo(errorString);
            qDebug() << "Error:" << errorString;
        }

        // 清理资源
        reply->deleteLater();
        multiPart->deleteLater();
    });
}

void CoalStaticWidget::on_pushButton_clicked()
{
    // 时间范围
    QString beginTimeStr = ui->dateTimeEdit_startTime->text();
    QString endTimeStr = ui->dateTimeEdit_endTime->text();

    // 创建 QDateTime 对象
    QDateTime beginTime = QDateTime::fromString(beginTimeStr, "yyyy/MM/d H:mm");
    QDateTime endTime = QDateTime::fromString(endTimeStr, "yyyy/MM/d H:mm");

    // 格式化为 "yyyy-MM-d H" 形式
    QString formattedBeginTime = beginTime.toString("yyyy-MM-dd HH");
    QString formattedEndTime = endTime.toString("yyyy-MM-dd HH");

    // 统计单位
    QString statisticUnit = ui->comboBox_unit->currentText();

    //    emit querySuccessInfo("查询起始时间：" + formattedBeginTime);
    //    emit querySuccessInfo("查询终止时间：" + formattedEndTime);

    getCoalStatisInfoByHttpRequest(formattedBeginTime, formattedEndTime, statisticUnit);
}
