#include "questionBody.h"
#include "ui_questionBody.h"

#include <QFile>
//#include "PaperDef.h"
#include "CAppInfo.h"
#include "CCommonTools.h"

questionBody::questionBody(const Json::Value jBody, QWidget *parent) :
    CBaseWidget(parent),
    ui(new Ui::questionBody)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose);

    m_jBody = jBody;

    setStyleSheet(g_appInfoPtr->m_sQssStr);
}

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

int questionBody::setUI(const int nWidth, const int nNum)
{
    int nNumber = nNum;
    setGeometry(0, 0, nWidth, g_appInfoPtr->m_fRate*300);
    ui->tb_questionBody->setGeometry(0, 0, nWidth, g_appInfoPtr->m_fRate*300);
    ui->tb_questionBody->setFixedWidth(nWidth);
    QTextCursor cursor = ui->tb_questionBody->textCursor();
    QTextBlockFormat textStyleFormat = cursor.blockFormat();
//    textStyleFormat.setTextIndent(26); //首行缩进
    textStyleFormat.setLineHeight(g_appInfoPtr->m_fRate*5, QTextBlockFormat::LineDistanceHeight);
    cursor.setBlockFormat(textStyleFormat);

    int nSize = m_jBody["sections"].size();
    for(int i = 0; i < nSize; i ++)
    {
        Json::Value blocks = m_jBody["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*16);
                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();
                int nFIndex = sTextStr.indexOf("##");
                if(nFIndex >= 0)
                {
                    int nStartIdex = 0;
                    while((nFIndex = sTextStr.indexOf("##", nStartIdex)) >=0)
                    {
                        int nSIndex = sTextStr.indexOf("##", nFIndex + 2);
                        if(nSIndex >= 0)
                        {
                            int nNumLen = nSIndex - nFIndex - 2;
                            QString sNumber = sTextStr.mid(nFIndex + 2, nNumLen);
                            if(IsNumber(sNumber))
                            {
                                sTextStr.replace(nFIndex + 2, nNumLen, QString::number(nNumber));
                                nSIndex = nSIndex - nNumLen +  QString::number(nNumber).length();
                                fmt.setFont(font);

                                cursor.insertText(sTextStr.mid(nStartIdex, nFIndex - nStartIdex), fmt);

                                QFont font1(font);
                                font1.setUnderline(true);
                                QBrush br = fmt.foreground();
                                fmt.setForeground(QColor(0, 122, 255));
                                fmt.setFont(font1);

                                cursor.insertText("  " + QString::number(nNumber) + "  ", fmt);
                                fmt.setForeground(br);
                                nNumber++;
                            }
                            else
                            {
                                fmt.setFont(font);
                                cursor.insertText(sTextStr.mid(nStartIdex, nSIndex + 2- nStartIdex), fmt);
                            }
                            nStartIdex = nSIndex + 2;
                        }
                        else
                        {
                            fmt.setFont(font);
                            cursor.insertText(sTextStr.mid(nStartIdex, nFIndex + 2- nStartIdex), fmt);
                            nStartIdex = nFIndex + 2;
                        }
                    }

                    fmt.setFont(font);
                    cursor.insertText(sTextStr.mid(nStartIdex, sTextStr.length()- nStartIdex), fmt);
                }
                else
                {
                    fmt.setFont(font);
                    cursor.insertText(sTextStr, fmt);
                }
//                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");
        }
    }

    ui->tb_questionBody->adjustSize();

    ui->tb_questionBody->selectAll();
    ui->tb_questionBody->setAlignment(Qt::AlignJustify);


    cursor.movePosition(QTextCursor::End);
    ui->tb_questionBody->setTextCursor(cursor);

    ui->tb_questionBody->setFixedHeight(ui->tb_questionBody->document()->size().height()+5);
    setGeometry(0, 0, nWidth, ui->tb_questionBody->y() + ui->tb_questionBody->height() + 10);
    return height();
}

bool questionBody::IsNumber(const QString sText)
{
    QByteArray ba = sText.toLatin1();
    const char *s = ba.data();
    bool bret = true;
    while(*s)
    {
        if(*s < '0' || *s > '9')
        {
            bret = false;
            break;
        }
        s++;
    }
    return bret;
}

void questionBody::setQuesionNo(const QString sItemNo)
{
    QTextCursor cursor = ui->tb_questionBody->textCursor();
    QTextCharFormat fmt;
    QFont font;
    font.setFamily("Microsoft YaHei");
    font.setPixelSize(16);
    font.setWeight(QFont::Medium);
    cursor.insertText(sItemNo, fmt);
    fmt.setFont(font);
    ui->tb_questionBody->setTextCursor(cursor);
}

int questionBody::widgetType()
{
    return wt_questionBody;
}

