#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QTimer>
#include "SerialConfig.h"
#include "serialportmanager.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
#include <QHBoxLayout>
#include <QChart>
#include <QValueAxis>
#include <QFont>
#include "databaseutils.h"
#include <QFileDialog>
#include "ExportThread.h"
#include <QMediaPlayer>
#include <QKeyEvent>
#include "passworddialog.h"
#include <QApplication>

using namespace QtCharts;
QT_CHARTS_USE_NAMESPACE

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow), serialPortManager(new SerialPortManager(this)), serialConfigDialog(new SerialConfig(this)), player(new QMediaPlayer(this))
//    , hidReader(new HIDReader(this))
{
    ui->setupUi(this);

    // 设置窗口最小大小和默认大小
    this->setMinimumSize(1200, 750);
    this->resize(1400, 950);

    ui->label_7->setFixedSize(100, 100);
    ui->lcdNumber->setFixedSize(450, 100);

    // 创建一个白色背景的QWidget
    QWidget *backgroundWidget = new QWidget;
    backgroundWidget->setStyleSheet("background-color: white; border-radius: 20px;");

    // 创建水平布局
    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->setSpacing(40);
    // 添加第一个控件（label_7）
    hLayout->addWidget(ui->label_7);

    // 创建并添加第二个垂直布局（link_button 和 link_label），并设置最大高度为65
    QVBoxLayout *vLayout1 = new QVBoxLayout;
    vLayout1->setSpacing(2);
    vLayout1->setContentsMargins(0, 0, 0, 0);
    ui->link_button->setMinimumHeight(80);
    ui->link_button->setMinimumWidth(80);
    ui->link_button->setMaximumHeight(80);
    ui->link_button->setMaximumWidth(80);
    ui->link_label->setMinimumHeight(25);
    ui->link_label->setMinimumWidth(80);
    ui->link_label->setMaximumHeight(25);
    vLayout1->addWidget(ui->link_button, 0, Qt::AlignHCenter);
    vLayout1->addWidget(ui->link_label, 0, Qt::AlignHCenter);
    hLayout->addLayout(vLayout1);

    // 创建并添加第三个垂直布局（auto_button 和 auto_label），并设置最大高度为65
    QVBoxLayout *vLayout2 = new QVBoxLayout;
    vLayout2->setSpacing(2);
    vLayout2->setContentsMargins(0, 0, 0, 0);
    ui->auto_button->setMinimumHeight(80);
    ui->auto_button->setMinimumWidth(80);
    ui->auto_button->setMaximumHeight(80);
    ui->auto_button->setMaximumWidth(80);
    ui->auto_label->setMinimumHeight(25);
    ui->auto_label->setMinimumWidth(80);
    ui->auto_label->setMaximumHeight(25);
    vLayout2->addWidget(ui->auto_button, 0, Qt::AlignHCenter);
    vLayout2->addWidget(ui->auto_label, 0, Qt::AlignHCenter);
    hLayout->addLayout(vLayout2);

    // 创建并添加第四个垂直布局（manual_button 和 manual_label），并设置最大高度为65
    QVBoxLayout *vLayout3 = new QVBoxLayout;
    vLayout3->setSpacing(2);
    vLayout3->setContentsMargins(0, 0, 0, 0);
    ui->manual_button->setMinimumHeight(80);
    ui->manual_button->setMinimumWidth(80);
    ui->manual_button->setMaximumHeight(80);
    ui->manual_button->setMaximumWidth(80);
    ui->manual_label->setMinimumHeight(25);
    ui->manual_label->setMinimumWidth(80);
    ui->manual_label->setMaximumHeight(25);
    vLayout3->addWidget(ui->manual_button, 0, Qt::AlignHCenter);
    vLayout3->addWidget(ui->manual_label, 0, Qt::AlignHCenter);
    hLayout->addLayout(vLayout3);

    // 创建并添加第五个垂直布局（excel_b 和 label_5），并设置最大高度为65
    QVBoxLayout *vLayout4 = new QVBoxLayout;
    vLayout4->setSpacing(2);
    vLayout4->setContentsMargins(0, 0, 0, 0);
    ui->excel_b->setMinimumHeight(80);
    ui->excel_b->setMinimumWidth(80);
    ui->excel_b->setMaximumHeight(80);
    ui->excel_b->setMaximumWidth(80);
    ui->label_5->setMinimumHeight(25);
    ui->label_5->setMinimumWidth(80);
    ui->label_5->setMaximumHeight(25);
    vLayout4->addWidget(ui->excel_b, 0, Qt::AlignHCenter);
    vLayout4->addWidget(ui->label_5, 0, Qt::AlignHCenter);
    hLayout->addLayout(vLayout4);

    // 添加第六个控件（lcdNumber）
    hLayout->addWidget(ui->lcdNumber);

    // 创建并添加第七个垂直布局（tishi_label 和 info_label），并设置最大高度为65
    QVBoxLayout *vLayout5 = new QVBoxLayout;
    //        ui->tishi_label->setMaximumHeight(65);
    //        ui->info_label->setMaximumHeight(65);
    ui->tishi_label->setMaximumHeight(40);
    ui->tishi_label->setMaximumWidth(140);
    ui->tishi_label->setMinimumHeight(40);
    ui->tishi_label->setMinimumWidth(140);
    ui->info_label->setMaximumHeight(40);
    ui->info_label->setMaximumWidth(140);
    ui->info_label->setMinimumHeight(40);
    ui->info_label->setMinimumWidth(140);
    vLayout5->addWidget(ui->tishi_label);
    vLayout5->addWidget(ui->info_label);
    hLayout->addLayout(vLayout5);

    // 添加第八个控件（label_img）
    //       hLayout->addWidget(ui->label_img);

    // 将水平布局设置为一个QWidget的布局
    QWidget *hLayoutWidget = new QWidget;
    hLayoutWidget->setLayout(hLayout);
    hLayoutWidget->setFixedHeight(140);
    hLayoutWidget->setMinimumWidth(1280); // 最小宽度

    // 创建垂直布局并添加顶部和底部的垂直Spacer
    QVBoxLayout *backgroundLayout = new QVBoxLayout;
    backgroundLayout->setContentsMargins(0, 0, 0, 0);
    backgroundLayout->addSpacerItem(new QSpacerItem(20, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
    backgroundLayout->addWidget(hLayoutWidget, 0, Qt::AlignLeft); // 左对齐
    backgroundLayout->addSpacerItem(new QSpacerItem(20, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));

    // 将背景布局设置为背景小部件的布局
    backgroundWidget->setLayout(backgroundLayout);

    // 创建垂直布局，将背景小部件和tabWidget添加进去
    QVBoxLayout *vLayoutMain = new QVBoxLayout;
    vLayoutMain->addWidget(backgroundWidget);
    vLayoutMain->addWidget(ui->tabWidget, 1); // 让tabWidget占据剩余空间

    // 创建一个容器窗口并设置布局
    QWidget *container = new QWidget(this);
    container->setLayout(vLayoutMain);
    setCentralWidget(container);

    // 为每个tab页设置左上对齐的布局（跳过总览页面tab_1，因为它有自己的图表布局）
    for (int i = 0; i < ui->tabWidget->count(); ++i)
    {
        QWidget *tab = ui->tabWidget->widget(i);
        // 跳过总览页面（tab_1），它在disp_IIOT()中有自己的布局
        if (tab && tab != ui->tab_1)
        {
            // 获取tab内所有直接子控件
            QList<QWidget *> children = tab->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly);

            // 创建一个固定大小的容器来包含所有控件
            QWidget *contentWidget = new QWidget(tab);
            contentWidget->setFixedSize(1300, 750);

            // 将所有子控件移到contentWidget中
            for (QWidget *child : children)
            {
                child->setParent(contentWidget);
            }

            // 为tab设置布局，让contentWidget左上对齐
            QHBoxLayout *tabHLayout = new QHBoxLayout(tab);
            tabHLayout->setContentsMargins(0, 0, 0, 0);
            tabHLayout->addWidget(contentWidget, 0, Qt::AlignTop | Qt::AlignLeft);
            tabHLayout->addStretch(); // 右边填充空白

            QVBoxLayout *wrapperLayout = new QVBoxLayout();
            wrapperLayout->addLayout(tabHLayout);
            wrapperLayout->addStretch(); // 下边填充空白

            // 清除旧布局，设置新布局
            delete tab->layout();
            tab->setLayout(wrapperLayout);
        }
    }

    // 确保控件自适应大小
    container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    ui->label_16->setStyleSheet("QLabel { color : #02E5FF; }");

    QMessageBox *msgBox = new QMessageBox(this);
    msgBox->setIcon(QMessageBox::Warning);
    msgBox->setWindowTitle("初始化");
    msgBox->setText("自动连接中...");
    msgBox->setStandardButtons(QMessageBox::NoButton);

    msgBox->show();
    QTimer::singleShot(1000, msgBox, &QMessageBox::accept);
    QCoreApplication::processEvents();

    ui->lcdNumber->setDigitCount(8);
    ui->lcdNumber->display(888.888);

    //    ui->label_bg->lower();

    disp_canshu();

    daily_date = DatabaseUtils::get_today_daliy_t(daily_cnt, daily_cnt_manual,
                                                  daily_qualified_cnt, daily_cnt_over,
                                                  daily_cnt_down, daily_cnt_max,
                                                  daily_cnt_min);
    //    qDebug() << "daily_date" <<daily_date;

    disp_IIOT();

    serialPortManager->setConnectionMode(SerialPortManager::Auto);
    bool serial_status = serialPortManager->connectSerialPort();
    if (serial_status)
    {
        //        QMessageBox::information(this, "连接成功", "自动连接");
        ui->link_label->setText("已连接");
        ui->link_label->setStyleSheet("QLabel { color : green; }");
        ui->set_tx_lineEdit_1->setText("01");
        ui->set_tx_lineEdit_2->setText("9600");
        playConnState_ok();
    }
    else
    {
        playConnState_no();
        QMessageBox::warning(this, "连接失败", "请手动连接");
    }

    connect(ui->link_button, &QPushButton::clicked, this, &MainWindow::onLinkButtonClicked);
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::auto_query);

    timer2 = new QTimer(this);
    updateCharts();
    connect(timer2, &QTimer::timeout, this, &MainWindow::updateCharts);
    timer2->start(1800);

    //    connect(hidReader, &HIDReader::dataRead, this, &MainWindow::handleDataRead);
    //    hidReader->startReading();

    this->setFocus();

    connect(ui->xc_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);
    connect(ui->pwd_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);
    connect(ui->user_data_button, &QPushButton::clicked, this, &MainWindow::on_user_data_button_clicked_func);
    connect(ui->name_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);
    connect(ui->auto_value_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);
    connect(ui->res_max_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);
    connect(ui->delete_1_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);
    connect(ui->delete_2_button, &QPushButton::clicked, this, &MainWindow::onShowPasswordDialog);

    int rowCount = ui->tableWidget->rowCount();       // 获取行数
    int columnCount = ui->tableWidget->columnCount(); // 获取列数

    for (int row = 0; row < rowCount; ++row)
    {
        for (int col = 0; col < columnCount; ++col)
        {
            // 获取当前单元格的 item，如果不存在则创建一个
            QTableWidgetItem *item = ui->tableWidget->item(row, col);
            if (!item)
            {
                item = new QTableWidgetItem("");
                ui->tableWidget->setItem(row, col, item);
            }
            // 设置单元格为禁用状态
            item->setFlags(Qt::NoItemFlags);
        }
    }

    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 禁用选择和焦点
    ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
    ui->tableWidget->setFocusPolicy(Qt::NoFocus);

    // 设置扫码输入框为只读，防止直接输入，只通过扫码填充
    ui->user_data_lineEdit_2->setReadOnly(true);
    ui->user_data_lineEdit_3->setReadOnly(true);
    ui->user_data_lineEdit_2->setFocusPolicy(Qt::NoFocus);
    ui->user_data_lineEdit_3->setFocusPolicy(Qt::NoFocus);
}

MainWindow::~MainWindow()
{
    daily_qualified_l = daily_qualified_cnt / (daily_cnt * 1.0);
    DatabaseUtils::insertOrUpdateDailyData(daily_cnt, daily_cnt_manual, daily_qualified_cnt, daily_cnt_over, daily_cnt_down, daily_cnt_max, daily_cnt_min, daily_qualified_l);
    DatabaseUtils::closeDatabase();
    //    hidReader->stopReading();
    delete timer;
    delete ui;
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
}

void MainWindow::handleDataRead(const QByteArray &data)
{
    QString text = QString::fromUtf8(data);
    ui->user_data_lineEdit_2->setText(text);
    //    ui->textEdit->append(text);
}

void MainWindow::on_link_button_clicked()
{
    serialConfigDialog->scanSerialPorts();
}

void MainWindow::onLinkButtonClicked()
{
    if (serialConfigDialog->exec() == QDialog::Accepted)
    {
        QString portName = serialConfigDialog->getSerialPort();
        int baudRate = serialConfigDialog->getBaudRate().toInt();
        int dataBits = serialConfigDialog->getDataBits().toInt();
        int stopBits = serialConfigDialog->getStopBits().toInt();
        int parity = serialConfigDialog->getParity().toInt();

        serialPortManager->configureSerialPort(portName, baudRate, dataBits, stopBits, parity);
        serialPortManager->setConnectionMode(SerialPortManager::Manual);
        if (serialPortManager->connectSerialPort())
        {
            serialPort = serialPortManager->getSerialPort();
            QMessageBox::information(this, "连接成功", "已成功连接到串口 " + serialPort->portName());
            ui->link_label->setText("已连接");
            ui->link_label->setStyleSheet("QLabel { color : green; }");
            ui->set_tx_lineEdit_1->setText("01");
            ui->set_tx_lineEdit_2->setText("9600");
        }
        else
        {
            ui->link_label->setText("连接");
            ui->link_label->setStyleSheet("QLabel { color : black; }");
            QMessageBox::warning(this, "连接失败", "未找到合适的串口连接。");
            ui->set_tx_lineEdit_1->setText("");
            ui->set_tx_lineEdit_2->setText("");
        }
    }
}

void MainWindow::auto_query()
{
    if (auto_mode)
    {
        get_one_data();
    }
}

void MainWindow::on_auto_button_clicked()
{
    if (auto_mode)
    {
        ui->auto_label->setText("自动关闭");
        auto_mode = false;
        timer->stop();
    }
    else
    {
        ui->auto_label->setText("自动开启");
        auto_mode = true;
        get_one_data();
        timer->start(auto_time * 1000);
    }
}

void MainWindow::on_manual_button_clicked()
{
    //    playQualified();
    if (auto_mode)
    {
        ui->auto_label->setText("自动关闭");
        auto_mode = false;
        timer->stop();
    }
    get_one_data();
}

void MainWindow::get_one_data()
{

    ui->tishi_label->setText("获取中...");
    ui->tishi_label->setStyleSheet("QLabel { color : black; }");

    double zz_disp = serialPortManager->sendModbus_receive("010400000001", 7);
    //    qDebug() << "zz_disp:" <<zz_disp;

    // zz_disp = 3.1; // 测试数据

    if (zz_disp == -3)
    {
        ui->tishi_label->setText("超出设备量程");
        ui->tishi_label->setStyleSheet("QLabel { color : red; }");
        ui->info_label->setText("");
        ui->lcdNumber->display("---.---");
        // qDebug() << "00000";
        return;
    }
    else if (zz_disp == -2)
    {
        //        play_no_conn_res();
        ui->tishi_label->setText("未连接电阻");
        ui->tishi_label->setStyleSheet("QLabel { color : black; }");
        ui->info_label->setText("");
        ui->lcdNumber->display("---.---");
        // qDebug() << "00000";
        return;
    }
    else if (zz_disp == -1)
    {

        ui->tishi_label->setText("获取异常");
        ui->tishi_label->setStyleSheet("QLabel { color : black; }");
        ui->info_label->setText("");
        ui->lcdNumber->display("---.---");
        // qDebug() << "00000";
        //        if(auto_mode == false){
        null_cnt++;
        if (null_cnt > 2)
        {
            //                play_get_err();
            ui->info_label->setText("请检查连接");
            ui->info_label->setStyleSheet("QLabel { color : red; }");
            null_cnt = 0;
        }
        //        }
        return;
    }

    // 检测两个扫码值是否都为空
    if (sm_num.isEmpty() || hot_num.isEmpty())
    {
        if (scanTipLabel == nullptr)
        {
            scanTipLabel = new QLabel(this);
            scanTipLabel->setText("编码缺失，请先扫码！");
            scanTipLabel->setStyleSheet(
                "QLabel { "
                "background-color: #FFFBE6; "
                "border: 2px solid #FFD666; "
                "border-radius: 8px; "
                "padding: 15px 25px; "
                "font-size: 16px; "
                "font-weight: bold; "
                "color: #D48806; "
                "}");
            scanTipLabel->setAlignment(Qt::AlignCenter);
            scanTipLabel->adjustSize();
            // 设置为不获取焦点
            scanTipLabel->setFocusPolicy(Qt::NoFocus);
            scanTipLabel->setAttribute(Qt::WA_ShowWithoutActivating);
        }
        // 居中显示
        int x = (this->width() - scanTipLabel->width()) / 2;
        int y = (this->height() - scanTipLabel->height()) / 2;
        scanTipLabel->move(x, y);
        scanTipLabel->show();
        scanTipLabel->raise();
        return;
    }

    //    qDebug() << "zz_disp:" <<zz_disp;
    zz_disp = zz_disp - xc_sd;

    //    qDebug() << "zz_disp:" <<zz_disp;

    ui->lcdNumber->display(zz_disp);

    if (daily_one)
    {
        daily_cnt_min = zz_disp;
        daily_cnt_max = zz_disp;
        daily_one = false;
    }
    if (auto_mode)
    {
        auto_mode_flag = "自动获取";
    }
    else
    {
        auto_mode_flag = "手动获取";
    }

    if (zz_disp > max_res)
    {
        playUnqualified();
        daily_cnt_over++;
        up_cnt++;
        DatabaseUtils::update_Info_t("up_cnt", up_cnt);
        if (DatabaseUtils::insert_ResData(chexing, sm_num, hot_num, zz_disp, detect, "异常：过大", auto_mode_flag, name))
        {
            sm_num = "";
            hot_num = "";
            ui->user_data_lineEdit_2->clear();
            ui->user_data_lineEdit_3->clear();
        }
        ui->info_label->setText("阻值过大");
        ui->info_label->setStyleSheet("QLabel { color : red; }");
    }
    else if (zz_disp < min_res)
    {
        playUnqualified();
        down_cnt++;
        daily_cnt_down++;
        DatabaseUtils::update_Info_t("down_cnt", down_cnt);
        if (DatabaseUtils::insert_ResData(chexing, sm_num, hot_num, zz_disp, detect, "异常：过小", auto_mode_flag, name))
        {
            sm_num = "";
            hot_num = "";
            ui->user_data_lineEdit_2->clear();
            ui->user_data_lineEdit_3->clear();
        }
        ui->info_label->setText("阻值过小");
        ui->info_label->setStyleSheet("QLabel { color : red; }");
    }
    else
    {
        playQualified();
        qualified_cnt++;
        daily_qualified_cnt++;
        DatabaseUtils::update_Info_t("qualified_cnt", qualified_cnt);
        if (DatabaseUtils::insert_ResData(chexing, sm_num, hot_num, zz_disp, detect, "合格", auto_mode_flag, name))
        {
            sm_num = "";
            hot_num = "";
            ui->user_data_lineEdit_2->clear();
            ui->user_data_lineEdit_3->clear();
        }
        ui->info_label->setText("阻值正常");
        ui->info_label->setStyleSheet("QLabel { color : green; }");
    }

    if (zz_disp > daily_cnt_max)
    {
        daily_cnt_max = zz_disp;
    }
    if (zz_disp < daily_cnt_min)
    {
        daily_cnt_min = zz_disp;
    }

    all_count++;
    manual_cnt++;
    daily_cnt++;
    daily_cnt_manual++;

    DatabaseUtils::update_Info_t("all_count", all_count);
    DatabaseUtils::update_Info_t("manual_cnt", manual_cnt);
    ui->tishi_label->setText(QString("今日检测：%1 ").arg(daily_cnt));
    ui->tishi_label->setStyleSheet("QLabel { color : green; }");
}

/**
  满量程对应值0103 1001 0002
  零值对应值 1002


输入满量程对应值        1001
输入零值对应值         1002
显示值的小数位数        1003
J1报警模式                1004
J1报警值或J1区间起点值   1005
J1回差值或J1区间终点值   1006
J2报警模式              1007
J2报警值或J2区间起点值   1008
J2回差值或J2区间终点值   1009
变送输出类型              100A
输出高限对应值             100B
输出低限对应值             100C
/从机地址                100D
/通讯波特率               100E

数字滤波系数              2000
清零值/偏移值             2001
测量线制                2005
参数显示/隐藏             2006


  */

void MainWindow::onExportSucceeded()
{
    QMessageBox::information(this, tr("导出"), tr("导出表格成功"));
}

void MainWindow::onExportFailed(const QString &error)
{
    QMessageBox::warning(this, tr("导出失败"), error);
}

void MainWindow::on_excel_b_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Excel File"), "", tr("Excel Files (*.xlsx *.xls)"));
    if (fileName.isEmpty())
    {
        return;
    }

    ExportThread *thread = new ExportThread(fileName, all_count, auto_cnt, manual_cnt, qualified_cnt, up_cnt, down_cnt, this);
    connect(thread, &ExportThread::exportSucceeded, this, &MainWindow::onExportSucceeded);
    connect(thread, &ExportThread::exportFailed, this, &MainWindow::onExportFailed);
    connect(thread, &QThread::finished, thread, &QObject::deleteLater);
    thread->start();

    //    if (totalRows == 0) {
    //        QMessageBox::warning(this, tr("Export to Excel"), tr("The table is empty. There is no data to export."));
    //        return;
    //    }

    //    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Excel File"), "", tr("Excel Files (*.xlsx *.xls)"));
    //    if (fileName.isEmpty()) {
    //        qDebug() << "No file selected";
    //        return;
    //    }

    //    QMessageBox::information(this, tr("导出"), tr("导出表格中......"));
    ////    QMessageBox *msgBox = new QMessageBox(this);
    ////    msgBox->setIcon(QMessageBox::Warning);
    ////    msgBox->setWindowTitle("导出");
    ////    msgBox->setText("导出表格中...");
    ////    msgBox->setStandardButtons(QMessageBox::NoButton);
    ////    msgBox->show();
    ////    QTimer::singleShot(1000, msgBox, &QMessageBox::accept);
    ////    QCoreApplication::processEvents();

    //    QVector<QVariantList> allData = DatabaseUtils::getAllData();

    //    if (allData.isEmpty()) {
    //        qDebug() << "No data retrieved from database";
    //        return;
    //    }

    //    QAxObject *excel = new QAxObject("Excel.Application", this);
    //    if (!excel->isNull()) {
    //        excel->setProperty("Visible", false);
    //    } else {
    //        qDebug() << "Failed to create Excel application";
    //        QMessageBox::warning(this, tr("Excel Error"), tr("Failed to create Excel application."));
    //        return;
    //    }

    //    QAxObject *workbooks = excel->querySubObject("Workbooks");
    //    QAxObject *workbook = workbooks->querySubObject("Add");
    //    QAxObject *worksheet = workbook->querySubObject("Worksheets(int)", 1);

    //    int columnCount = allData.first().size();

    //    for (int col = 0; col < columnCount; ++col) {
    //        QString columnName = QString("Column %1").arg(col + 1);
    //        QAxObject *cell = worksheet->querySubObject("Cells(int,int)", 1, col + 1);
    //        cell->setProperty("Value", columnName);
    //    }

    //    for (int row = 0; row < allData.size(); ++row) {
    //        const QVariantList &rowData = allData[row];
    //        for (int col = 0; col < rowData.size(); ++col) {
    //            QAxObject *cell = worksheet->querySubObject("Cells(int,int)", row + 2, col + 1);
    //            QVariant value = rowData[col];
    //            cell->setProperty("Value2", value);

    ////            qDebug() << "Writing to Excel: Row" << row + 2 << "Col" << col + 1 << value;
    //        }
    //    }

    //    workbook->dynamicCall("SaveAs(const QString&)", QDir::toNativeSeparators(fileName));
    //    workbook->dynamicCall("Close()");
    //    excel->dynamicCall("Quit()");

    //    delete excel;
    //    QMessageBox::information(this, tr("导出"), tr("导出表格成功"));
}

void MainWindow::on_user_data_button_clicked_func()
{
    QString userInput1 = ui->user_data_lineEdit_1->text();
    bool save_flag = DatabaseUtils::update_Info_t("chexing", userInput1);
    chexing = userInput1;

    if (save_flag == false)
    {
        QMessageBox::warning(this, "保存失败", "请重新设置");
    }
    else
    {
        QMessageBox::warning(this, "保存成功", "已修改");
    }
}

void MainWindow::on_name_button_clicked_func()
{
    QString userInput1 = ui->name_lineEdit->text();

    bool save_flag = DatabaseUtils::update_Info_t("name", userInput1);
    name = userInput1;

    if (save_flag == false)
    {
        QMessageBox::warning(this, "保存失败", "请重新设置");
    }
    else
    {
        QMessageBox::warning(this, "保存成功", "已修改");
    }
}

void MainWindow::on_res_max_button_clicked_func()
{
    QString userInput1 = ui->res_max_lineEdit_1->text();
    QString userInput2 = ui->res_max_lineEdit_2->text();

    double res = userInput1.toDouble();
    if (res >= 10)
    {
        QMessageBox::warning(this, "保存失败", "输入值不在范围");
        return;
    }
    double sd = userInput2.toDouble();
    double sd1 = sd;

    sd = res * (sd / 100);
    max_res = res + sd;
    if (max_res >= 10)
    {
        QMessageBox::warning(this, "保存失败", "最大值无效");
        return;
    }
    min_res = res - sd;
    if (min_res < 0)
    {
        QMessageBox::warning(this, "保存失败", "最小值无效");
        return;
    }
    //    qDebug()<<"res" << res;
    //    qDebug()<<"sd" << sd;
    //    qDebug()<<"max_res" << max_res;
    //    qDebug()<<"min_res" << min_res;

    detect = QString("%1Ω ±%2%").arg(res).arg(sd1); // 使用sd1(原始百分比值)而不是sd(计算后的值)

    bool save_flag = DatabaseUtils::update_Info_t("res_value", res);
    save_flag = DatabaseUtils::update_Info_t("res_sd", sd1);

    save_flag = DatabaseUtils::update_Info_t("max_res", max_res);
    save_flag = DatabaseUtils::update_Info_t("min_res", min_res);

    if (save_flag == false)
    {
        QMessageBox::warning(this, "保存失败", "请重新设置");
    }
    else
    {
        QMessageBox::warning(this, "保存成功", "已修改");
    }
}

void MainWindow::on_auto_value_button_clicked_func()
{
    QString userInput1 = ui->auto_value_lineEdit_1->text();
    bool save_flag;
    if (userInput1.toInt() < 1)
    {
        //        save_flag = DatabaseUtils::update_Info_t("auto_time",10);
        save_flag = false;
    }
    else
    {
        auto_time = userInput1.toInt();
        save_flag = DatabaseUtils::update_Info_t("auto_time", auto_time);
        ui->auto_value_lineEdit_1->setText(QString::number(auto_time));
    }

    if (save_flag == false)
    {
        QMessageBox::warning(this, "保存失败", "输入值不在范围");
    }
    else
    {
        QMessageBox::warning(this, "保存成功", "已修改");
    }
}

// void MainWindow::on_set_tx_button_clicked()
//{

//    QString userInput1 = ui->set_tx_lineEdit_1->text();
//    QString userInput2 = ui->set_tx_lineEdit_2->text();

//}

void delay(int milliseconds)
{
    QEventLoop loop;
    QTimer::singleShot(milliseconds, &loop, SLOT(quit()));
    loop.exec();
}

void MainWindow::on_xc_button_clicked_func()
{
    if (auto_mode)
    {
        ui->auto_label->setText("自动关闭");
        auto_mode = false;
        timer->stop();
    }
    QString userInput1 = ui->xc_lineEdit->text();
    bool ok;
    xc_sd = userInput1.toDouble(&ok);

    if (ok == false)
    {
        QString warningMessage = QString("字符转换问题:非数字").arg(xc_sd);
        QMessageBox::warning(this, "保存失败", warningMessage);
        return;
    }

    if (xc_sd < 3 && ok && xc_sd >= 0)
    {
        ok = DatabaseUtils::update_Info_t("xc_sd", xc_sd);
        if (ok == false)
        {
            QString warningMessage = QString("数据库问题:无法保存").arg(xc_sd);
            QMessageBox::warning(this, "保存失败", warningMessage);
            return;
        }
    }
    else
    {
        ok = false;
        QString warningMessage = QString("输入值 %1 不在范围").arg(xc_sd);
        QMessageBox::warning(this, "保存失败", warningMessage);
        return;
    }

    if (ok == true)
    {
        QString warningMessage = QString("已修改 %1 ").arg(xc_sd);
        QMessageBox::warning(this, "保存成功", warningMessage);
    }
}

// void MainWindow::on_bj_2_button_clicked()
//{
//     if(auto_mode){
//         ui->auto_label->setText("自动关闭");
//         auto_mode = false;
//         timer->stop();
//     }
//     QString userInput1 = ui->bj_2_lineEdit_0->text();
//     QString userInput2 = ui->bj_2_lineEdit_1->text();
//     QString userInput3 = ui->bj_2_lineEdit_2->text();

//    QString command1;
//     if (userInput1 == "0") {
//         command1 = "010610070000";
//     } else if (userInput1 == "1") {
//         command1 = "010610070001";
//     } else if (userInput1 == "2") {
//         command1 = "010610070002";
//     } else if (userInput1 == "3") {
//         command1 = "010610070003";
//     } else if (userInput1 == "4") {
//         command1 = "010610070004";
//     } else {
//         ui->bj_2_lineEdit_0->setText("输入无效: 请输入0到4之间的数字");
//         ui->bj_2_lineEdit_0->setStyleSheet("QLabel { color : red; }");
//         return;
//     }
//     bool rec_flag = serialPortManager->sendModbus_receive_2(command1, 8);
//    delay(10);

//     bool ok;
//     int value2 = userInput2.toInt(&ok);
//     if (!ok) {
//         ui->bj_2_lineEdit_1->setText("输入无效: 请输入有效的数字");
//         ui->bj_2_lineEdit_1->setStyleSheet("QLabel { color : red; }");
//         return;
//     }

//     QString hexValue2 = QString("%1").arg(value2, 4, 16, QLatin1Char('0')).toUpper();
//     QString command2 = "01061008" + hexValue2;
//     rec_flag = serialPortManager->sendModbus_receive_2(command2, 8);
//    delay(10);

//     int value3 = userInput3.toInt(&ok);
//     if (!ok) {
//         ui->bj_2_lineEdit_2->setText("输入无效: 请输入有效的数字");
//         ui->bj_2_lineEdit_2->setStyleSheet("QLabel { color : red; }");
//         return;
//     }
//     QString hexValue3 = QString("%1").arg(value3, 4, 16, QLatin1Char('0')).toUpper();
//     QString command3 = "01061009" + hexValue3;
//     rec_flag = serialPortManager->sendModbus_receive_2(command3, 8);
//     if(rec_flag == false){
//         QMessageBox::warning(this, "设置失败", "请重新设置");
//     } else {
//         QMessageBox::warning(this, "设置成功", "已修改");
//     }
// }

void MainWindow::get_device_bj_info()
{

    //    serialPortManager->sendModbus_receive_2("010310040002", 9);
    //    ui->bj_1_lineEdit_0->setText("");
    //    serialPortManager->sendModbus_receive_2("010310050002", 9);
    //    ui->bj_1_lineEdit_1->setText("");
    //    serialPortManager->sendModbus_receive_2("010310060002", 9);
    //    ui->bj_1_lineEdit_2->setText("");
    //    serialPortManager->sendModbus_receive_2("010310070002", 9);

    //    ui->bj_2_lineEdit_0->setText("");
    //    serialPortManager->sendModbus_receive_2("010310080002", 9);
    //    ui->bj_2_lineEdit_1->setText("");
    //    serialPortManager->sendModbus_receive_2("010310090002", 9);
    //    ui->bj_2_lineEdit_2->setText("");
}

void MainWindow::on_nextPageButton_clicked()
{

    totalRows = DatabaseUtils::getResTotalRows();

    uppage = false;

    if ((currentPage + 1) * rowsPerPage < totalRows)
    {
        currentPage++;
    }
    else
    {
        currentPage = 0; // 第一页
    }
    //    qDebug() << "totalRows:" << totalRows;
    //         qDebug() << "Next page:" << currentPage;
    updateTableWidget(DatabaseUtils::getData(rowsPerPage, currentPage * rowsPerPage));
}

void MainWindow::on_prevPageButton_clicked()
{

    totalRows = DatabaseUtils::getResTotalRows();

    uppage = false;

    if (currentPage > 0)
    {
        currentPage--;
    }
    else
    {
        currentPage = (totalRows + rowsPerPage - 1) / rowsPerPage - 1; // 最后一页
    }
    // qDebug() << "totalRows:" << totalRows;
    //       qDebug() << "Previous page:" << currentPage;
    updateTableWidget(DatabaseUtils::getData(rowsPerPage, currentPage * rowsPerPage));
}

void MainWindow::updateTableWidget(const QVector<QVariantList> &data)
{
    ui->tableWidget->setRowCount(rowsPerPage);

    for (int row = 0; row < data.size(); ++row)
    {
        const QVariantList &rowData = data[row];
        for (int col = 0; col < rowData.size(); ++col)
        {
            QTableWidgetItem *item = new QTableWidgetItem(rowData[col].toString());
            item->setFlags(Qt::NoItemFlags);
            item->setTextAlignment(Qt::AlignCenter); // 文字居中
            ui->tableWidget->setItem(row, col, item);
        }
    }

    for (int i = data.size(); i < rowsPerPage; ++i)
    {
        for (int col = 0; col < ui->tableWidget->columnCount(); ++col)
        {
            ui->tableWidget->setItem(i, col, new QTableWidgetItem(""));
        }
    }
    //    ui->user_data_lineEdit_2->setFocus();
    // ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
}

void MainWindow::updateCharts()
{

    if (uppage)
    {
        totalRows = DatabaseUtils::getResTotalRows();

        if (totalRows > old_totalRows)
        {
            int cnt = (totalRows + rowsPerPage - 1) / rowsPerPage;
            for (int i = currentPage; i < cnt - 1; i++)
            {
                on_nextPageButton_clicked();
            }
            updateTableWidget(DatabaseUtils::getData(rowsPerPage, currentPage * rowsPerPage));
        }
        old_totalRows = totalRows;
    }
    else
    {
        uppage_cnt++;
        if (uppage_cnt >= 3)
        {
            uppage = true;
        }
    }

    if (daily_date != nullptr)
    {
        QString currentDate = QDate::currentDate().toString("yyyy-MM-dd");
        //        qDebug() << "daily_date" <<daily_date;
        //        qDebug() << "currentDate" <<currentDate;
        if (currentDate != daily_date)
        {
            daily_qualified_l = daily_qualified_cnt / (daily_cnt * 1.0);
            DatabaseUtils::insertOrUpdateDailyData(daily_cnt, daily_cnt_manual, daily_qualified_cnt, daily_cnt_over, daily_cnt_down, daily_cnt_max, daily_cnt_min, daily_qualified_l);
            DatabaseUtils::updateLastDate();

            set20->replace(0, 0);
            set21->replace(1, 0);
            set22->replace(2, 0);
            axisX2->setRange(0, std::max({daily_qualified_cnt, daily_cnt_over + daily_cnt_down, daily_cnt}));

            daily_date = DatabaseUtils::get_today_daliy_t(daily_cnt, daily_cnt_manual,
                                                          daily_qualified_cnt, daily_cnt_over,
                                                          daily_cnt_down, daily_cnt_max,
                                                          daily_cnt_min);
            //            qDebug() << "daily_cnt" <<daily_cnt;
            return;
        }
    }

    double qualified_percentage = all_count != 0 ? (qualified_cnt / static_cast<double>(all_count)) * 100 : 0;
    double unqualified_percentage = all_count != 0 ? ((up_cnt + down_cnt) / static_cast<double>(all_count)) * 100 : 0;

    QList<QPieSlice *> slices = pieSeries->slices();

    slices[0]->setLabel(QString("%1").arg(all_count));
    //        slices[0]->setLabel(QString("%1 (%2)").arg("总检验次数").arg(all_count));
    slices[1]->setLabel(QString("%1% (%2)").arg(qualified_percentage, 0, 'f', 1).arg(qualified_cnt));
    slices[2]->setLabel(QString("%1% (%2)").arg(unqualified_percentage, 0, 'f', 1).arg((up_cnt + down_cnt)));

    set20->replace(0, daily_qualified_cnt);
    set21->replace(1, daily_cnt_over + daily_cnt_down);
    set22->replace(2, daily_cnt);

    bool allZero = (daily_qualified_cnt == 0) && (daily_cnt_over + daily_cnt_down == 0) && (daily_cnt == 0);

    if (allZero)
    {
        axisX2->setRange(0, 1);
        //        axisX2->setTickCount(3);
    }
    else
    {
        int maxValue = std::max({daily_qualified_cnt, daily_cnt_over + daily_cnt_down, daily_cnt});
        axisX2->setRange(0, maxValue);
        axisX2->applyNiceNumbers();
    }
    //    axisX2->setRange(0, std::max({daily_qualified_cnt, daily_cnt_over+daily_cnt_down, daily_cnt}));
}

void MainWindow::disp_IIOT()
{
    QList<QVariantList> dataList = DatabaseUtils::getLastFiveDailyDataSkippingToday();
    const int rowCount = 5;
    int dailyInspectionCounts[rowCount] = {0};
    int manualInspectionCounts[rowCount] = {0};
    int qualifieds[rowCount] = {0};
    int overLimits[rowCount] = {0};
    int underLimits[rowCount] = {0};
    double maxValues[rowCount] = {0.0};
    double minValues[rowCount] = {0.0};
    double qualificationRates[rowCount] = {0.0};
    QString dates[rowCount];

    int rowIndex = 0;
    for (const QVariantList &row : dataList)
    {
        if (rowIndex >= rowCount)
            break;
        dailyInspectionCounts[rowIndex] = row[1].toInt();
        manualInspectionCounts[rowIndex] = row[2].toInt();
        qualifieds[rowIndex] = row[3].toInt();
        overLimits[rowIndex] = row[4].toInt();
        underLimits[rowIndex] = row[5].toInt();
        maxValues[rowIndex] = row[6].toDouble();
        minValues[rowIndex] = row[7].toDouble();
        qualificationRates[rowIndex] = row[8].toDouble();
        dates[rowIndex] = row[9].toString();
        rowIndex++;
    }
    // 日检验次数 手动检测次数 合格 过大 过小 最大值 最小值 合格率 日期

    //    for (int i = 0; i < rowCount; ++i) {
    //        qDebug() << "Daily Inspection Count:" << dailyInspectionCounts[i]
    //                 << "Manual Inspection Count:" << manualInspectionCounts[i]
    //                 << "Qualified:" << qualifieds[i]
    //                 << "Over Limit:" << overLimits[i]
    //                 << "Under Limit:" << underLimits[i]
    //                 << "Max Value:" << maxValues[i]
    //                 << "Min Value:" << minValues[i]
    //                 << "Qualification Rate:" << qualificationRates[i]
    //                 << "Date:" << dates[i];
    //    }

    QColor backgroundColor("#1A1445");
    QColor big_textColor(Qt::white);
    QColor textColor("#CCCCCC");
    QColor lineColor("#7D7D7D");
    QColor barColor("#02E5FF");

    QFont boldFont;
    boldFont.setBold(true);

    // 折线图
    QLineSeries *lineSeries = new QLineSeries();
    lineSeries->append(1, qualificationRates[4]);
    lineSeries->append(2, qualificationRates[3]);
    lineSeries->append(3, qualificationRates[2]);
    lineSeries->append(4, qualificationRates[1]);
    lineSeries->append(5, qualificationRates[0]);
    QChart *lineChart = new QChart();
    lineChart->addSeries(lineSeries);
    lineChart->setTitle("近五天合格率");
    lineChart->setTitleFont(boldFont);
    lineChart->setBackgroundBrush(QBrush(backgroundColor));
    lineChart->setTitleBrush(QBrush(big_textColor));
    QChartView *lineChartView = new QChartView(lineChart);
    lineChartView->setRenderHint(QPainter::Antialiasing);

    QValueAxis *axisX = new QValueAxis();
    QValueAxis *axisY = new QValueAxis();
    axisX->setTitleText("天");
    axisY->setTitleText("合格率");
    axisX->setLabelsBrush(QBrush(lineColor));
    axisY->setLabelsBrush(QBrush(lineColor));
    axisX->setTitleBrush(QBrush(barColor));
    axisY->setTitleBrush(QBrush(barColor));
    axisX->setLinePen(QPen(lineColor));
    axisY->setLinePen(QPen(lineColor));
    axisY->setRange(0, 1.0);
    axisY->setTickCount(5);
    lineChart->addAxis(axisX, Qt::AlignBottom);
    lineChart->addAxis(axisY, Qt::AlignLeft);
    lineSeries->attachAxis(axisX);
    lineSeries->attachAxis(axisY);

    // 柱状图
    QBarSet *set2 = new QBarSet("超出区间");
    QBarSet *set4 = new QBarSet("小于区间");
    *set2 << maxValues[4] << maxValues[3] << maxValues[2] << maxValues[1] << maxValues[0];
    *set4 << minValues[4] << minValues[3] << minValues[2] << minValues[1] << minValues[0];
    set2->setColor(QColor("#FF5733"));
    set4->setColor(QColor("#FFBD33"));

    bool allZero = true;
    for (int i = 0; i < 5; ++i)
    {
        if (maxValues[i] != 0 || minValues[i] != 0)
        {
            allZero = false;
            break;
        }
    }
    QBarSeries *barSeries = new QBarSeries();
    barSeries->append(set2);
    barSeries->append(set4);
    QChart *barChart = new QChart();
    barChart->addSeries(barSeries);
    barChart->setTitle("近五天最值");
    barChart->setTitleFont(boldFont);
    barChart->setBackgroundBrush(QBrush(backgroundColor));
    barChart->setTitleBrush(QBrush(big_textColor));
    QChartView *barChartView1 = new QChartView(barChart);
    barChartView1->setRenderHint(QPainter::Antialiasing);

    QLegend *legend = barChart->legend();
    for (int i = 0; i < legend->markers().size(); ++i)
    {
        QLegendMarker *marker = legend->markers().at(i);
        marker->setLabelBrush(QBrush(textColor));
    }

    QBarCategoryAxis *axisX1 = new QBarCategoryAxis();
    axisX1->append(QStringList() << "1" << "2" << "3" << "4" << "5");
    axisX1->setTitleText("条数");
    axisX1->setLabelsBrush(QBrush(lineColor));
    axisX1->setTitleBrush(QBrush(barColor));
    axisX1->setLinePen(QPen(lineColor));
    QValueAxis *axisY11 = new QValueAxis();
    axisY11->setTitleText("最值");
    axisY11->setLabelsBrush(QBrush(lineColor));
    axisY11->setTitleBrush(QBrush(barColor));
    axisY11->setLinePen(QPen(lineColor));
    if (allZero)
    {
        axisY11->setRange(0, 5);
    }
    else
    {
        double maxValue = *std::max_element(maxValues, maxValues + 5);
        double minValue = *std::min_element(minValues, minValues + 5);
        axisY11->setRange(minValue, maxValue);
    }
    barChart->addAxis(axisX1, Qt::AlignBottom);
    barChart->addAxis(axisY11, Qt::AlignLeft);
    barSeries->attachAxis(axisX1);
    barSeries->attachAxis(axisY11);

    // 柱状图
    QBarSet *set10 = new QBarSet("合格");
    QBarSet *set11 = new QBarSet("大于");
    QBarSet *set12 = new QBarSet("小于");
    *set10 << qualifieds[4] << qualifieds[3] << qualifieds[2] << qualifieds[1] << qualifieds[0];
    *set11 << overLimits[4] << overLimits[3] << overLimits[2] << overLimits[1] << overLimits[0];
    *set12 << underLimits[4] << underLimits[3] << underLimits[2] << underLimits[1] << underLimits[0];

    allZero = true;
    for (int i = 0; i < 5; ++i)
    {
        if (qualifieds[i] != 0 || overLimits[i] != 0 || underLimits[i] != 0)
        {
            allZero = false;
            break;
        }
    }
    set10->setColor(QColor("#33FF57"));
    set11->setColor(QColor("#FF5733"));
    set12->setColor(QColor("#FFBD33"));

    QBarSeries *barSeries2 = new QBarSeries();
    barSeries2->append(set11);
    barSeries2->append(set10);
    barSeries2->append(set12);
    QChart *barChart2 = new QChart();
    barChart2->addSeries(barSeries2);
    barChart2->setTitle("近五天检验值");
    barChart2->setTitleFont(boldFont);
    barChart2->setBackgroundBrush(QBrush(backgroundColor));
    barChart2->setTitleBrush(QBrush(big_textColor));
    QChartView *barChartView2 = new QChartView(barChart2);
    barChartView2->setRenderHint(QPainter::Antialiasing);

    legend = barChart2->legend();
    for (int i = 0; i < legend->markers().size(); ++i)
    {
        QLegendMarker *marker = legend->markers().at(i);
        marker->setLabelBrush(QBrush(textColor));
    }

    axisX1 = new QBarCategoryAxis();
    axisX1->append(QStringList() << "1" << "2" << "3" << "4" << "5");
    axisX1->setTitleText("天");
    axisX1->setLabelsBrush(QBrush(lineColor));
    axisX1->setTitleBrush(QBrush(barColor));
    axisX1->setLinePen(QPen(lineColor));
    axisY = new QValueAxis();
    axisY->setTitleText("检验值");
    axisY->setLabelsBrush(QBrush(lineColor));
    axisY->setTitleBrush(QBrush(barColor));
    axisY->setLinePen(QPen(lineColor));
    if (allZero)
    {
        axisY->setRange(0, 5);
    }
    barChart2->addAxis(axisX1, Qt::AlignBottom);
    barChart2->addAxis(axisY, Qt::AlignLeft);
    barSeries2->attachAxis(axisX);
    barSeries2->attachAxis(axisY);

    // 饼状图
    pieSeries = new QPieSeries();
    pieSeries->append("总检验次数", 3);
    pieSeries->append("良品", 2);
    pieSeries->append("不合格", 1);

    QList<QPieSlice *> slices = pieSeries->slices();

    slices[0]->setColor(QColor("#02C1D7"));
    slices[0]->setBorderColor(QColor("#1A1445"));
    slices[0]->setBorderWidth(2);
    slices[0]->setLabel(QString("%1 (%2)").arg(slices[0]->label()).arg(all_count));
    slices[0]->setLabelVisible(true);
    slices[0]->setLabelBrush(QBrush(QColor(barColor)));

    slices[1]->setColor(QColor("#90EE90"));
    slices[1]->setBorderColor(QColor("#1A1445"));
    slices[1]->setBorderWidth(2);
    double qualified_percentage = all_count != 0 ? (qualified_cnt / static_cast<double>(all_count)) * 100 : 0;
    slices[1]->setLabel(QString("%1% (%2)").arg(qualified_percentage, 0, 'f', 1).arg(qualified_cnt));
    slices[1]->setLabelVisible(true);
    slices[1]->setLabelBrush(QBrush(QColor(barColor)));

    slices[2]->setColor(QColor("#FF6347"));
    slices[2]->setBorderColor(QColor("#1A1445"));
    slices[2]->setBorderWidth(2);
    double unqualified_percentage = all_count != 0 ? ((up_cnt + down_cnt) / static_cast<double>(all_count)) * 100 : 0;
    slices[2]->setLabel(QString("%1% (%2)").arg(unqualified_percentage, 0, 'f', 1).arg((up_cnt + down_cnt)));
    slices[2]->setLabelVisible(true);
    slices[2]->setLabelBrush(QBrush(QColor(barColor)));

    QChart *pieChart = new QChart();
    pieChart->addSeries(pieSeries);
    pieChart->setTitle("检验总览");
    pieChart->setTitleFont(boldFont);
    pieChart->setBackgroundBrush(QBrush(backgroundColor));
    pieChart->setTitleBrush(QBrush(big_textColor));
    QChartView *pieChartView = new QChartView(pieChart);
    pieChartView->setRenderHint(QPainter::Antialiasing);

    legend = pieChart->legend();
    for (int i = 0; i < legend->markers().size(); ++i)
    {
        QLegendMarker *marker = legend->markers().at(i);
        if (i == 0)
        {
            marker->setLabel("总检验次数");
        }
        else if (i == 1)
        {
            marker->setLabel("良品");
        }
        else if (i == 2)
        {
            marker->setLabel("不合格");
        }
        marker->setLabelBrush(QBrush(textColor));
    }

    // 条形图
    set20 = new QBarSet("良品");
    set21 = new QBarSet("不合格");
    set22 = new QBarSet("日检验次");

    *set20 << 0 << 0 << 0;
    *set21 << 0 << 0 << 0;
    *set22 << 0 << 0 << 0;

    set20->setColor(QColor("#33FF57"));
    set21->setColor(QColor("#FF5733"));
    set22->setColor(QColor(barColor));

    QHorizontalBarSeries *hBarSeries = new QHorizontalBarSeries();
    hBarSeries->append(set20);
    hBarSeries->append(set21);
    hBarSeries->append(set22);

    hBarSeries->setLabelsVisible(true);
    hBarSeries->setLabelsFormat("@value");
    QFont labelFont;
    labelFont.setPointSize(12);
    labelFont.setBold(true);
    set20->setLabelFont(labelFont);
    set21->setLabelFont(labelFont);
    set22->setLabelFont(labelFont);
    QBrush labelBrush(QColor("#FFFFFF"));
    set20->setLabelBrush(labelBrush);
    set21->setLabelBrush(labelBrush);
    set22->setLabelBrush(labelBrush);

    QChart *hBarChart = new QChart();
    hBarChart->addSeries(hBarSeries);
    hBarChart->setTitle("今日检验情况");
    hBarChart->setTitleFont(boldFont);
    hBarChart->setBackgroundBrush(QBrush(backgroundColor));
    hBarChart->setTitleBrush(QBrush(big_textColor));

    QChartView *hBarChartView = new QChartView(hBarChart);
    hBarChartView->setRenderHint(QPainter::Antialiasing);

    legend = hBarChart->legend();
    for (int i = 0; i < legend->markers().size(); ++i)
    {
        QLegendMarker *marker = legend->markers().at(i);
        marker->setLabelBrush(QBrush(textColor));
    }

    axisX2 = new QValueAxis();
    axisX2->setTitleText("数量");
    axisX2->setLabelsBrush(QBrush(lineColor));
    axisX2->setTitleBrush(QBrush(barColor));
    axisX2->setLinePen(QPen(lineColor));
    allZero = true;
    for (int i = 0; i < 3; ++i)
    {
        if ((*set20)[i] != 0 || (*set21)[i] != 0 || (*set22)[i] != 0)
        {
            allZero = false;
            break;
        }
    }
    if (allZero)
    {
        axisX2->setRange(0, 3);
        axisX2->setTickCount(3);
    }
    hBarChart->addAxis(axisX2, Qt::AlignBottom);
    hBarSeries->attachAxis(axisX2);
    QCategoryAxis *axisY1 = new QCategoryAxis();
    axisY1->append(" ", 1);
    axisY1->append(" ", 2);
    axisY1->setLabelsBrush(QBrush(lineColor));
    axisY1->setLinePen(QPen(lineColor));
    // axisY1->setGridLineVisible(false);
    hBarChart->addAxis(axisY1, Qt::AlignLeft);
    hBarSeries->attachAxis(axisY1);

    // 曲线图
    QSplineSeries *splineSeries = new QSplineSeries();
    splineSeries->append(1, manualInspectionCounts[4]);
    splineSeries->append(2, manualInspectionCounts[3]);
    splineSeries->append(3, manualInspectionCounts[2]);
    splineSeries->append(4, manualInspectionCounts[1]);
    splineSeries->append(5, manualInspectionCounts[0]);

    QChart *splineChart = new QChart();
    splineChart->addSeries(splineSeries);
    splineChart->setTitle("近五天手动检测次数");
    splineChart->setTitleFont(boldFont);
    splineChart->setBackgroundBrush(QBrush(backgroundColor));
    splineChart->setTitleBrush(QBrush(big_textColor));
    QChartView *splineChartView = new QChartView(splineChart);
    splineChartView->setRenderHint(QPainter::Antialiasing);

    axisX = new QValueAxis();
    axisY = new QValueAxis();
    axisX->setTitleText("天");
    axisY->setTitleText("次数");
    axisX->setLabelsBrush(QBrush(lineColor));
    axisY->setLabelsBrush(QBrush(lineColor));
    axisX->setTitleBrush(QBrush(barColor));
    axisY->setTitleBrush(QBrush(barColor));
    axisX->setLinePen(QPen(lineColor));
    axisY->setLinePen(QPen(lineColor));
    allZero = true;
    for (int i = 0; i < 5; ++i)
    {
        if (manualInspectionCounts[i] != 0)
        {
            allZero = false;
            break;
        }
    }

    if (allZero)
    {
        axisY->setRange(0, 5);
    }
    splineChart->addAxis(axisX, Qt::AlignBottom);
    splineChart->addAxis(axisY, Qt::AlignLeft);
    splineSeries->attachAxis(axisX);
    splineSeries->attachAxis(axisY);

    QHBoxLayout *topLayout = new QHBoxLayout();
    topLayout->addWidget(barChartView1);
    topLayout->addWidget(pieChartView);
    topLayout->addWidget(barChartView2);
    QHBoxLayout *bottomLayout = new QHBoxLayout();
    bottomLayout->addWidget(lineChartView);
    bottomLayout->addWidget(hBarChartView);
    bottomLayout->addWidget(splineChartView);
    QVBoxLayout *mainLayout = new QVBoxLayout(ui->tab_1);
    mainLayout->addLayout(topLayout);
    mainLayout->addLayout(bottomLayout);
}

void MainWindow::disp_canshu()
{
    QPalette nextButtonPalette = ui->nextPageButton->palette();
    nextButtonPalette.setColor(QPalette::ButtonText, Qt::white);
    ui->nextPageButton->setPalette(nextButtonPalette);
    ui->prevPageButton->setPalette(nextButtonPalette);

    // 设置表格列宽自适应，最后一列（日期）设置为适应内容
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 最后一列设置为适应内容，确保日期显示完整
    int lastCol = ui->tableWidget->columnCount() - 1;
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(lastCol, QHeaderView::ResizeToContents);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //    for (int row = 0; row < 16; ++row) {
    //        for (int col = 0; col < 4; ++col) {
    //            QTableWidgetItem *item = new QTableWidgetItem(QString("Row %1, Col %2").arg(row + 1).arg(col + 1));
    //            ui->tableWidget->setItem(row, col, item);
    //        }
    //    }

    //    DatabaseUtils::insertTestData(100);

    totalRows = DatabaseUtils::getResTotalRows();
    //    qDebug() << "Total rows:" << totalRows;
    updateTableWidget(DatabaseUtils::getData(rowsPerPage, currentPage * rowsPerPage));

    QMap<QString, QVariant> infoData = DatabaseUtils::read_all_Info_t();
    //    for (auto it = infoData.begin(); it != infoData.end(); ++it) {
    //        qDebug() << it.key() << ":" << it.value();
    //    }
    all_count = infoData.value("all_count").toInt();
    auto_cnt = infoData.value("auto_cnt").toInt();
    manual_cnt = infoData.value("manual_cnt").toInt();
    qualified_cnt = infoData.value("qualified_cnt").toInt();
    up_cnt = infoData.value("up_cnt").toInt();
    down_cnt = infoData.value("down_cnt").toInt();
    res_value = infoData.value("res_value").toDouble();
    res_sd = infoData.value("res_sd").toDouble();
    max_res = infoData.value("max_res").toDouble();
    min_res = infoData.value("min_res").toDouble();
    xc_sd = infoData.value("xc_sd").toDouble();
    auto_time = infoData.value("auto_time").toInt();
    name = infoData.value("name").toString();
    chexing = infoData.value("chexing").toString();
    pwd = infoData.value("pwd").toString();

    //    qDebug() << "all_count" << all_count;

    detect = QString("%1Ω ±%2%").arg(res_value).arg(res_sd);
    //    qDebug() << "Detect string:" << detect;

    ui->user_data_lineEdit_1->setText(chexing);
    ui->name_lineEdit->setText(name);
    ui->res_max_lineEdit_1->setText(QString::number(res_value));
    ui->res_max_lineEdit_2->setText(QString::number(res_sd));
    ui->auto_value_lineEdit_1->setText(QString::number(auto_time));
    ui->xc_lineEdit->setText(QString::number(xc_sd));
    //    ui->set_tx_lineEdit_1->text();
    //    ui->bj_1_lineEdit_0->text();
}

void MainWindow::on_pushButton_2_clicked()
{
    QString filePath = QFileDialog::getSaveFileName(this, tr("Save PDF"), "", tr("PDF Files (*.pdf)"));

    if (!filePath.isEmpty())
    {
        QFile resourceFile(":/res/user.pdf");
        if (resourceFile.open(QIODevice::ReadOnly))
        {

            QFile outputFile(filePath);
            if (outputFile.open(QIODevice::WriteOnly))
            {
                outputFile.write(resourceFile.readAll());
                outputFile.close();

                QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
            }
            else
            {
                QMessageBox::warning(this, tr("Error"), tr("Cannot open output file for writing."));
            }
            resourceFile.close();
        }
        else
        {
            QMessageBox::warning(this, tr("Error"), tr("Cannot open resource file."));
        }
    }
}

void MainWindow::playQualified()
{
    player->setMedia(QUrl("qrc:/res/ok.wav"));
    player->setVolume(100);
    player->play();
}

void MainWindow::playUnqualified()
{
    player->setMedia(QUrl("qrc:/res/no.wav"));
    player->setVolume(100);
    player->play();
}

void MainWindow::playConnState_ok()
{
    player->setMedia(QUrl("qrc:/res/auto_conn_ok.wav"));
    player->setVolume(100);
    player->play();
}
void MainWindow::playConnState_no()
{
    player->setMedia(QUrl("qrc:/res/auto_conn_no.wav"));
    player->setVolume(100);
    player->play();
}

void MainWindow::play_get_err()
{
    player->setMedia(QUrl("qrc:/res/get_err.wav"));
    player->setVolume(100);
    player->play();
}

void MainWindow::play_no_conn_res()
{
    player->setMedia(QUrl("qrc:/res/no_conn_res.wav"));
    player->setVolume(100);
    player->play();
}

void MainWindow::dispscan(const QString barcode)
{
    // 有扫码数据时关闭提示标签
    if (scanTipLabel != nullptr)
    {
        scanTipLabel->close();
        scanTipLabel->deleteLater();
        scanTipLabel = nullptr;
    }

    // 扫码逻辑：
    // 1. 如果两个框都有值，说明开始新一轮，先清空再从护面开始
    // 2. 如果护面框为空，输入到护面框
    // 3. 如果护面框有值但加热框为空，输入到加热框

    bool sm_has_value = !ui->user_data_lineEdit_2->text().isEmpty();
    bool hot_has_value = !ui->user_data_lineEdit_3->text().isEmpty();

    if (sm_has_value && hot_has_value)
    {
        // 两个框都有值，开始新一轮，先清空
        ui->user_data_lineEdit_2->clear();
        ui->user_data_lineEdit_3->clear();
        sm_num = "";
        hot_num = "";
        // 然后输入到护面框
        sm_num = barcode;
        ui->user_data_lineEdit_2->setText(barcode);
        ui->tishi_label->setText("护面扫码成功");
    }
    else if (!sm_has_value)
    {
        // 护面框为空，输入到护面框
        sm_num = barcode;
        ui->user_data_lineEdit_2->setText(barcode);
        ui->tishi_label->setText("护面扫码成功");
    }
    else
    {
        // 护面框有值，加热框为空，输入到加热框
        hot_num = barcode;
        ui->user_data_lineEdit_3->setText(barcode);
        ui->tishi_label->setText("加热垫扫码成功");
    }

    QMediaPlayer *player1 = new QMediaPlayer(this);

    // 设置媒体文件
    player1->setMedia(QUrl("qrc:/res/sm.wav"));
    player1->setVolume(100);

    // 连接信号，当播放结束时释放 player1
    connect(player1, &QMediaPlayer::stateChanged, this, [player1](QMediaPlayer::State state)
            {
        if (state == QMediaPlayer::StoppedState) {
            player1->deleteLater(); // 延迟释放
        } });

    // 播放音频
    player1->play();
}

void MainWindow::on_delete_1_button_clicked_func()
{

    if (auto_mode)
    {
        ui->auto_label->setText("自动关闭");
        auto_mode = false;
        timer->stop();
    }
    QString userInput1 = ui->delete_res_lineEdit_0->text();

    bool ok;

    int value1 = userInput1.toInt(&ok);
    if (!ok)
    {
        ui->delete_res_lineEdit_0->setText("输入无效: 请输入有效的数字");
        ui->delete_res_lineEdit_0->setStyleSheet("QLabel { color : red; }");
        return;
    }

    int rec_flag = DatabaseUtils::delete_ResData(value1);

    if (rec_flag == 0)
    {
        ui->delete_res_lineEdit_0->setText("");
        QMessageBox::warning(this, "设置失败", "ID不存在");
    }
    else if (rec_flag == 1)
    {
        on_nextPageButton_clicked();
        on_prevPageButton_clicked();
        ui->delete_res_lineEdit_0->setText("");
        QMessageBox::warning(this, "设置成功", "已修改");
    }
    else
    {
        ui->delete_res_lineEdit_0->setText("");
        QMessageBox::warning(this, "设置失败", "请重新设置");
    }

    //    if(auto_mode){
    //        ui->auto_label->setText("自动关闭");
    //        auto_mode = false;
    //        timer->stop();
    //    }
    //    QString userInput1 = ui->delete_res_lineEdit_2->text();
    //    QString userInput2 = ui->delete_res_lineEdit_2->text();
    //    QString userInput3 = ui->delete_res_lineEdit_2->text();

    //    bool ok;

    //    int value2 = userInput2.toInt(&ok);
    //    if (!ok) {
    //        ui->delete_res_lineEdit_2->setText("输入无效: 请输入有效的数字");
    //        ui->delete_res_lineEdit_2->setStyleSheet("QLabel { color : red; }");
    //        return;
    //    }

    //    int value3 = userInput3.toInt(&ok);
    //    if (!ok) {
    //        ui->delete_res_lineEdit_2->setText("输入无效: 请输入有效的数字");
    //        ui->delete_res_lineEdit_2->setStyleSheet("QLabel { color : red; }");
    //        return;
    //    }

    //    QString hexValue2 = QString("%1").arg(value2, 4, 16, QLatin1Char('0')).toUpper();
    //    QString hexValue3 = QString("%1").arg(value3, 4, 16, QLatin1Char('0')).toUpper();

    //    QString command1;
    //     if (userInput1 == "0") {
    //         command1 = "011003ED0003060000";
    //     } else if (userInput1 == "1") {
    //         command1 = "011003ED0003060001";
    //     } else if (userInput1 == "2") {
    //         command1 = "011003ED0003060002";
    //     } else if (userInput1 == "3") {
    //         command1 = "011003ED0003060003";
    //     } else {
    //         ui->delete_res_lineEdit_2->setText("输入无效: 请输入0到4之间的数字");
    //         ui->delete_res_lineEdit_2->setStyleSheet("QLabel { color : red; }");
    //         return;
    //     }

    //     command1 += hexValue2;
    //     command1 += hexValue3;

    //     bool rec_flag = serialPortManager->sendModbus_receive_2(command1, 6);
    //     delay(10);

    //     if(rec_flag == false){
    //         QMessageBox::warning(this, "设置失败", "请重新设置");
    //     } else {
    //         QMessageBox::warning(this, "设置成功", "已修改");
}

void MainWindow::on_delete_2_button_clicked_func()
{
    if (auto_mode)
    {
        ui->auto_label->setText("自动关闭");
        auto_mode = false;
        timer->stop();
    }

    QString userInput2 = ui->delete_res_lineEdit_1->text();
    QString userInput3 = ui->delete_res_lineEdit_2->text();

    bool ok;

    int value2 = userInput2.toInt(&ok);
    if (!ok)
    {
        ui->delete_res_lineEdit_1->setText("输入无效: 请输入有效的数字");
        ui->delete_res_lineEdit_1->setStyleSheet("QLabel { color : red; }");
        return;
    }

    int value3 = userInput3.toInt(&ok);
    if (!ok)
    {
        ui->delete_res_lineEdit_2->setText("输入无效: 请输入有效的数字");
        ui->delete_res_lineEdit_2->setStyleSheet("QLabel { color : red; }");
        return;
    }

    int rec_flag = -1;
    int flag = 1;
    int temp = -1;
    for (int i = value2; i <= value3; i++)
    {
        temp = DatabaseUtils::delete_ResData(i);
        if (temp == 1)
        {
            rec_flag = 1;
            flag = 0;
        }
        else if ((temp == 0) && flag)
        {
            rec_flag = 0;
        }
    }

    if (rec_flag == 0)
    {
        ui->delete_res_lineEdit_1->setText("");
        ui->delete_res_lineEdit_2->setText("");
        QMessageBox::warning(this, "设置失败", "ID都不存在");
    }
    else if (rec_flag == 1)
    {
        on_nextPageButton_clicked();
        on_prevPageButton_clicked();
        ui->delete_res_lineEdit_1->setText("");
        ui->delete_res_lineEdit_2->setText("");
        QMessageBox::warning(this, "设置成功", "已修改");
    }
    else
    {
        ui->delete_res_lineEdit_1->setText("");
        ui->delete_res_lineEdit_2->setText("");
        QMessageBox::warning(this, "设置失败", "请重新设置");
    }
}

void MainWindow::on_pwd_button_clicked_func()
{
    QString userInput = ui->pwd_lineEdit->text();

    if (userInput.length() > 8)
    {
        ui->pwd_lineEdit->setText("");
        QMessageBox::warning(this, "设置失败", "密码长度不能超过8个字符，请重新输入");
        return;
    }

    bool save_flag = DatabaseUtils::update_Info_t("pwd", userInput);
    pwd = userInput;

    if (save_flag == false)
    {
        ui->pwd_lineEdit->setText("");
        QMessageBox::warning(this, "设置失败", "请重新设置");
    }
    else
    {
        ui->pwd_lineEdit->setText("");
        QMessageBox::warning(this, "设置成功", "请记住密码");
    }
}

void MainWindow::onShowPasswordDialog()
{
    PasswordDialog *passwordDialog = new PasswordDialog(this);
    //    passwordDialog->setWindowModality(Qt::ApplicationModal); // 设置为模态对话框
    passwordDialog->show();

    //    connect(passwordDialog, &PasswordDialog::accepted, this, &MainWindow::onPasswordDialogAccepted);

    // 获取发送信号的对象
    QObject *senderObj = sender();
    senderButton = qobject_cast<QPushButton *>(senderObj);

    // 连接对话框的 accepted 信号到 的槽函数
    connect(passwordDialog, &PasswordDialog::accepted, this, &MainWindow::onPasswordAccepted);
}

void MainWindow::onPasswordAccepted()
{
    PasswordDialog *passwordDialog = qobject_cast<PasswordDialog *>(sender());
    if (passwordDialog)
    {
        QString password = passwordDialog->getPassword();
        qDebug() << "password:" << password;

        if (password == pwd)
        {

            if (senderButton)
            {
                if (senderButton == ui->xc_button)
                {
                    on_xc_button_clicked_func();
                }
                else if (senderButton == ui->pwd_button)
                {
                    on_pwd_button_clicked_func();
                }
                else if (senderButton == ui->name_button)
                {
                    on_name_button_clicked_func();
                }
                else if (senderButton == ui->auto_value_button)
                {
                    on_auto_value_button_clicked_func();
                }
                else if (senderButton == ui->res_max_button)
                {
                    on_res_max_button_clicked_func();
                }
                else if (senderButton == ui->delete_1_button)
                {
                    on_delete_1_button_clicked_func();
                }
                else if (senderButton == ui->delete_2_button)
                {
                    on_delete_2_button_clicked_func();
                }
            }
            senderButton = NULL;
        }
        else
        {
            senderButton = NULL;
            QMessageBox::warning(this, "密码错误", "请检查密码");
        }
    }
}
