#include "MainAndSecondaryCamerasWnd.h"
#include "ui_MainAndSecondaryCamerasWnd.h"
#include <QSettings>
#include <QCloseEvent>
#include <QVBoxLayout>
#include <QTimer>
#include "CameraMaterialGroupWnd/CameraImage/CameraImageHandler.h"
#include <qDebug.h>
#include <QScrollBar>

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

    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup("LastSettings");
    lastRightPixmap = settings.value("LastRightPixmap").value<QPixmap>();
    lasttextList = settings.value("LasttextList").toStringList();
    lastLastRightPixmap = settings.value("LastLastRightPixmap").value<QPixmap>();
    lastLasttextList = settings.value("LastLasttextList").toStringList();
    settings.endGroup();

    initFrom();
    isShow = true;
}

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

void MainAndSecondaryCamerasWnd::initFrom()
{

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainAndSecondaryCamerasWnd::checkSettings);
    timer->start(100);

    ui->Leftlabel_Percentage->setAlignment(Qt::AlignCenter);
    ui->Rightlabel_Percentage->setAlignment(Qt::AlignCenter);

    initSliders();
    initLineEdits();
    // 连接 QSlider 的 valueChanged 信号到 QProgressBar 的 setValue 槽
    connect(ui->RedLightverticalSlider_2, &QSlider::valueChanged, ui->RedLightprogressBar_2, &QProgressBar::setValue);
    connect(ui->BlueLightverticalSlider, &QSlider::valueChanged, ui->BlueLightprogressBar_2, &QProgressBar::setValue);
    connect(ui->GreenLightverticalSlider_5, &QSlider::valueChanged, ui->GreenLightprogressBar_5, &QProgressBar::setValue);
    connect(ui->DotLightverticalSlider_2, &QSlider::valueChanged, ui->DotLightprogressBar_2, &QProgressBar::setValue);
    connectSliderAndLineEdit(ui->RedLightverticalSlider_2, ui->RedLightlineEdit_2);
    connectSliderAndLineEdit(ui->GreenLightverticalSlider_5, ui->GreenLightlineEdit_5);
    connectSliderAndLineEdit(ui->BlueLightverticalSlider, ui->BlueLightlineEdit_2);
    connectSliderAndLineEdit(ui->DotLightverticalSlider_2, ui->DotLightlineEdit_2);
    connect(ui->LeftOperatewidget,&ImageWidget::sendDoubleClicksignal,this,&MainAndSecondaryCamerasWnd::handleDoubleClick);
    connect(ui->RightOperatewidget,&ImageWidget::sendDoubleClicksignal,this,&MainAndSecondaryCamerasWnd::handleDoubleClick);
    QWidget *viewport = ui->scrollArea->viewport();
    QWidget *container = new QWidget(viewport);
    QHBoxLayout *mainLayout = new QHBoxLayout(container);

    mainLayout->setSpacing(28);
    mainLayout->setMargin(0);

    QList<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8};

    QList<Group*> widgets;

    for (int i = 0; i < numbers.size(); ++i) {
        int num = numbers[i];
        CameraImageHandler* manager = new CameraImageHandler(num);
        Group* widget = manager->getGroup();
        connect(widget,&Group::send_button_Signal,this,&MainAndSecondaryCamerasWnd::showAndHide);
        if (widget != nullptr) {
            mainLayout->addWidget(widget);
            widgets.append(widget);
        }

        delete manager;
    }

    // 设置控件的最小高度和最大宽度
    int minHeight = 162;
    int maxWidth = 244;
    int num = -28;
    for (Group* w : widgets) {
        w->setMinimumHeight(minHeight);
        w->setMaximumWidth(maxWidth);
        num = num + 272;
    }

    container->setMinimumSize(num, 162);
    container->setLayout(mainLayout);
    ui->scrollArea->setWidget(container);
    ui->scrollArea->resize(1062, 177);

    ui->LeftOperatewidget->setMouseTracking(true);
    ui->RightOperatewidget->setMouseTracking(true);

    QSettings settings2("YourOrganization", "YourApplication_lastWndType");
    int lastWndType = settings2.value("LastWndType").toInt();
    int LastGroup = settings2.value("LastGroup").toInt();
    lastIndex = lastWndType;
    lastGroupId = LastGroup;
}

void MainAndSecondaryCamerasWnd::initSliders() {
    QList<QSlider*> sliders = {
    ui->RedLightverticalSlider_2, ui->GreenLightverticalSlider_5,
    ui->BlueLightverticalSlider, ui->DotLightverticalSlider_2
    };
    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 MainAndSecondaryCamerasWnd::initProgressBar(){
    QList<int> initialValues = {22, 11, 0, 0};
    QList<QProgressBar*> progressBar = {
        ui->RedLightprogressBar_2,ui->GreenLightprogressBar_5,
        ui->BlueLightprogressBar_2,ui->DotLightprogressBar_2
    };
    for (int i = 0; i < progressBar.size(); ++i) {
        progressBar[i]->setMinimum(0);
        progressBar[i]->setMaximum(100);
        progressBar[i]->setValue(initialValues[i]);
    }
}

void MainAndSecondaryCamerasWnd::handleDoubleClick(){
    QPoint globalMousePos = QCursor::pos();  // 获取当前鼠标的全局位置
    QPoint leftWidgetLocalPos = ui->LeftOperatewidget->mapFromGlobal(globalMousePos);
    QPoint rightWidgetLocalPos = ui->RightOperatewidget->mapFromGlobal(globalMousePos);
    if (ui->LeftOperatewidget->rect().contains(leftWidgetLocalPos)){
        QPixmap scaledImage = Left_currentPixmap.scaled(Left_currentPixmap.width(), Left_currentPixmap.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->LeftOperatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片
        Left_scaleFactor = 1.0;
        ui->Leftlabel_Percentage->setText("100%");
    }
    if(ui->RightOperatewidget->rect().contains(rightWidgetLocalPos)){
        QPixmap scaledImage = Right_currentPixmap.scaled(Right_currentPixmap.width(), Right_currentPixmap.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->RightOperatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片
        Right_scaleFactor = 1.0;
        ui->Rightlabel_Percentage->setText("100%");
    }

}

void MainAndSecondaryCamerasWnd::initLineEdits() {
    QList<QLineEdit*> lineEdits = {
        ui->RedLightlineEdit_2, ui->GreenLightlineEdit_5,
        ui->BlueLightlineEdit_2, ui->DotLightlineEdit_2
    };

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

void MainAndSecondaryCamerasWnd::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 MainAndSecondaryCamerasWnd::checkSettings() {
    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();

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

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

void MainAndSecondaryCamerasWnd::loadGroupSettings(int Id, int Index) {
    // isUpdatingSettings = true;
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(Id));
    QString imagePath1 = settings.value("ImagePath1").toString();
    int materialWndType = settings.value("MaterialWndType").toInt();
    QStringList textList = settings.value("TextList").toStringList();
    settings.endGroup();
    QString lastRightImage = settings.value("LastRightImage").toString();

    QSize size_left = ui->LeftOperatewidget->size();
    QSize size_right = ui->RightOperatewidget->size();

    QPixmap newPixmap;

    if (Index == 1) {
        newPixmap = QPixmap(imagePath1);
        clearLayout(1);

        if (lastIndex == 1) {
            clearLayout(0);
        } else if (lastIndex == 2) {
            clearLayout(0);
            if (lastGroupId == 1) {
                WaferWidget(0);
            } else if (lastGroupId == 2) {
                WaffleWidget(0);
            } else if (lastGroupId == 3) {
                MaterialBoxWidget(0);
            }
        }
    } else if (Index == 2) {
        clearLayout(1);
        clearLayout(0);

        if (materialWndType == 1) {
            if (lastIndex == 2) {
                if (lastGroupId == 1) {
                    WaferWidget(0);
                } else if (lastGroupId == 2) {
                    WaffleWidget(0);
                } else if (lastGroupId == 3) {
                    MaterialBoxWidget(0);
                }
            }
            WaferWidget(1);
        } else if (materialWndType == 2) {
            if (lastIndex == 2) {
                if (lastGroupId == 1) {
                    WaferWidget(0);
                } else if (lastGroupId == 2) {
                    WaffleWidget(0);
                } else if (lastGroupId == 3) {
                    MaterialBoxWidget(0);
                }
            }
            WaffleWidget(1);
        } else if (materialWndType == 3) {
            if (lastIndex == 2) {
                if (lastGroupId == 1) {
                    WaferWidget(0);
                } else if (lastGroupId == 2) {
                    WaffleWidget(0);
                } else if (lastGroupId == 3) {
                    MaterialBoxWidget(0);
                }
            }
            MaterialBoxWidget(1);
        }
    }

    QSettings settings2("YourOrganization", "YourApplication_lastWndType");
    settings2.setValue("LastWndType", lastIndex);
    settings2.setValue("LastGroup", lastGroupId);

    QPixmap scaledPixmap_right = newPixmap.scaled(size_right, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->RightOperatewidget->setPixmap(scaledPixmap_right);

    QPixmap scaledPixmap_left = lastRightPixmap.scaled(size_left, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->LeftOperatewidget->setPixmap(scaledPixmap_left);

    // 更新当前图片的成员变量
    Left_currentPixmap = scaledPixmap_left;
    Left_scaleFactor = 1.0;
    Right_currentPixmap = scaledPixmap_right;
    Right_scaleFactor = 1.0;
    ui->Leftlabel_Percentage->setText("100%");
    ui->Rightlabel_Percentage->setText("100%");

    ui->LeftDataSources->clear();
    ui->LeftDataSources->addItems(lasttextList);
    ui->RightDataSources->clear();
    ui->RightDataSources->addItems(textList);

    // 保存到 QSettings
    settings.beginGroup("LastSettings");
    settings.setValue("LastRightPixmap", lastRightPixmap);
    settings.setValue("LasttextList", lasttextList);
    settings.setValue("LastLastRightPixmap", lastLastRightPixmap);
    settings.setValue("LastLasttextList", lastLasttextList);
    settings.endGroup();

    if (isUpdatingSettings) {
        lastLastRightPixmap = lastRightPixmap;
        lastLasttextList = lasttextList;
        lastRightPixmap = scaledPixmap_right;
        lasttextList = textList;
    }
}

void MainAndSecondaryCamerasWnd::clearLayout(int flag) {
    QWidget* widget = (flag == 1) ? ui->RightOperatewidget : ui->LeftOperatewidget;
    QLayout* layout = widget->layout();

    if (layout) {
        QLayoutItem *child;
        while ((child = layout->takeAt(0)) != nullptr) {
            if (child->widget() != nullptr) {
                delete child->widget();  // 删除控件
            }
            delete child;  // 删除布局项
        }
        delete layout;  // 删除布局本身
    }
}

// 圆晶
void MainAndSecondaryCamerasWnd::WaferWidget(int flag) {
    // QWidget *operatewidget = ui->LeftOperatewidget;

    // if (flag == 1) {
    //     operatewidget = ui->RightOperatewidget;
    // }

    // QGridLayout *layout = new QGridLayout(operatewidget);
    // wafer = new Wafer(1, operatewidget);
    // wafer->initFrom(operatewidget);

    // layout->setContentsMargins(0, 0, 0, 0);
    // layout->addWidget(wafer->globalWidget);
    // operatewidget->setLayout(layout);
    // operatewidget->setFixedSize(476, 476);
}

// 华夫盒
void MainAndSecondaryCamerasWnd::WaffleWidget(int flag) {
    QWidget *operatewidget = ui->LeftOperatewidget;

    if (flag == 1) {
        operatewidget = ui->RightOperatewidget;
    }

    QVBoxLayout *layout = new QVBoxLayout(operatewidget);
    waffle = new Waffle(1, operatewidget);

    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(waffle);
    operatewidget->setLayout(layout);
    operatewidget->setFixedSize(476, 476);
}

// 料盒
void MainAndSecondaryCamerasWnd::MaterialBoxWidget(int flag) {
    QWidget *operatewidget = ui->LeftOperatewidget;

    if (flag == 1) {
        operatewidget = ui->RightOperatewidget;
    }

    QVBoxLayout *layout = new QVBoxLayout(operatewidget);
    materialbox = new MaterialBox(1, operatewidget);

    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(materialbox);
    operatewidget->setLayout(layout);
    operatewidget->setFixedSize(476, 476);
}

void MainAndSecondaryCamerasWnd::on_LeftZoomUpButton_clicked()
{
    Left_scaleFactor *= 1.1;

    int newWidth = Left_currentPixmap.width() * Left_scaleFactor;
    int newHeight = Left_currentPixmap.height() * Left_scaleFactor;

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

    ui->LeftOperatewidget->setPixmap(scaledImage);

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


void MainAndSecondaryCamerasWnd::on_RightZoomUpButton_clicked()
{
    Right_scaleFactor *= 1.1;

    int newWidth = Right_currentPixmap.width() * Right_scaleFactor;
    int newHeight = Right_currentPixmap.height() * Right_scaleFactor;

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

    ui->RightOperatewidget->setPixmap(scaledImage);

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


void MainAndSecondaryCamerasWnd::on_LeftZoomOutButton_clicked()
{
    double Left_newScaleFactor = Left_scaleFactor * 0.9;

    if (Left_newScaleFactor >= 1.0) {
        Left_scaleFactor = Left_newScaleFactor;
    } else {
        Left_scaleFactor = 1.0;
    }

    int newWidth = Left_currentPixmap.width() * Left_scaleFactor;
    int newHeight = Left_currentPixmap.height() * Left_scaleFactor;

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

    ui->LeftOperatewidget->setPixmap(scaledImage);

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


void MainAndSecondaryCamerasWnd::on_RightZoomOutButton_clicked()
{
    double Right_newScaleFactor = Right_scaleFactor * 0.9;

    if (Right_newScaleFactor >= 1.0) {
        Right_scaleFactor = Right_newScaleFactor;
    } else {
        Right_scaleFactor = 1.0;
    }

    int newWidth = Right_currentPixmap.width() * Right_scaleFactor;
    int newHeight = Right_currentPixmap.height() * Right_scaleFactor;

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

    ui->RightOperatewidget->setPixmap(scaledImage);

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

void MainAndSecondaryCamerasWnd::wheelEvent(QWheelEvent *event)
{
    if (ui->LeftOperatewidget->rect().contains(ui->LeftOperatewidget->mapFromGlobal(event->globalPosition().toPoint()))) {
        if (event->angleDelta().y() > 0) {
            Left_scaleFactor *= 1.1;
        } else {
            double Left_newScaleFactor = Left_scaleFactor * 0.9;

            if (Left_newScaleFactor >= 1.0) {
                Left_scaleFactor = Left_newScaleFactor;
            } else {
                Left_scaleFactor = 1.0;
            }
        }

        int newWidth_left = Left_currentPixmap.width() * Left_scaleFactor;
        int newHeight_left = Left_currentPixmap.height() * Left_scaleFactor;

        QPixmap scaledImage_left = Left_currentPixmap.scaled(newWidth_left, newHeight_left, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        // ui->LeftOperatewidget->setPixmap(scaledImage_left);
        // ui->LeftOperatewidget->setPixmapAndPoint(scaledImage_left);

        double percentage_left = Left_scaleFactor * 100;
        QString percentageStr_left = QString::number((int)percentage_left);
        ui->Leftlabel_Percentage->setText(QString("%1%").arg(percentageStr_left));
    }

    if (ui->RightOperatewidget->rect().contains(ui->RightOperatewidget->mapFromGlobal(event->globalPosition().toPoint()))) {
        if (event->angleDelta().y() > 0) {
            Right_scaleFactor *= 1.1;
        } else {
            double Right_newScaleFactor = Right_scaleFactor * 0.9;

            if (Right_newScaleFactor >= 1.0) {
                Right_scaleFactor = Right_newScaleFactor;
            } else {
                Right_scaleFactor = 1.0;
            }
        }

        int newWidth = Right_currentPixmap.width() * Right_scaleFactor;
        int newHeight = Right_currentPixmap.height() * Right_scaleFactor;

        QPixmap scaledImage = Right_currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        // ui->RightOperatewidget->setPixmap(scaledImage);
        // ui->RightOperatewidget->setPixmapAndPoint(scaledImage);

        double percentage = Right_scaleFactor * 100;
        QString percentageStr = QString::number((int)percentage);
        ui->Rightlabel_Percentage->setText(QString("%1%").arg(percentageStr));
    }
    if (ui->scrollArea->rect().contains(ui->scrollArea->mapFromGlobal(event->globalPos()))) {
        // 获取 QScrollArea 的横向滚动条
        QScrollBar *scrollBar = ui->scrollArea->horizontalScrollBar();
        // 根据滚轮滚动方向改变滚动条的值
        if (event->angleDelta().y() > 0) {
            scrollBar->setValue(scrollBar->value() - 50);
        } else {
            scrollBar->setValue(scrollBar->value() + 50);
        }
    }
    QMainWindow::wheelEvent(event);
}

void MainAndSecondaryCamerasWnd::showEvent(QShowEvent *event) {
    isUpdatingSettings = false;
    QMainWindow::showEvent(event);

    loadSettings();
    isUpdatingSettings = true;
}

void MainAndSecondaryCamerasWnd::hideEvent(QHideEvent *event) {
    isUpdatingSettings = false;
    QMainWindow::hideEvent(event);
}

void MainAndSecondaryCamerasWnd::showAndHide(){
    if(isShow == true){
        isShow = false;
    }else{
        isShow = true;
    }
    QList<QLineEdit*> lineEdits = {
        ui->RedLightlineEdit_2, ui->GreenLightlineEdit_5,
        ui->BlueLightlineEdit_2, ui->DotLightlineEdit_2
    };
    QList<QSlider*> sliders = {
        ui->RedLightverticalSlider_2, ui->GreenLightverticalSlider_5,
        ui->BlueLightverticalSlider, ui->DotLightverticalSlider_2
    };
    QList<QProgressBar*> progressBar = {
        ui->RedLightprogressBar_2,ui->GreenLightprogressBar_5,
        ui->BlueLightprogressBar_2,ui->DotLightprogressBar_2
    };
    if(isShow == true){
        for (QLineEdit* lineEdit : lineEdits) {
            lineEdit->show();
        }
        for (int i = 0; i < sliders.size(); ++i) {
            sliders[i]->show();
        }
        for (int i = 0; i < progressBar.size(); ++i) {
            progressBar[i]->show();
        }
        ui->BlueLight->show();
        ui->RedLight->show();
        ui->DotLight->show();
        ui->GreenLight->show();
        ui->BlueLightlabel_2->show();
        ui->RedLightlabel_2->show();
        ui->DotLightlabel_2->show();
        ui->GreenLightlabel_5->show();
    }else{
        for (QLineEdit* lineEdit : lineEdits) {
            lineEdit->hide();
        }
        for (int i = 0; i < sliders.size(); ++i) {
            sliders[i]->hide();
        }
        for (int i = 0; i < progressBar.size(); ++i) {
            progressBar[i]->hide();
        }
        ui->BlueLight->hide();
        ui->RedLight->hide();
        ui->DotLight->hide();
        ui->GreenLight->hide();
        ui->BlueLightlabel_2->hide();
        ui->RedLightlabel_2->hide();
        ui->DotLightlabel_2->hide();
        ui->GreenLightlabel_5->hide();
    }
}
