#include "privacyWidget.h"
#include "ui_privacyWidget.h"

#include <QDesktopWidget>
#include <QScrollBar>

#include "CAppInfo.h"
#include "json/json.h"
#include "awMsgBox.h"
#include "logproc.h"
#include "CSqlite3DBProc.h"

#include "CCommonTools.h"
privacyWidget::privacyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::privacyWidget)
{
    ui->setupUi(this);

    setWindowFlags(Qt::FramelessWindowHint);

    setStyleSheet(g_appInfoPtr->m_sQssStr);		  

	qRegisterMetaType<CAgreement>("CAgreement");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnAgreement, this, &privacyWidget::onAgreement);

	CHttpRequestPackage hrp;
    hrp.sUri = QString("https://%1/oe_client/pc/agreement.json").arg(g_appInfoPtr->m_sEscDomain);
	hrp.nRequestType = RequestType::rtAgreement;
	g_httpBllPtr->getUrl(hrp);

	m_pTimer = std::make_shared<QTimer>();
	m_pTimer->setInterval(1000);
	connect(m_pTimer.get(), &QTimer::timeout, this, [&]() {
		--m_nStaySeconds;
		if (m_nStaySeconds == 0)
		{
			m_pTimer->stop();
			ui->btn_pw_agree->setText(QString::fromLocal8Bit("同意"));
            QString sStyle = QString(R"(QPushButton#btn_pw_agree
            {
                outline:none;
                background:rgba(19,186,140,1);
                border-radius:%1px;
                font-size:%2px;
                font-family:"Microsoft YaHei";
                font-weight:400;
                color:rgba(255,255,255,1);
            })").arg((int)(g_appInfoPtr->m_fRate*6))
                    .arg((int)(g_appInfoPtr->m_fRate*14));
            ui->btn_pw_agree->setStyleSheet(sStyle);

		}
		else
		{
			ui->btn_pw_agree->setText(QString::fromLocal8Bit("同意 (%1秒)").arg(m_nStaySeconds));
		}
	});
    initUI();
}

privacyWidget::~privacyWidget()
{
    awMsgBox::clear(this);
    delete ui;
}

void privacyWidget::initAgreement(QString sContent)
{
	ui->txtb_pw_privacy->verticalScrollBar()->setStyleSheet(QString(R"(QScrollBar:vertical
                                       {
                                           border:0px;
                                           background:rgba(255,255,255,1);
                                           width:%1px;
                                           margin:0 %2 0 %3px;
                                       }


                                       QScrollBar::handle:vertical
                                       {
                                           background:rgba(227,228,232,1);
                                           border-radius:%4px;
                                       }

                                       QScrollBar::add-line:vertical
                                       {
                                           border:0px solid rgba(227,228,232,1);
                                           background:rgba(255,255,255,1);
                                       }


                                       QScrollBar::sub-line:vertical
                                       {
                                           border:0px solid rgba(255,255,255,1);
                                           background:rgba(255,255,255,1);
                                       }


                                       QScrollBar::up-arrow:vertical,QScrollBar::down-arrow:vertical
                                       {
                                           border:0px solid rgba(255,255,255,1);
                                           width:0px;
                                           height:0px;
                                           background:rgba(255,255,255,1);
                                       }


                                       QScrollBar::add-page:vertical
                                       {
                                           background:rgba(255,255,255,1);
                                       }

                                       QScrollBar::sub-page:vertical
                                       {
                                           background:rgba(255,255,255,1);
                                       })").arg((int)(g_appInfoPtr->m_fRate * 40))
		.arg((int)(g_appInfoPtr->m_fRate * 12))
		.arg((int)(g_appInfoPtr->m_fRate * 20))
		.arg((int)(g_appInfoPtr->m_fRate * 4)));

	Json::Reader reader;
	Json::Value jsonRoot = Json::Value::null;
	if (!reader.parse(sContent.toStdString(), jsonRoot))
	{
        ShowMsg(QString::fromLocal8Bit("加载隐私协议出错"), this, MSG_ICON_TYPE::mit_error);
		qDebug() << sContent;
	}
	QTextCursor cursor = ui->txtb_pw_privacy->textCursor();
	QTextBlockFormat textStyleFormat = cursor.blockFormat();
	//    textStyleFormat.setTextIndent(26); //首行缩进
	textStyleFormat.setLineHeight(10, QTextBlockFormat::LineDistanceHeight);
	cursor.setBlockFormat(textStyleFormat);

	int nSize = jsonRoot["sections"].size();
	for (int i = 0; i < nSize; i++)
	{
		Json::Value blocks = jsonRoot["sections"][i];
		for (int j = 0; j < (int)blocks["blocks"].size(); j++)
		{
			if (blocks["blocks"][j]["type"].asString() == "text")
			{
				QTextCharFormat fmt;
				QFont font;
				font.setFamily("Microsoft YaHei");
                font.setPixelSize(g_appInfoPtr->m_fRate*12);
				font.setWeight(QFont::Medium);
				if (blocks["blocks"][j].isMember("param"))
				{

                    if (blocks["blocks"][j]["param"].isMember("bold"))
                    {
                        font.setBold(blocks["blocks"][j]["param"]["bold"].asBool());
                    }

                    if (blocks["blocks"][j]["param"].isMember("italic"))
                    {
                        bool bstyle = blocks["blocks"][j]["param"]["italic"].asBool();
                        font.setItalic(bstyle);
                    }

                    if (blocks["blocks"][j]["param"].isMember("underline"))
                    {
                        font.setUnderline(blocks["blocks"][j]["param"]["underline"].asBool());
                    }

                    if (blocks["blocks"][j]["param"].isMember("strikeOut"))
                    {
                        font.setStrikeOut(blocks["blocks"][j]["param"]["strikeOut"].asBool());
                    }

                    if (blocks["blocks"][j]["param"].isMember("size"))
                    {
                        font.setPixelSize(blocks["blocks"][j]["param"]["size"].asInt());
                    }

                    if (blocks["blocks"][j]["param"].isMember("name"))
                    {
                        font.setFamily(blocks["blocks"][j]["param"]["name"].asString().c_str());
                    }
                }

				fmt.setFont(font);

				QString sTextStr = blocks["blocks"][j]["value"].asString().c_str();
				cursor.insertText(blocks["blocks"][j]["value"].asString().c_str(), fmt);
			}
			else if (blocks["blocks"][j]["type"].asString() == "image")
			{
                QString sImage = blocks["blocks"][j]["value"].asString().c_str();
                if(!(sImage.startsWith("http") || sImage.startsWith("data:image")))
                {
                    sImage = QString("temp/paper/attachment/")  + sImage;
                }

                if(sImage.startsWith("data:image"))
                {
                    QImage img;
                    img = QImage::fromData(QByteArray::fromBase64(CCommonTools::getImageRawBase64Str(sImage).toLatin1()));
                    if(blocks["blocks"][j]["param"].isMember("width")
                            && !QString(blocks["blocks"][j]["param"]["width"].asString().c_str()).isEmpty() &&
                            !QString(blocks["blocks"][j]["param"]["height"].asString().c_str()).isEmpty())
                    {
                        img = img.scaled(QString(blocks["blocks"][j]["param"]["width"].asString().c_str()).toInt(),
                                QString(blocks["blocks"][j]["param"]["height"].asString().c_str()).toInt(),
                                Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

                    }
                    cursor.insertImage(img);
                }
                else
                {
                    QImage img(sImage);
                    if(blocks["blocks"][j]["param"].isMember("width") && !QString(blocks["blocks"][j]["param"]["width"].asString().c_str()).isEmpty() &&
                            !QString(blocks["blocks"][j]["param"]["height"].asString().c_str()).isEmpty())
                    {
                        img = img.scaled(QString(blocks["blocks"][j]["param"]["width"].asString().c_str()).toInt(),
                                QString(blocks["blocks"][j]["param"]["height"].asString().c_str()).toInt(),
                                Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

                    }
                    cursor.insertImage(img);
                }

//				QString strHtml = "";
//				if (blocks["blocks"][j]["param"].isMember("width"))
//				{
//					strHtml = QString("<img src=\"%1\" height=\"%2\" width=\"%3\" align=\"bottom\" />")
//						.arg(blocks["blocks"][j]["value"].asString().c_str())
//						.arg(blocks["blocks"][j]["param"]["height"].asString().c_str())
//						.arg(blocks["blocks"][j]["param"]["width"].asString().c_str());
//				}
//				else
//				{
//					strHtml = "<img src=\"" + QString::fromLocal8Bit(blocks["blocks"][j]["value"].asString().c_str()) + "\"  align=\"bottom\" />";
//				}
//				cursor.insertHtml(strHtml);
			}
		}
		if (i < nSize - 1)
		{
			cursor.insertText("\n");
		}
	}

	cursor.movePosition(QTextCursor::Start);
	ui->txtb_pw_privacy->setTextCursor(cursor);
}

void privacyWidget::initUI()
{
    QDesktopWidget *dekwiget = QApplication::desktop();
    setGeometry(0, 0, dekwiget->width(), dekwiget->height());
    ui->widget_mask->setGeometry(0, 0, dekwiget->width(), dekwiget->height());
    ui->widget_pw_BG->setGeometry((width() - g_appInfoPtr->m_fRate*700)/2, (height() - g_appInfoPtr->m_fRate*591)/2,
                                   g_appInfoPtr->m_fRate*700, g_appInfoPtr->m_fRate*591);
    ui->label_pw_title->adjustSize();
    ui->label_pw_title->setGeometry(g_appInfoPtr->m_fRate*20, g_appInfoPtr->m_fRate*16,
                                    ui->label_pw_title->width(), ui->label_pw_title->height());
    ui->btn_pw_close->setGeometry(ui->widget_pw_BG->width() - g_appInfoPtr->m_fRate*(20 + 16), g_appInfoPtr->m_fRate*19,
                                  g_appInfoPtr->m_fRate*16, g_appInfoPtr->m_fRate*16);
    ui->label_HLine_top->setGeometry(0, g_appInfoPtr->m_fRate*54, ui->widget_pw_BG->width(), g_appInfoPtr->m_fRate*1 < 1 ? 1 : g_appInfoPtr->m_fRate*1);
    ui->txtb_pw_privacy->setGeometry(0, ui->label_HLine_top->y() + ui->label_HLine_top->height() + g_appInfoPtr->m_fRate*20,
                                     ui->widget_pw_BG->width(), g_appInfoPtr->m_fRate*432);
    ui->label_HLine_bottom->setGeometry(0, ui->txtb_pw_privacy->y() + ui->txtb_pw_privacy->height() + g_appInfoPtr->m_fRate*19,
                                        ui->widget_pw_BG->width(), g_appInfoPtr->m_fRate*1 < 1 ? 1 : g_appInfoPtr->m_fRate*1);
    ui->btn_pw_agree->setGeometry(g_appInfoPtr->m_fRate*185, ui->label_HLine_bottom->y() + ui->label_HLine_bottom->height() + g_appInfoPtr->m_fRate*12,
                                  g_appInfoPtr->m_fRate*160, g_appInfoPtr->m_fRate*40);
    ui->btn_pw_disagree->setGeometry(ui->btn_pw_agree->x() + ui->btn_pw_agree->width() + g_appInfoPtr->m_fRate*10, ui->btn_pw_agree->y(),
                                  ui->btn_pw_agree->width(), ui->btn_pw_agree->height());
}

void privacyWidget::onAgreement(CAgreement agreement)
{
	if (agreement.nCode = 200)
	{
		ui->label_pw_title->setText(agreement.sTitle);
		ui->label_pw_title->adjustSize();
		ui->label_pw_title->setGeometry(g_appInfoPtr->m_fRate * 20, g_appInfoPtr->m_fRate * 16,
			ui->label_pw_title->width(), ui->label_pw_title->height());
		m_nStaySeconds = agreement.nStaySeconds;
		initAgreement(agreement.sContent);
		m_pTimer->start();
	}
	else
	{

	}
}

void privacyWidget::on_btn_pw_agree_clicked()
{
	if (m_nStaySeconds > 0)
	{
		return;
	}
	QString sSql = QString("insert or replace into t_agreement (student_id,agreement) values(%1,1)").arg(g_appInfoPtr->m_nStudentId);
	if (!g_sysDBProcPtr->ExcuteSql(sSql.toStdString()))
	{
        ShowMsg(QString::fromLocal8Bit("保存隐私协议信息失败！"), this, MSG_ICON_TYPE::mit_error);
	}
    emit agreement();
}

void privacyWidget::on_btn_pw_disagree_clicked()
{
    emit disAgreement();
}

void privacyWidget::on_btn_pw_close_clicked()
{
    emit disAgreement();
}
