#include "Group.h"
#include "ui_Group.h"
#include <QDebug>
#include <QMouseEvent>
#include <QSettings>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>
// #include "MainWnd.h"

// 静态变量初始化
Group* Group::currentlySelectedGroup = nullptr;
Group* Group::previouslySelectedBlueGroup = nullptr;
Group* Group::lastClickedGroup = nullptr;
int Group::lastClickedIndex = 0;
int Group::lastSavedIndex = 1;

Group::Group(int Id, const QString& imagePath1, int MaterialWindowType, const QStringList& textList, QWidget* parent)
    : QWidget(parent), ui(new Ui::Group), groupId(Id)
{
    ui->setupUi(this);

    QPixmap pixmap1(imagePath1);
    ui->Imagewidget_left->setPixmap(pixmap1);

    ui->DatacomboBox->addItems(textList);
    ui->GroupButton->setStyleSheet(
        "QPushButton:hover {"
        "   background-color: #45a049;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #3e8e41;"
        "}"
        );

    ui->Imagewidget_left->setProperty("groupId", Id);
    ui->Imagewidget_right->setProperty("groupId", Id);

    if (MaterialWindowType == 1) {
        wafer = new Wafer(0, ui->Imagewidget_right);
        WaferWidget();
    } else if (MaterialWindowType == 2) {
        waffle = new Waffle(0, ui->Imagewidget_right);
        WaffleWidget();
    } else if (MaterialWindowType == 3) {
        materialbox = new MaterialBox(0, ui->Imagewidget_right);
        MaterialBoxWidget();
    }

    saveGroupSettings(Id, imagePath1, MaterialWindowType, textList);
    connect(ui->GroupButton, &QPushButton::clicked, this, &Group::onclickbutton);
    initForm();

    connect(this, &Group::groupSelected, this, &Group::onGroupSelected);
}

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

void Group::initForm()
{
    ui->Imagewidget_left->installEventFilter(this);
    ui->Imagewidget_right->installEventFilter(this);

    // MainWnd *mainWindow = new MainWnd();
    // connect(mainWindow,&MainWnd::styleChanged,this,&Group::Changedstyle);
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Group::Changedstyle);
    timer->start(100);
}

void Group::Changedstyle()
{
    QSettings settings("YourCompany", "YourApplication_style");
    int flag = settings.value("Flag_Style", 0).toInt();

    if (flag == 0) {
        ui->DatacomboBox->setStyleSheet("background-color: #FFFFFF;");
    } else {
        ui->DatacomboBox->setStyleSheet("background-color: #4C4FA6;");
    }
}

bool Group::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonDblClick) {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            int groupId = obj->property("groupId").toInt();
            QSettings settings("YourCompany", "YourApplication_");
            settings.setValue("GroupId", groupId);
            int index = 0;
            if (obj == this->ui->Imagewidget_left) {
                index = 1;
                settings.setValue("Index", 1);
                check_selected(1);
            } else if (obj == this->ui->Imagewidget_right) {
                index = 2;
                settings.setValue("Index", 2);
                check_selected(2);
            }
            emit groupSelected(this, index);
            return true;
        }
    }
    return QWidget::eventFilter(obj, event);
}

void Group::check_selected(int index)
{
    if (index == 1) {
        ui->leftBackground->setStyleSheet("border: 2px solid red;");
    } else if (index == 2) {
        ui->rightBackground->setStyleSheet("border: 2px solid red;");
    }
}

void Group::saveGroupSettings(int Id, const QString& imagePath1, int materialWndType, const QStringList& textList)
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(Id));
    settings.setValue("ImagePath1", imagePath1);
    settings.setValue("MaterialWndType", materialWndType);
    settings.setValue("TextList", textList);
    settings.endGroup();
}

void Group::WaferWidget()
{
    QVBoxLayout *layout2 = new QVBoxLayout(ui->Imagewidget_right);
    wafer->paintInitFrom(ui->Imagewidget_right);

    QLabel* pixmapLabel = new QLabel();
    pixmapLabel->setPixmap(wafer->getGlobalPixmap());

    ui->Imagewidget_right->setLayout(layout2);
    ui->Imagewidget_right->setFixedSize(110, 110);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout2->addWidget(pixmapLabel);
}

void Group::WaffleWidget()
{
    QVBoxLayout *layout2 = new QVBoxLayout(ui->Imagewidget_right);
    ui->Imagewidget_right->setLayout(layout2);
    ui->Imagewidget_right->setFixedSize(110, 110);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout2->addWidget(waffle);
}

void Group::MaterialBoxWidget()
{
    QVBoxLayout *layout2 = new QVBoxLayout(ui->Imagewidget_right);
    ui->Imagewidget_right->setLayout(layout2);
    ui->Imagewidget_right->setFixedSize(110, 110);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout2->addWidget(materialbox);
}

void Group::onclickbutton(){
    QSettings settings("YourCompany", "YourApplication_Button");
    settings.setValue("GroupId_button", groupId);

    emit send_button_Signal();
}

void Group::setDatacomboBox(int index){
    ui->DatacomboBox->setCurrentIndex(index);
}

void Group::on_DatacomboBox_currentIndexChanged(int index){
    send_ComboBox_singal(currentGroupId,index);
}

void Group::onGroupSelected(Group* group, int index)
{
    QSettings settings("OrganizationName__", "ApplicationName__");
    int currentLastSavedIndex = settings.value("lastIndex", 1).toInt();

    // 清除当前红色边框
    if (currentlySelectedGroup != nullptr) {
        currentlySelectedGroup->ui->leftBackground->setStyleSheet("");
        currentlySelectedGroup->ui->rightBackground->setStyleSheet("");
    }

    // 清除当前蓝色边框
    if (previouslySelectedBlueGroup != nullptr) {
        previouslySelectedBlueGroup->ui->leftBackground->setStyleSheet("");
        previouslySelectedBlueGroup->ui->rightBackground->setStyleSheet("");
    }

    if (currentLastSavedIndex == 1 || currentLastSavedIndex == 3) {
        // 仅当前选中设为红色，蓝色边框清空
        previouslySelectedBlueGroup = nullptr;
    } else if (currentLastSavedIndex == 2) {
        // 当前选中设为红色，上一个选中设为蓝色
        if (lastClickedGroup != nullptr) {
            QString blueBorderStyle = "border: 2px solid blue;";
            // 即使是同一个实例，只要索引不同就设置蓝色边框
            if (lastClickedGroup == group && lastClickedIndex != index) {
                if (lastClickedIndex == 1) {
                    lastClickedGroup->ui->leftBackground->setStyleSheet(blueBorderStyle);
                } else if (lastClickedIndex == 2) {
                    lastClickedGroup->ui->rightBackground->setStyleSheet(blueBorderStyle);
                }
                previouslySelectedBlueGroup = lastClickedGroup;
            } else if (lastClickedGroup != group) {
                if (lastClickedIndex == 1) {
                    lastClickedGroup->ui->leftBackground->setStyleSheet(blueBorderStyle);
                } else if (lastClickedIndex == 2) {
                    lastClickedGroup->ui->rightBackground->setStyleSheet(blueBorderStyle);
                }
                previouslySelectedBlueGroup = lastClickedGroup;
            }
        }
    }

    // 更新当前选中的 Group 实例
    currentlySelectedGroup = group;
    // 将当前选中的边框设为红色
    group->check_selected(index);

    // 更新上一次点击的记录
    lastClickedGroup = group;
    lastClickedIndex = index;
}

void Group::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    loadBorderSettings();
}

void Group::hideEvent(QHideEvent *event) {
    QWidget::hideEvent(event);
    saveBorderSettings();  // 保存边框颜色信息
}

void Group::saveBorderSettings()
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(groupId));

    QString leftStyle = ui->leftBackground->styleSheet();
    if (leftStyle.contains("blue", Qt::CaseInsensitive)) {
        leftStyle = ""; // 清除样式
        // 记录该边框信息
        recordBorderInfo(groupId, "Left");
    }
    settings.setValue("LeftBorderStyle", leftStyle);

    QString rightStyle = ui->rightBackground->styleSheet();
    if (rightStyle.contains("blue", Qt::CaseInsensitive)) {
        rightStyle = ""; // 清除样式
        // 记录该边框信息
        recordBorderInfo(groupId, "Right");
    }
    settings.setValue("RightBorderStyle", rightStyle);

    settings.setValue("LastClickedIndex", lastClickedIndex);
    settings.setValue("LastSavedIndex", lastSavedIndex);

    if (currentlySelectedGroup == this) {
        settings.setValue("IsCurrentlySelected", true);
    } else {
        settings.setValue("IsCurrentlySelected", false);
    }

    settings.endGroup();
}

void Group::recordBorderInfo(int groupId, const QString& side)
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup("ModifiedBorders");
    QString key = QString("%1_%2").arg(groupId).arg(side);
    settings.setValue(key, true);
    settings.endGroup();
}

void Group::loadBorderSettings()
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(groupId));

    QString leftStyle = settings.value("LeftBorderStyle", "").toString();
    QString rightStyle = settings.value("RightBorderStyle", "").toString();
    lastClickedIndex = settings.value("LastClickedIndex", 0).toInt();
    lastSavedIndex = settings.value("LastSavedIndex", 1).toInt();
    bool isCurrentlySelected = settings.value("IsCurrentlySelected", false).toBool();


    QSettings settings2("OrganizationName__", "ApplicationName__");
    int Index = settings2.value("lastIndex", 1).toInt();

    if (Index == 2) {
        QSettings borderInfoSettings("YourOrganization", "YourApplication");
        borderInfoSettings.beginGroup("ModifiedBorders");
        QString leftKey = QString("%1_Left").arg(groupId);
        QString rightKey = QString("%1_Right").arg(groupId);

        // 检查左边框是否需要还原
        if (borderInfoSettings.contains(leftKey)) {
            leftStyle = getBlueBorderStyle();
            borderInfoSettings.remove(leftKey); // 移除记录，避免下次重复处理
        }
        // 检查右边框是否需要还原
        if (borderInfoSettings.contains(rightKey)) {
            rightStyle = getBlueBorderStyle();
            borderInfoSettings.remove(rightKey);
        }
        borderInfoSettings.endGroup();
    }

    ui->leftBackground->setStyleSheet(leftStyle);
    ui->rightBackground->setStyleSheet(rightStyle);

    if (isCurrentlySelected) {
        currentlySelectedGroup = this;
        if (leftStyle.contains("red")) {
            lastClickedIndex = 1;
        } else if (rightStyle.contains("red")) {
            lastClickedIndex = 2;
        }
    }

    settings.endGroup();
}

QString Group::getBlueBorderStyle()
{
    static const QString blueBorderStyle = "border: 2px solid blue;";
    return blueBorderStyle;
}
