#include "qaaBlank.h"
#include "ui_qaaBlank.h"

#include <QFile>
#include <QTextBlock>
//#include "MsgDlg.h"
#include "CAppInfo.h"
#include "CCommonTools.h"
#include "logproc.h"
#include <QTextDocumentFragment>

qaaBlank::qaaBlank(QWidget *parent) :
    CBaseWidget(parent),
    ui(new Ui::qaaBlank)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose);

    setStyleSheet(g_appInfoPtr->m_sQssStr);

}

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

int qaaBlank::setUI(const int nWidth)
{
    setGeometry(0, 0, nWidth, g_appInfoPtr->m_fRate*284);
    ui->btn_qaab_copy->setGeometry(0, g_appInfoPtr->m_fRate*20, g_appInfoPtr->m_fRate*40, g_appInfoPtr->m_fRate*22);
    ui->btn_qaab_cut->setGeometry(ui->btn_qaab_copy->x() + ui->btn_qaab_copy->width() + g_appInfoPtr->m_fRate*5,
                                  ui->btn_qaab_copy->y(), ui->btn_qaab_copy->width(), ui->btn_qaab_copy->height());
    ui->btn_qaab_paste->setGeometry(ui->btn_qaab_cut->x() + ui->btn_qaab_cut->width() + g_appInfoPtr->m_fRate*5,
                                    ui->btn_qaab_copy->y(), ui->btn_qaab_copy->width(), ui->btn_qaab_copy->height());
    ui->btn_qaab_superscript->setGeometry(ui->btn_qaab_paste->x() + ui->btn_qaab_paste->width() + g_appInfoPtr->m_fRate*5,
                                    ui->btn_qaab_copy->y(), ui->btn_qaab_copy->width(), ui->btn_qaab_copy->height());
    ui->btn_qaab_cancelSup->setGeometry(ui->btn_qaab_superscript->x() + ui->btn_qaab_superscript->width() + g_appInfoPtr->m_fRate*5,
                                        ui->btn_qaab_copy->y(), g_appInfoPtr->m_fRate*64, ui->btn_qaab_copy->height());
    ui->btn_qaab_subscript->setGeometry(ui->btn_qaab_cancelSup->x() + ui->btn_qaab_cancelSup->width() + g_appInfoPtr->m_fRate*5,
                                    ui->btn_qaab_copy->y(), ui->btn_qaab_copy->width(), ui->btn_qaab_copy->height());
    ui->btn_qaab_cancelSub->setGeometry(ui->btn_qaab_subscript->x() + ui->btn_qaab_subscript->width() + g_appInfoPtr->m_fRate*5,
                                    ui->btn_qaab_copy->y(), ui->btn_qaab_cancelSup->width(), ui->btn_qaab_copy->height());
    ui->tedt_qaa_blank->setGeometry(0, ui->btn_qaab_copy->y() + ui->btn_qaab_copy->height() + g_appInfoPtr->m_fRate*12, g_appInfoPtr->m_fRate*640, g_appInfoPtr->m_fRate*220);
    return g_appInfoPtr->m_fRate*284;
}

int qaaBlank::widgetType()
{
    return wt_QAABlank;
}

void qaaBlank::on_tedt_qaa_blank_textChanged()
{        
    QString sAnswer = ui->tedt_qaa_blank->toPlainText();
    if(sAnswer.isEmpty())
    {
        emit answerChanged(false);
    }
    else
    {
        emit answerChanged(true);
    }

    QApplication::processEvents();
}

void qaaBlank::getAnswer(QString &sAnswer)
{
    sAnswer = "";
    auto bodyDoc = ui->tedt_qaa_blank->document();
    if(!bodyDoc->isEmpty())
    {
        Json::Value sectionJson = Json::Value::null;
        for (QTextBlock it = bodyDoc->begin(); it != bodyDoc->end(); it = it.next())
        {
            Json::Value blocksJson = Json::Value::null;
            for(auto fragit = it.begin(); !fragit.atEnd(); ++fragit)
            {
                if(fragit.fragment().charFormat().isImageFormat())
                {//图片
                    const std::string& txt = fragit.fragment().charFormat().toImageFormat().name().toLocal8Bit().toStdString();

                    if(0 == txt.find_first_of("data:image/"))
                    {

                    }
                    else
                    {

                    }
                }
                else
                {//文本
                    QString sText = fragit.fragment().text();
                    if(fragit.fragment().charFormat().verticalAlignment() == QTextCharFormat::AlignSuperScript)
                    {
                        sText = QString("<sup>%1</sup>").arg(sText);

                    }
                    else if(fragit.fragment().charFormat().verticalAlignment() == QTextCharFormat::AlignSubScript)
                    {
                        sText = QString("<sub>%1</sub>").arg(sText);
                    }
                    sAnswer += sText;
                }
            }           
            sAnswer += "\r\n";
        }
    }
}

void qaaBlank::setAnswer(QString sAnswer)
{
    if(sAnswer.isEmpty())
    {
        return;
    }
    Json::Value jAnswer = Json::Value::null;
    Json::Reader reader;
    qDebug()<<sAnswer;
    if(!reader.parse(sAnswer.toStdString(), jAnswer))
    {
//        ShowMsg(QString::fromLocal8Bit("解析答案出错！"), g_appInfoPtr->m_answerWidget);
        myDebug()<<QString::fromLocal8Bit("解析答案出错！");
        return;
    }
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
   // for(int ia = 0; ia < (int)jAnswer.size(); ia++)
    {
        int nSize = jAnswer/*[ia]*/["sections"].size();
        for(int i = 0; i < nSize; i ++)
        {
            Json::Value blocks = jAnswer/*[ia]*/["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*14);
                    font.setWeight(QFont::Medium);
                    fmt.setFont(font);
                    fmt.setVerticalAlignment(QTextCharFormat::AlignNormal);
                    QString sTextStr = blocks["blocks"][j]["value"].asString().c_str();
                    QRegExp reg("<su([b,p])(>)");
                    if(sTextStr.indexOf(reg) >= 0)
                    {
                        int nFIndex = 0;
                        int nStartIdex = 0;
                        while((nFIndex = sTextStr.indexOf(reg, nStartIdex)) >=0)
                        {
                            bool bSub = sTextStr.mid(nFIndex, 5) == "<sub>" ? true : false;
                            int nSIndex = 0;
                            if(bSub)
                            {
                                nSIndex = sTextStr.indexOf("</sub>", nFIndex + 5);
								fmt.setVerticalAlignment(QTextCharFormat::AlignNormal);
								cursor.insertText(sTextStr.mid(nStartIdex, nFIndex - nStartIdex), fmt);

                                fmt.setVerticalAlignment(QTextCharFormat::AlignSubScript);
                            }
                            else
                            {
                                nSIndex = sTextStr.indexOf("</sup>", nFIndex + 5);
								fmt.setVerticalAlignment(QTextCharFormat::AlignNormal);
								cursor.insertText(sTextStr.mid(nStartIdex, nFIndex - nStartIdex), fmt);

                                fmt.setVerticalAlignment(QTextCharFormat::AlignSuperScript);
                            }


                            if(nSIndex >= 0)
                            {                                
                                cursor.insertText(sTextStr.mid(nFIndex + 5, nSIndex - nFIndex - 5), fmt);
                                nStartIdex = nSIndex + 6;
                            }
                        }
                        fmt.setVerticalAlignment(QTextCharFormat::AlignNormal);
                        cursor.insertText(sTextStr.mid(nStartIdex, sTextStr.length()- nStartIdex), fmt);
                    }                    
                    else
                    {
						if (blocks["blocks"][j].isMember("param"))
						{
							if (blocks["blocks"][j]["param"].isMember("sup"))
							{
								fmt.setVerticalAlignment(QTextCharFormat::AlignSuperScript);
							}
							else if (blocks["blocks"][j]["param"].isMember("sub"))
							{
								fmt.setVerticalAlignment(QTextCharFormat::AlignSubScript);
							}
						}
                        cursor.insertText(blocks["blocks"][j]["value"].asString().c_str(), fmt);
                    }
                }
            }
            if(i < nSize - 1)
            {
                cursor.insertText("\n");
            }
        }
    }
    ui->tedt_qaa_blank->setTextCursor(cursor);
}

void qaaBlank::on_btn_qaab_mark_clicked()
{
    //标记
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }
    QTextCharFormat fmt = cursor.charFormat();
    QTextCharFormat oldFmt = fmt;
	if (fmt.background() == QColor(22, 122, 22))
//	{
//		fmt.setBackground(QColor(255, 255, 255));
//	}
//	else
	{
		fmt.setBackground(QColor(22, 122, 22));
	}
    
    cursor.mergeCharFormat(fmt);
    
    cursor.movePosition(QTextCursor::End);
    cursor.mergeCharFormat(oldFmt);
    ui->tedt_qaa_blank->setTextCursor(cursor);
}

void qaaBlank::on_btn_qaab_cut_clicked()
{
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }

    ui->tedt_qaa_blank->cut();

}

void qaaBlank::on_btn_qaab_paste_clicked()
{

    ui->tedt_qaa_blank->paste();
}

void qaaBlank::on_btn_qaab_superscript_clicked()
{
    //上标
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }
    QTextCharFormat fmt = cursor.charFormat();
    QTextCharFormat oldFmt = fmt;
    fmt.setVerticalAlignment(QTextCharFormat::AlignSuperScript);
    cursor.mergeCharFormat(fmt);

    cursor.movePosition(QTextCursor::End);
    cursor.setCharFormat(oldFmt);
    ui->tedt_qaa_blank->setTextCursor(cursor);

}

void qaaBlank::on_btn_qaab_cancelSup_clicked()
{
    //取消上标
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }
	QString tdf = cursor.selection().toHtml();
	int n = tdf.indexOf("vertical-align:sup");
    QTextCharFormat fmt = cursor.charFormat();
    if(tdf.indexOf("vertical-align:sup") < 0)
    {
        return;
    }
    fmt.setVerticalAlignment(QTextCharFormat::AlignNormal);
    cursor.mergeCharFormat(fmt);
    ui->tedt_qaa_blank->setTextCursor(cursor);
}

void qaaBlank::on_btn_qaab_subscript_clicked()
{
    //下标
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }
    QTextCharFormat fmt = cursor.charFormat();
    QTextCharFormat oldFmt = fmt;
    fmt.setVerticalAlignment(QTextCharFormat::AlignSubScript);
    cursor.mergeCharFormat(fmt);
	cursor.movePosition(QTextCursor::End);
	cursor.setCharFormat(oldFmt);
    ui->tedt_qaa_blank->setTextCursor(cursor);    
}

void qaaBlank::on_btn_qaab_cancelSub_clicked()
{
    //取消下标
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }
    QString tdf = cursor.selection().toHtml();
	int n = tdf.indexOf("vertical-align:sub");
	
    QTextCharFormat fmt = cursor.charFormat();
    
    if(tdf.indexOf("vertical-align:sub") < 0)
    {
        return;
    }
    fmt.setVerticalAlignment(QTextCharFormat::AlignNormal);
    cursor.mergeCharFormat(fmt);
    ui->tedt_qaa_blank->setTextCursor(cursor);
}

void qaaBlank::on_btn_qaab_copy_clicked()
{
    QTextCursor cursor = ui->tedt_qaa_blank->textCursor();
    if (!cursor.hasSelection())
    {
        return;
    }

    ui->tedt_qaa_blank->copy();
}
