#include "WidgetPageWeb.h"
#include <iostream>

WidgetPageWeb::WidgetPageWeb(QWidget* parent, std::string name) : WidgetPage(parent)
{
    wWebView = std::make_shared<QWebEngineView>(this);
    wWebView->setGeometry(0, 0, 1920, 900);
    
    jsHandler = new JsHandler();
         
    webChannel = new QWebChannel();
    // 注册C++对象到QWebChannel，这样远端的QWebChannel也会生成一个对应的JS对象
    // 在JS中引入 qwebchannel.js， 使用 channel.objects.webNative 获取注册的“webNative”
    webChannel->registerObject("webNative", jsHandler);
    wWebView->page()->setWebChannel(webChannel);
    wWebView->setContextMenuPolicy(Qt::NoContextMenu);
    //webEngineView.load(QUrl("https://www.baidu.com"));

    std::string url = "file:///assets/html/" + name + "/index.html";

    std::cout << "===> url=" << url << std::endl;
    wWebView->load(QUrl(url.c_str()));

    // 默认设置透明，解决加载过程中白屏
    wWebView->page()->setBackgroundColor(Qt::transparent);

    // 加载进度
    connect(wWebView.get(), &QWebEngineView::loadProgress, [=](int progress)
        {
            //pWebEngineView->page()->setBackgroundColor(Qt::transparent);
        });
   

    connect(wWebView.get(), &QWebEngineView::loadFinished, this, &WidgetPageWeb::slotLoadFinished);
    connect(jsHandler, &JsHandler::signalShowWebView, this, &WidgetPageWeb::slotShowWebView);

    //std::string htmlContent = "HelloWorld";
    //webEngineView.setHtml(htmlContent.c_str());
    wWebView->hide();

    //webView = std::make_shared<WidgetWeb>(this);
}

void WidgetPageWeb::slotLoadFinished(bool isOk)
{
    //QString jsCode = QString("showalert('%1')").arg("Hello QtWebEngine!");
    //wWebView->page()->runJavaScript(jsCode, [](const QVariant& v) { qDebug() << v.toString(); });
    wWebView->show();
}

void WidgetPageWeb::slotShowWebView()
{
    wWebView->show();
}