#include "standardAnswer.h"
#include "ui_standardAnswer.h"

#include "CAppInfo.h"
#include "logproc.h"
#include "CCommonTools.h"
standardAnswer::standardAnswer(CSubQuestionStruct &sqs, QWidget *parent) :
    CBaseWidget(parent),
    ui(new Ui::standardAnswer), m_sqs(sqs)
{
    ui->setupUi(this);

    setStyleSheet(g_appInfoPtr->m_sQssStr);

    m_bShowAnswer = false;
	
}

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

void standardAnswer::initAnswer()
{
    ui->txtb_sa_answer->clear();
	QTextCursor cursor = ui->txtb_sa_answer->textCursor();
	QTextCharFormat fmt;
	QFont font;
	font.setFamily("Microsoft YaHei");
	font.setPixelSize(14);
	font.setWeight(QFont::Medium);


	int nRA = m_sqs.vRightAnswer.size();
	QString sRightAnswer = "";
	for (int ira = 0; ira < nRA; ++ira)
	{		
		if (!m_sqs.vRightAnswer[ira].isEmpty())
		{
			Json::Reader reader;
			Json::Value m_jBody = Json::Value::null;
			if (!reader.parse(m_sqs.vRightAnswer[ira].toStdString(), m_jBody))
			{
				//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
				myDebug() << QString::fromLocal8Bit("解析题干出错！");
			}

			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();
						fmt.setFont(font);
						if (m_sqs.sQuestionType == QUESTION_TYPE::SingleChoice ||
							m_sqs.sQuestionType == QUESTION_TYPE::MultipleChoice)							
						{
							std::vector<int>::iterator result = std::find(m_sqs.voptionPermutation.begin(), m_sqs.voptionPermutation.end(), sTextStr.toInt());

							sRightAnswer = QChar('A' + *result);
							cursor.insertText(sRightAnswer);
						}
						else if (m_sqs.sQuestionType == QUESTION_TYPE::TrueOrFalse)
						{
							if (sTextStr == "true")
							{
								cursor.insertText(QString::fromLocal8Bit("正确"));
							}
							else
							{
								cursor.insertText(QString::fromLocal8Bit("错误"));
							}
						}
						else if (m_sqs.sQuestionType == QUESTION_TYPE::FillUp || m_sqs.sQuestionType == QUESTION_TYPE::Essay)
						{
							cursor.insertText(sTextStr, 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->txtb_sa_answer->adjustSize();
	ui->txtb_sa_answer->selectAll();
	ui->txtb_sa_answer->setAlignment(Qt::AlignJustify);
	cursor.movePosition(QTextCursor::End);

	ui->txtb_sa_answer->setTextCursor(cursor);
}

int standardAnswer::setUI(const int nWidth)
{    
    ui->btn_sa_showAnswer->setGeometry(g_appInfoPtr->m_fRate*30, g_appInfoPtr->m_fRate*20, g_appInfoPtr->m_fRate*72, g_appInfoPtr->m_fRate*24);
    ui->label_sa_arrow->setGeometry(ui->btn_sa_showAnswer->x() + ui->btn_sa_showAnswer->width() - g_appInfoPtr->m_fRate*4,
                                    ui->btn_sa_showAnswer->y() + (ui->btn_sa_showAnswer->height())/2,
                                    g_appInfoPtr->m_fRate*8, g_appInfoPtr->m_fRate*4);
    ui->label_sa_answer->adjustSize();
    ui->label_sa_answer->setGeometry(0, 0,
                                     ui->label_sa_answer->width(), ui->label_sa_answer->height());
    ui->txtb_sa_answer->setGeometry(ui->label_sa_answer->x() + ui->label_sa_answer->width(), ui->label_sa_answer->y() - g_appInfoPtr->m_fRate *3,
		nWidth - ui->label_sa_answer->width(), 300);
	ui->txtb_sa_answer->setFixedWidth(nWidth - ui->label_sa_answer->width());
	initAnswer();
	
    int nHeight = ui->txtb_sa_answer->document()->size().height() + g_appInfoPtr->m_fRate*5;
	ui->txtb_sa_answer->setFixedHeight(nHeight);
    ui->widget_sa_answer->setGeometry(ui->btn_sa_showAnswer->x() + g_appInfoPtr->m_fRate*5, ui->btn_sa_showAnswer->y() + ui->btn_sa_showAnswer->height() + g_appInfoPtr->m_fRate * g_appInfoPtr->m_fRate*10,
		nWidth, ui->txtb_sa_answer->height());
    ui->widget_sa_answer->setVisible(false);
	setGeometry(0, 0, nWidth, ui->widget_sa_answer->y() + ui->widget_sa_answer->height() + g_appInfoPtr->m_fRate*20);
    return height();
}


void standardAnswer::on_btn_sa_showAnswer_clicked()
{
    if(!m_bShowAnswer)
    {
		setFixedHeight(ui->widget_sa_answer->y() + ui->widget_sa_answer->height() + g_appInfoPtr->m_fRate * 20);        
		m_bShowAnswer = true;
    }
    else
    {
		setFixedHeight(ui->btn_sa_showAnswer->y() + ui->btn_sa_showAnswer->height() + g_appInfoPtr->m_fRate * 20);        
		m_bShowAnswer = false;
    }
    ui->widget_sa_answer->setVisible(m_bShowAnswer);
    emit heightChange(height());
}

int standardAnswer::widgetType()
{
    return wt_standardAnswer;
}
