#include "mainwindow.h"
#include <QDebug>
#include <fstream>
#include <QFile> 
#include <QGuiApplication>
#include <QTimer>

extern const char* sFilePath;
extern const char* slFilePath;

MainWindow::MainWindow(QObject* parent)
    : QObject(parent), m_next(0),m_Auto(0),m_skip(0),m_save(0), m_saveCount(0),m_drop((0)), m_wheelDelta(0),m_da(0),m_shuru(""),m_weizhix(0),m_weizhiy(0),m_ws(0),m_ad(0),m_fs(0), m_inextra(0), m_inbextra(1)
{
    // 在堆上创建状态变量
    m_currentPage.reset(new QString("index"));
    m_suofang.reset(new int(3));
    m_exit.reset(new int(0));
    m_vzi.reset(new float(0.5));
    m_vhang.reset(new float(0.5));
    m_inliang.reset(new float(0.5));

    // 尝试从文件加载缩放状态
    std::ifstream file(sFilePath);

    if (file.is_open()) {
        std::string firstLine;

        // 只读取文件的第一行
        if (std::getline(file, firstLine)) {
            try {
                // 将第一行内容转换为整数
                int value = std::stoi(firstLine);

                // 验证值是否在合理范围内（可选）
                if (value >= 1 && value <= 10) {
                    *m_suofang = value;
                    qDebug() << "成功从文件加载缩放状态:" << *m_suofang;
                }
                else {
                    qWarning() << "缩放值超出范围 (1-10)，使用默认值。文件值:" << value;
                }
            }
            // 捕获无效参数异常（非数字内容）
            catch (const std::invalid_argument& e) {
                qWarning() << "文件第一行内容无效，使用默认缩放状态。内容:'"
                    << firstLine.c_str() << "'";
            }
            // 捕获数值越界异常
            catch (const std::out_of_range& e) {
                qWarning() << "文件缩放值超出整数范围，使用默认缩放状态。内容:'"
                    << firstLine.c_str() << "'";
            }
        }
        else {
            // 文件存在但为空
            qWarning() << "状态文件为空，使用默认缩放状态:" << *m_suofang;
        }
        file.close();
    }
    else {
        // 文件不存在
        qDebug() << "状态文件不存在，使用默认缩放状态:" << *m_suofang;
    }
    requestSaveCount();
    qApp->installEventFilter(this);
}
QString MainWindow::currentPage() const
{
    return m_currentPage ? *m_currentPage : "index";
}
void MainWindow::setLastSource(const QString& source)
{
    m_lastSource = source;
}
QString MainWindow::getLastSource()
{
    return m_lastSource;
}


int MainWindow::suofang() const
{
    return m_suofang ? *m_suofang : 3;
}

int MainWindow::exit() const
{
    return m_exit ? *m_exit : 0;
}

int MainWindow::next() const
{
    return m_next;
}
int MainWindow::Auto() const
{
    return m_Auto;
}
int MainWindow::skip() const
{
    return m_skip;
}
int MainWindow::save() const
{
    return m_save;
}
float MainWindow::vzi() const
{
    return *m_vzi;
}
float MainWindow::vhang() const
{
    return *m_vhang;
}
float MainWindow::inliang() const
{
    return *m_inliang;
}
int MainWindow::drop() const
{
    return m_drop;
}
int MainWindow::da() const
{
    return m_da;
}
QString MainWindow::shuru() const
{
    return m_shuru;
}
float MainWindow::weizhix() const
{
    return m_weizhix;
}
float MainWindow::weizhiy() const
{
    return m_weizhix;
}
int MainWindow::ws() const
{
    return m_ws;
}
int MainWindow::ad() const
{
    return m_ad;
}
QVariantList MainWindow::elementArray() const
{
    return m_elementArray;
}
int MainWindow::fs() const
{
    return m_fs;
}
int MainWindow::inextra() const
{
    return m_inextra;
}
int MainWindow::inbextra() const
{
    return m_inbextra;
}

void MainWindow::navigateindex()
{
    if (!m_currentPage) return;

    if (*m_currentPage != "index") {
        *m_currentPage = "index";
        emit currentPageChanged();
        m_Auto = 0;
        emit AutoChanged(m_Auto);
        m_skip = 0;
        emit skipChanged(m_skip);
        emit Start(1);
    }
    emit toindex(1);
}

void MainWindow::navigategame(const QString& source)
{
    if (!m_currentPage) return;

    setLastSource(source);

    if (*m_currentPage != "game") {
        *m_currentPage = "game";
        emit currentPageChanged();
    }
}

void MainWindow::navigateload(const QString& source)
{
    if (!m_currentPage) return;

    setLastSource(source);

    if (*m_currentPage != "load") {
        *m_currentPage = "load";
        emit currentPageChanged();
    }
}

void MainWindow::navigateextra()
{
    if (!m_currentPage) return;

    if (*m_currentPage != "extra") {
        *m_currentPage = "extra";
        emit currentPageChanged();
        emit Extra(1);
    }
}

void MainWindow::navigatesetting(const QString& source)
{
    if (!m_currentPage) return;

    setLastSource(source);

    if (*m_currentPage != "setting") {
        *m_currentPage = "setting";
        emit currentPageChanged();
    }
}

void MainWindow::quanping()
{
    if (!m_suofang) return;

    //qDebug() << "调用 quanping()，当前 suofang =" << *m_suofang;

    if (*m_suofang != 1) {
        *m_suofang = 1;
        emit suofangChanged(*m_suofang);
    }
}

void MainWindow::xiaochuang()
{
    if (!m_suofang) return;

    //qDebug() << "调用 xiaochuang()，当前 suofang =" << *m_suofang;

    if (*m_suofang != 0) {
        *m_suofang = 0;
        emit suofangChanged(*m_suofang);
    }
}

void MainWindow::fangda()
{
    if (!m_suofang) return;

    //qDebug() << "调用 fangda()，当前 suofang =" << *m_suofang;

    if (*m_suofang != 2) {
        *m_suofang = 2;
        emit suofangChanged(*m_suofang);
    }
}

void MainWindow::exit1()
{
    *m_exit = 1;
    emit exitChanged(*m_exit);
    *m_exit = 0;
}

void MainWindow::next1()
{
    m_next = 1;
    emit nextChanged(m_next);
    m_next = 0;
}

void MainWindow::Auto1()
{
    m_Auto = ~m_Auto;
    emit AutoChanged(m_Auto);
}
void MainWindow::skip1()
{
    m_skip= ~m_skip;
    emit skipChanged(m_skip);
}
void MainWindow::save1()
{
    QTimer::singleShot(10, [&]() {
        m_save = 1;
        emit saveChanged(m_save);
        });
}
void MainWindow::vzi1(float valuevzi)
{
    if (valuevzi != *m_vzi) {
        *m_vzi = valuevzi;
        emit vziChanged(*m_vzi);
    }
}
void MainWindow::vhang1(float valuevhang)
{
    if (valuevhang != *m_vhang) {
        *m_vhang = valuevhang;
        emit vhangChanged(*m_vhang);
    }
}
void MainWindow::inliang1(float valueinliang)
{
    if (valueinliang != *m_inliang) {
        *m_inliang = valueinliang;
        emit inliangChanged(*m_inliang);
    }
}
void MainWindow::requestSaveCount()
{
    int count = 0;
    QFile file(slFilePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        while (!in.atEnd()) {
            in.readLine(); // 只计算行数，不读取内容
            count++;
        }
        file.close();
    }

    if (m_saveCount != count) {
        m_saveCount = count;
        emit saveCountChanged(m_saveCount);
        qDebug() << "存档数量更新:" << m_saveCount;
        emit refreshImagesRequested();
    }
}
void MainWindow::loadSave(int position)
{
    qDebug() << "发射 loadSave 信号，位置:" << position;
    emit Load(position);
}
int MainWindow::saveCount() const
{
    return m_saveCount;
}
bool MainWindow::fileExists(const QString& filePath) const
{
    return QFile::exists(filePath);
}
void MainWindow::dropsaves(int dropn)
{
    m_drop = dropn;
    emit Drop(m_drop);
}
bool MainWindow::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::Wheel) {
        QWheelEvent* wheelEvent = static_cast<QWheelEvent*>(event);

        // 获取滚轮方向
        const int delta = wheelEvent->angleDelta().y();
        m_wheelDelta = delta; // 更新滚轮值

        // 根据方向发出特定信号
        if (delta > 0) {
            qDebug() << "鼠标滚轮向上滚动";
            emit wheelChanged(1);
        }
        else if (delta < 0) {
            qDebug() << "鼠标滚轮向下滚动";
            emit wheelChanged(-1);
        }
        else {
            emit wheelChanged(0);
        }
        // 阻止事件继续传播（可选）
        return true;
    }

    // 其他事件继续传播
    return QObject::eventFilter(obj, event);
}
int MainWindow::wheelDelta() const
{
    return m_wheelDelta;
}
void MainWindow::da1(int valueda)
{
    if (valueda != m_da) {
        m_da = valueda;
        emit daChanged(m_da);
        m_da = 0;
    }
}
void MainWindow::shuru1(QString valueshuru)
{
    if (valueshuru != m_shuru) {
        m_shuru = valueshuru;
        emit shuruChanged(m_shuru);
        m_shuru = "";
    }
}
void MainWindow::weizhi1(float sx, float sy)
{
    if ((sx != m_weizhix)|| (sy != m_weizhiy)) {
        m_weizhix = sx;
        m_weizhiy = sy;
        emit weizhiChanged(m_weizhix, m_weizhiy);
    }
}
void MainWindow::ws1(int ws)
{
    if (ws != 0) {
        m_ws = ws;
        emit wsChanged(m_ws);
        m_ws = 0;
    }
}
void MainWindow::ad1(int ad)
{
    if (ad != 0) {
        m_ad = ad;
        emit adChanged(m_ad);
        m_ad = 0;
    }
}
void MainWindow::updateElementArray(const QVariantList& newArray)
{
    m_elementArray = newArray;
    QStringList stringList;
    for (const QVariant& variant : m_elementArray) {
        stringList.append(variant.toString());
    }

    QString arrayString = stringList.join(", ");
    emit elementArrayChanged(arrayString);
}
void MainWindow::fs1()
{
    m_fs = 1;
    emit fsChanged(m_fs);
    m_fs = 0;
    QTimer::singleShot(200, [&]() {
        emit fsChanged(m_fs);
    });
}
void MainWindow::inextra1(int inextra1)
{
    m_inextra = inextra1;
    emit inextraChanged(m_inextra);
}
void MainWindow::inbextra1(int inbextra1)
{
    m_inbextra = inbextra1;
    emit inbextraChanged(m_inbextra);
}