#include "Demo001_3.h"
#include "ui_Demo001_3.h"
#include <QSettings>
#include <QCloseEvent>
#include "Group.h"
#include <QVBoxLayout>
#include <QDebug>
#include <QTimer>

Demo001_3::Demo001_3(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Demo001_3), scaleFactor(1.0)
{
    ui->setupUi(this);

    // initFrom();
    // connect(this, &Demo001_3::closeEvent, this, &Demo001_3::saveSliderStates);


}

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

void Demo001_3::initFrom() {
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Demo001_3::checkSettings);
    timer->start(100);

    ui->label_Percentage->setAlignment(Qt::AlignCenter);

    // 设置右下部分
    loadSliderStates();

    initSliders();
    initLineEdits();

    connectSliderAndLineEdit(ui->verticalSlider, ui->lineEdit);
    connectSliderAndLineEdit(ui->verticalSlider_2, ui->lineEdit_2);
    connectSliderAndLineEdit(ui->verticalSlider_3, ui->lineEdit_3);
    connectSliderAndLineEdit(ui->verticalSlider_4, ui->lineEdit_4);
    connectSliderAndLineEdit(ui->verticalSlider_5, ui->lineEdit_5);
    connectSliderAndLineEdit(ui->verticalSlider_6, ui->lineEdit_6);

    // 设置右上部分
    QWidget *viewport = ui->scrollArea->viewport();
    QWidget *container = new QWidget(viewport);
    QVBoxLayout *layout = new QVBoxLayout(container);

    layout->setSpacing(16); // 设置Group之间的间隔距离
    layout->setMargin(0);

    QStringList dispmodel;
    dispmodel<<("P die align")<<("D device align");
    Group *widget = new Group(1, ":/images/test_image/image_1.png", ":/images/test_image/image_2.png", dispmodel, this);
    layout->addWidget(widget);

    QStringList dispmodel1;
    dispmodel1<<("D device align")<<("P die align");
    Group *widget_1 = new Group(2, ":/images/test_image/image_3.png", ":/images/test_image/image_4.png", dispmodel1, this);
    layout->addWidget(widget_1);

    QStringList dispmodel2;
    dispmodel2<<("B device align")<<("P die align");
    Group *widget_2 = new Group(3, ":/images/test_image/image_5.png", ":/images/test_image/image_6.png", dispmodel2, this);
    layout->addWidget(widget_2);

    QStringList dispmodel3;
    dispmodel3<<("U die align")<<("D device align");
    Group *widget_3 = new Group(4, ":/images/test_image/image_7.png", ":/images/test_image/image_8.png", dispmodel3, this);
    layout->addWidget(widget_3);

    Group *widget_4 = new Group(5, ":/images/test_image/image.png", ":/images/test_image/image_2.png", dispmodel, this);
    layout->addWidget(widget_4);

    widget->setMinimumHeight(162);
    widget_1->setMinimumHeight(162);
    widget_2->setMinimumHeight(162);
    widget_3->setMinimumHeight(162);
    widget_4->setMinimumHeight(162);

    widget->setMaximumWidth(244);
    widget_1->setMaximumWidth(244);
    widget_2->setMaximumWidth(244);
    widget_3->setMaximumWidth(244);
    widget_4->setMaximumWidth(244);

    container->setLayout(layout);
    ui->scrollArea->setWidget(container);
    ui->scrollArea->resize(261, 700);

    ui->Operatewidget->setMouseTracking(true);
}

void Demo001_3::closeEvent(QCloseEvent *event) {
    // 保存滑块状态
    saveSliderStates();

    // 确保调用基类的 closeEvent 处理其他关闭逻辑
    QMainWindow::closeEvent(event);
}

void Demo001_3::initSliders() {
    QList<QSlider*> sliders = {
        ui->verticalSlider, ui->verticalSlider_2, ui->verticalSlider_3,
        ui->verticalSlider_4, ui->verticalSlider_5, ui->verticalSlider_6
    };
    QList<int> initialValues = {11, 22, 9, 11, 0, 0};

    for (int i = 0; i < sliders.size(); ++i) {
        sliders[i]->setMinimum(0);
        sliders[i]->setMaximum(100);
        sliders[i]->setValue(initialValues[i]);
    }
}

void Demo001_3::initLineEdits() {
    QList<QLineEdit*> lineEdits = {
        ui->lineEdit, ui->lineEdit_2, ui->lineEdit_3,
        ui->lineEdit_4, ui->lineEdit_5, ui->lineEdit_6
    };

    for (QLineEdit* lineEdit : lineEdits) {
        lineEdit->setAlignment(Qt::AlignCenter);
    }
}

void Demo001_3::saveSliderStates() {
    QSettings settings("YourCompany", "YourApp");
    settings.beginGroup("SliderStates");
    settings.setValue("verticalSlider", ui->verticalSlider->value());
    settings.setValue("verticalSlider_2", ui->verticalSlider_2->value());
    settings.setValue("verticalSlider_3", ui->verticalSlider_3->value());
    settings.setValue("verticalSlider_4", ui->verticalSlider_4->value());
    settings.setValue("verticalSlider_5", ui->verticalSlider_5->value());
    settings.setValue("verticalSlider_6", ui->verticalSlider_6->value());
    settings.endGroup();
}

void Demo001_3::loadSliderStates() {
    QSettings settings("YourCompany", "YourApp");
    settings.beginGroup("SliderStates");
    ui->verticalSlider->setValue(settings.value("verticalSlider", 11).toInt());
    ui->verticalSlider_2->setValue(settings.value("verticalSlider_2", 22).toInt());
    ui->verticalSlider_3->setValue(settings.value("verticalSlider_3", 9).toInt());
    ui->verticalSlider_4->setValue(settings.value("verticalSlider_4", 11).toInt());
    ui->verticalSlider_5->setValue(settings.value("verticalSlider_5", 0).toInt());
    ui->verticalSlider_6->setValue(settings.value("verticalSlider_6", 0).toInt());
    settings.endGroup();
}

// QSlider 和 QLineEdit 的联动
void Demo001_3::connectSliderAndLineEdit(QSlider* slider, QLineEdit* lineEdit)
{
    QIntValidator* validator = new QIntValidator(slider->minimum(), slider->maximum(), lineEdit);
    lineEdit->setValidator(validator);

    connect(slider, &QSlider::valueChanged, [lineEdit](int value) {
        lineEdit->setText(QString::number(value));
    });

    connect(lineEdit, &QLineEdit::textChanged, [slider](const QString &text) {
        bool ok;
        int value = text.toInt(&ok);
        if (ok && value >= slider->minimum() && value <= slider->maximum()) {
            slider->setValue(value);
        } else if (!text.isEmpty()) {
            int closestValue = qMin(qMax(text.toInt(&ok), slider->minimum()), slider->maximum());
            slider->setValue(closestValue);
        }
    });
}

void Demo001_3::checkSettings() {
    static int lastGroupId = -1;
    static int lastIndex = -1;

    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();

    if (groupId != lastGroupId || index != lastIndex) {
        lastGroupId = groupId;
        lastIndex = index;
        loadSettings();
    }
}

void Demo001_3::loadSettings()
{
    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();
    loadGroupSettings(groupId, index);
}

void Demo001_3::loadGroupSettings(int Id, int Index) {
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(Id));
    QString imagePath1 = settings.value("ImagePath1").toString();
    QString imagePath2 = settings.value("ImagePath2").toString();
    QStringList textList = settings.value("TextList").toStringList();
    settings.endGroup();

    QSize size = ui->Operatewidget->size();

    QPixmap newPixmap;
    if (Index == 1) {
        newPixmap = QPixmap(imagePath1);
    } else if (Index == 2) {
        newPixmap = QPixmap(imagePath2);
    } else {
        newPixmap = QPixmap(":/images/test_image/image.png");
    }

    QPixmap scaledPixmap = newPixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->Operatewidget->setPixmap(scaledPixmap);

    // 更新当前图片的成员变量
    currentPixmap = scaledPixmap;
    scaleFactor = 1.0;
    ui->label_Percentage->setText("100%");

    ui->DatacomboBox->clear();
    ui->DatacomboBox->addItems(textList);
    // qDebug() << "ComboBox items added:" << ui->DatacomboBox->count();
    // connect(ui->DatacomboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(Demo001_3::onComboBoxIndexChanged(int)));
}

void Demo001_3::on_ZoomUpButton_clicked() {
    scaleFactor *= 1.1;

    int newWidth = currentPixmap.width() * scaleFactor;
    int newHeight = currentPixmap.height() * scaleFactor;

    QPixmap scaledImage = currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    ui->Operatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片

    double percentage = (scaleFactor * 100);
    QString percentageStr = QString::number((int)percentage);
    ui->label_Percentage->setText(QString("%1%").arg(percentageStr));
}

void Demo001_3::on_ZoomOutButton_clicked() {
    scaleFactor *= 0.9;

    int newWidth = currentPixmap.width() * scaleFactor;
    int newHeight = currentPixmap.height() * scaleFactor;

    QPixmap scaledImage = currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    ui->Operatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片

    double percentage = scaleFactor * 100;
    QString percentageStr = QString::number((int)percentage);
    ui->label_Percentage->setText(QString("%1%").arg(percentageStr));
}

void Demo001_3::wheelEvent(QWheelEvent *event) {
    // 检查鼠标事件是否发生在 widget 上
    if (ui->Operatewidget->rect().contains(ui->Operatewidget->mapFromGlobal(event->globalPos()))) {
        if (event->angleDelta().y() > 0) {
            scaleFactor *= 1.1;
        } else {
            scaleFactor *= 0.9;
        }

        int newWidth = currentPixmap.width() * scaleFactor;
        int newHeight = currentPixmap.height() * scaleFactor;

        QPixmap scaledImage = currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->Operatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片

        double percentage = scaleFactor * 100;
        QString percentageStr = QString::number((int)percentage);
        ui->label_Percentage->setText(QString("%1%").arg(percentageStr));
    }

    QMainWindow::wheelEvent(event);
}

void Demo001_3::onComboBoxIndexChanged(int index) {
    // 根据index获取图片路径
    QString imagePath = getImagePathFromIndex(index);
    if (!imagePath.isEmpty()) {
        QPixmap newPixmap(imagePath);
        QPixmap scaledPixmap = newPixmap.scaled(ui->Operatewidget->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->Operatewidget->setPixmap(scaledPixmap);
        // 更新当前图片的成员变量
        currentPixmap = scaledPixmap;
        scaleFactor = 1.0;
        ui->label_Percentage->setText("100%");
    }
}

QString Demo001_3::getImagePathFromIndex(int index) {
    // 假设你有一个方法来根据索引获取图片路径
    // 这里需要你根据实际情况来实现这个函数
    QStringList imagePaths = {
        ":/images/test_image/image.png",
        ":/images/test_image/image_2.png",
    };
    if (index >= 0 && index < imagePaths.size()) {
        return imagePaths[index];
    }
    return ":/images/test_image/image.png";
}

void Demo001_3::showEvent(QShowEvent *event) {
    QMainWindow::showEvent(event);
    loadSettings(); // 重新加载设置，确保Operatewidget显示正确
    initFrom();
}

void Demo001_3::hideEvent(QHideEvent *event) {
    QMainWindow::hideEvent(event);
    // 可以在这里保存Operatewidget的状态，以便下次显示时恢复
}

