#include "MainWeb.h"

#include "app/Config.h"
#include <QCoreApplication>
#include <QLabel>
#include <QThread>
//#include <QWebEngineSettings>
//#include <QWebEngineProfile>
#include <QAction>
#include <QToolBar>
#include <QMouseEvent>
#include <QHBoxLayout>
#include <QNetworkProxyFactory>

#include "common/Spdlogger.h"

void MySplash(MainWeb* mainWin)
{
    //===动态程序启动画面===
    QPixmap pixmap("./assets/ui/splash.png");
    QSplashScreen splash(pixmap);
    splash.show();
    QCoreApplication::processEvents();
    QLabel label(&splash);
    label.setStyleSheet("background-color: gray");
    label.setGeometry(100, 480, 800, 20);
    label.show();

    QLabel labelProgress(&splash);
    labelProgress.setStyleSheet("background-color: rgb(29, 54, 102)");
    labelProgress.setGeometry(10, 10, 0, 20);
    labelProgress.show();

    int i = 0;
    while ((++i)<500)
    {
        splash.showMessage(QString("Loading... %1 ms").arg(i), Qt::AlignBottom | Qt::AlignRight, Qt::black);
        labelProgress.setGeometry(100, 480, i*2*0.8, 20);
        QCoreApplication::processEvents();
        QThread::msleep(10);
    }

    splash.finish(mainWin);//程序启动画面结束
}


MainWeb::MainWeb()
{
    QNetworkProxyFactory::setUseSystemConfiguration(false);
    QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);

    this->setWindowTitle("光储充站监控与运营管理平台");
    this->setGeometry(0, 0, 1920, 1080);
    this->hide();
    //this->setMouseTracking(true);
    this->setAttribute(Qt::WA_Hover, true);

    this->initWebview();
    this->mySplash();

    btnFullscreen.setParent(this);
    btnFullscreen.raise();
    btnFullscreen.setGeometry(0, 0, 34, 34);
    btnFullscreen.setStyleSheet("background: transparent; background-image: url(./assets/ui/iconFullscreen.png);");

    QObject::connect(&btnFullscreen, &QPushButton::clicked, [=](bool checked)
        {
            isFullscreen ?  this->showNormal() : this->showFullScreen();
            isFullscreen = !isFullscreen;
            if (isFullscreen)
            {
                btnFullscreen.setStyleSheet("background: transparent; background-image: url(./assets/ui/iconFullscreenExit.png);");
            }
            else
            {
                btnFullscreen.setStyleSheet("background: transparent; background-image: url(./assets/ui/iconFullscreen.png);");
            }
        });

    this->show();
}


void MainWeb::initWebview()
{
    labelWebErr.setParent(this);
    labelWebErr.setGeometry(180, 100, 800, 50);
    labelWebErr.setText("WEB服务异常！！！");
    labelWebErr.setStyleSheet("font: bold 20px;");
    labelWebErr.hide();

    
    //this->setCentralWidget(&webView);
    //webView.setParent(this);
    //webView.setGeometry(0, 0, 1920, 1080);

    //// 在加载页面之前清除缓存
    ////QWebEngineProfile::defaultProfile()->clearHttpCache();
    ////QWebEngineSettings* settings = webView.settings();
    ////settings->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
    ////settings->setAttribute(QWebEngineSettings::LocalStorageEnabled, true);
    ////settings->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true); // 解决http资源加载问题
    ////settings->setAttribute(QWebEngineSettings::PluginsEnabled, true);
    //// 默认设置透明, 解决加载时的白屏闪烁
    ////webView.page()->setBackgroundColor(Qt::transparent);
    ////webView.setContextMenuPolicy(Qt::NoContextMenu);
    //webView.load(QUrl(Config::option.webSrvUrl.c_str()));
    //webView.hide();

    //// 将主 Web 页面的开发者工具页面设置为 devToolsView 的页面
    ////qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "9222"); // 即使内置视图，有时也需要开启调试端口
    ////webView.page()->setDevToolsPage(devTools.page());

    //QObject::connect(&webView, &QWebEngineView::loadFinished, [=](bool ok)
    //    {
    //        if (ok)
    //        {
    //            webView.show();
    //            labelWebErr.hide();
    //        }
    //        else
    //        {
    //            spdlog::error("[web] webview load failed, url={}", Config::option.webSrvUrl);
    //            webView.hide();
    //            labelWebErr.show();
    //        }
    //    });
}
void MainWeb::mySplash()
{
    //===动态程序启动画面===
    splash = std::make_shared<QSplashScreen>(QPixmap("./assets/ui/splash.png"));
    QCoreApplication::processEvents();
    label1.setParent(splash.get());
    label1.setStyleSheet("background-color: gray");
    label1.setGeometry(100, 480, 800, 20);

    labelProgress.setParent(splash.get());
    labelProgress.setStyleSheet("background-color: rgb(29, 54, 102)");
    labelProgress.setGeometry(10, 10, 0, 20);

    splash->show();
    label1.show();
    labelProgress.show();

    int i = 0;
    while ((++i)<100)
    {
        splash->showMessage(QString("Loading... %1 ms").arg(i), Qt::AlignBottom | Qt::AlignRight, Qt::black);
        labelProgress.setGeometry(100, 480, i*10*0.8, 20);
        QCoreApplication::processEvents();
        QThread::msleep(20);
    }
    splash->finish(this);//程序启动画面结束
}

void MainWeb::showDevTools()
{
    if (layout)
    {
        //webView.setParent(this);
        //QLayoutItem* item;
        //while ((item = layout->takeAt(0)) != nullptr) { // 不断取出第一个项
        //    //if (item->widget()) { 
        //    //    delete item->widget(); // 删除控件
        //    //}
        //    //else if (item->layout()) { // 如果是子QLayout
        //    //    delete item->layout(); // 删除子布局
        //    //}
        //    delete item; // 最后删除QLayoutItem本身
        //}
        //delete layout;
        //layout = NULL;
    }
    else
    {
        qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "9222"); // 即使内置视图，有时也需要开启调试端口
        //webView.page()->setDevToolsPage(devTools.page());

        //QWidget* w = new QWidget;
        //w->resize(800, 900);
        //devTools.setParent(w);
        //devTools.resize(800, 900);
        //w->show();

        //// 如果你需要先导航主页面，然后在某个事件（如按钮点击）后显示开发者工具，可以将这行代码放在事件处理函数中。
        //layout = new QHBoxLayout(this);
        //// 将两个视图添加到布局中
        //layout->addWidget(&webView);
        //layout->addWidget(&devTools);
        //layout->setStretch(0, 2); // 主视图占2份
        //layout->setStretch(1, 1); // 开发者工具视图占1份
    }
}

bool MainWeb::event(QEvent* e)
{
    if (QEvent::HoverMove == e->type())//鼠标移动
    {
        QHoverEvent* hoverEvent = static_cast<QHoverEvent*>(e);
        int x = hoverEvent->pos().x();
        int y = hoverEvent->pos().y();

        if (x > 40 || y > 40) { btnFullscreen.hide(); }
        else { btnFullscreen.show(); }
    }
    return QWidget::event(e);
}

void MainWeb::keyPressEvent(QKeyEvent* e)
{
    auto key = e->key();
    if (key == Qt::Key_F12) 
    {
        this->showDevTools();
    }
    else if (key == Qt::Key_F5)
    {
        //webView.update();
        //webView.load(QUrl(Config::option.webSrvUrl.c_str()));
    }
}