#include "clopPaperDetail.h"
#include "ui_clopPaperDetail.h"

#include "CAppInfo.h"
#include "questionBody.h"
#include "audioPlay.h"
#include "logproc.h"
#include "CCommonTools.h"
#include "awMsgBox.h"
 
clopPaperDetail::clopPaperDetail(__int64 nExamRecordDataId, QString sCourseCode, bool bFromCache, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::clopPaperDetail), m_sCourseCode(sCourseCode), m_nExamRecordDataId(nExamRecordDataId),m_bFromCache(bFromCache)
{
    ui->setupUi(this);

    setStyleSheet(g_appInfoPtr->m_sQssStr);

	qRegisterMetaType<CFindExamRecordDataEntity>("CFindExamRecordDataEntity");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnFindExamRecordDataEntity, this, &clopPaperDetail::onFindExamRecordDataEntity);
	qRegisterMetaType<CGetExamRecordPaperStruct>("CGetExamRecordPaperStruct");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetExamRecordPaperStruct, this, &clopPaperDetail::onGetExamRecordPaperStruct);
	qRegisterMetaType<CGetExamRecordQuestions>("CGetExamRecordQuestions");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetExamRecordQuestions, this, &clopPaperDetail::onGetExamRecordQuestions);
	qRegisterMetaType<CGetQuestion>("CGetQuestion");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetQuestion, this, &clopPaperDetail::onGetQuestion);
	{
		CHttpRequestPackage hrp;
		hrp.sUri = "/api/ecs_oe_admin/client/exam/process/getExamRecordPaperStruct";
		hrp.sParamList.push_back(QString("examRecordDataId,%1").arg(nExamRecordDataId));
        if(bFromCache)
        {
            hrp.sParamList.push_back(QString("fromCache,%1").arg(true));
        }
		hrp.nRequestType = RequestType::rtGetExamRecordPaperStruct;
		hrp.eParamType = HttpParamType::hptUrl;
		g_httpBllPtr->post(hrp);
	}

	{
		CHttpRequestPackage hrp;
		hrp.sUri = QString("/api/ecs_oe_admin/client/exam/process/findExamRecordDataEntity");
		hrp.sParamList.push_back(QString("examRecordDataId,%1").arg(m_nExamRecordDataId));
        if(bFromCache)
        {
            hrp.sParamList.push_back(QString("fromCache,%1").arg(true));
        }
		hrp.nRequestType = RequestType::rtFindExamRecordDataEntity;
		hrp.eParamType = HttpParamType::hptUrl;
		g_httpBllPtr->post(hrp);
	}
}

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

int clopPaperDetail::setUI(const int nWidth)
{
    ui->btn_expandPaper->setGeometry(g_appInfoPtr->m_fRate*30, 0, g_appInfoPtr->m_fRate*108, g_appInfoPtr->m_fRate*32);
    ui->btn_expandPaper->setIconSize(QSize(g_appInfoPtr->m_fRate*14, g_appInfoPtr->m_fRate*14));
    ui->btn_expandPaper->setIcon(QIcon(":/images/icon-expand-paper.png"));
    ui->lw_paperDetail->setGeometry(ui->btn_expandPaper->x(), ui->btn_expandPaper->y() + ui->btn_expandPaper->height() + g_appInfoPtr->m_fRate*19,
                                      nWidth - g_appInfoPtr->m_fRate*30*2, 200);
    ui->lw_paperDetail->setVisible(false);
    return ui->btn_expandPaper->y() + ui->btn_expandPaper->height() + g_appInfoPtr->m_fRate*20;
}

void clopPaperDetail::onFindExamRecordDataEntity(CFindExamRecordDataEntity findExamRecordDataEntity)
{
	if (findExamRecordDataEntity.nCode == 200)
	{
		m_nExamId = findExamRecordDataEntity.nExamId;
		m_sPaperType = findExamRecordDataEntity.sPaperType;
		CHttpRequestPackage hrp;
		hrp.sUri = QString("/api/ecs_oe_admin/client/exam/process/getExamRecordQuestions");
        hrp.sParamList.push_back(QString("examRecordDataId,%1").arg(m_nExamRecordDataId));
        if(m_bFromCache)
        {
            hrp.sParamList.push_back(QString("fromCache,%1").arg(true));
        }
		hrp.nRequestType = RequestType::rtGetExamRecordQuestions;
		hrp.eParamType = HttpParamType::hptUrl;
		g_httpBllPtr->post(hrp);
	}
	else
	{
        if(findExamRecordDataEntity.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取考试记录失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(findExamRecordDataEntity.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clopPaperDetail::onGetExamRecordQuestions(CGetExamRecordQuestions getExamRecordQuestions)
{
	if (getExamRecordQuestions.nCode == 200)
	{	
		int nSize = getExamRecordQuestions.vExamRecordQuestions.size();
		for (int i = 0; i < nSize; ++i)
		{
			CAnsweredQuestion aq = getExamRecordQuestions.vExamRecordQuestions[i];
			setStudentAnswer(aq.nOrder, aq.sStudentAnswer);
			CHttpRequestPackage hrp;
			hrp.sUri = QString("/api/branch_ecs_ques/default_question/question/for/client");
			hrp.sParamList.push_back(QString("questionId,%1").arg(aq.sQuestionId));
			hrp.sParamList.push_back(QString("examId,%1").arg(m_nExamId));
			hrp.sParamList.push_back(QString("courseCode,%1").arg(m_sCourseCode));
			hrp.sParamList.push_back(QString("groupCode,%1").arg(m_sPaperType));
			hrp.nRequestType = RequestType::rtGetQuestion;
			hrp.eParamType = HttpParamType::hptBody;
			g_httpBllPtr->post(hrp);
		}
	}
	else
	{
        if(getExamRecordQuestions.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取题目信息失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getExamRecordQuestions.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clopPaperDetail::setStudentAnswer(int nOrder, QString sStudentAnswer)
{
	for (CPaperGroupStruct &pgs : m_vPaperGroupStruct)
	{
		for (CQuestionStruct &qs : pgs.vQuestionStruct)
		{
			for (CSubQuestionStruct &sqs : qs.vSubQuestionStruct)
			{
				if (sqs.nOrder == nOrder)
				{
					sqs.sStudentAnswer = sStudentAnswer;
					break;
				}
			}
		}
	}
}

void clopPaperDetail::onGetExamRecordPaperStruct(CGetExamRecordPaperStruct getExamRecordPaperStruct)
{
	if (getExamRecordPaperStruct.nCode == 200)
	{
		m_vPaperGroupStruct.swap(getExamRecordPaperStruct.vPaperGroupStruct);		
	}
	else
	{
        if(getExamRecordPaperStruct.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取试卷结构失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getExamRecordPaperStruct.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clopPaperDetail::onGetQuestion(CGetQuestion getQuestion)
{
	if (getQuestion.nCode == 200)
	{
		for (CPaperGroupStruct &pgs : m_vPaperGroupStruct)
		{
			for (CQuestionStruct &qs : pgs.vQuestionStruct)
			{
				if (qs.sQuestionId == getQuestion.sId)
				{
					qs.bHasContent = true;
					qs.sBody = getQuestion.sBody;
					qs.sVersion = getQuestion.sVersion;
					qs.bhasAudios = getQuestion.bhasAudios;
					for (int i = 0; i < getQuestion.vSubQuestion.size(); ++i)
					{
						CSubQuestion sq = getQuestion.vSubQuestion[i];
						qs.vSubQuestionStruct[i].sBody = sq.sBody;
						qs.vSubQuestionStruct[i].vRightAnswer.swap(sq.vRightAnswer);
						qs.vSubQuestionStruct[i].vOptions.swap(sq.vOptions);
					}															
					break;
				}
			}
		}			
	}
	else
	{
        if(getQuestion.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取试题失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getQuestion.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clopPaperDetail::on_btn_expandPaper_clicked()
{
	bool bShow = true;
	for(CPaperGroupStruct &pgs : m_vPaperGroupStruct)
	{
		for (CQuestionStruct &qs : pgs.vQuestionStruct)
		{
			if (!qs.bHasContent)
			{
				CHttpRequestPackage hrp;
				hrp.sUri = QString("/api/branch_ecs_ques/default_question/question/for/client");
				hrp.sParamList.push_back(QString("questionId,%1").arg(qs.sQuestionId));
				hrp.sParamList.push_back(QString("examId,%1").arg(m_nExamId));
				hrp.sParamList.push_back(QString("courseCode,%1").arg(m_sCourseCode));
				hrp.sParamList.push_back(QString("groupCode,%1").arg(m_sPaperType));
				hrp.nRequestType = RequestType::rtGetQuestion;
				hrp.eParamType = HttpParamType::hptBody;
				g_httpBllPtr->post(hrp);
				bShow = false;
			}
		}
	}

	if (bShow)
	{
		int nIndex = 1;
		Json::Value jBody = Json::Value::null;
		for (int i = 0; i < m_vPaperGroupStruct.size(); ++i)
		{
			CPaperGroupStruct pgs = m_vPaperGroupStruct[i];
			QString sGroupBody = QString::fromLocal8Bit(R"({"sections":[{"blocks":[{"type":"text","value":"%1、%2"}]}]})")
				.arg(CCommonTools::Arab2Sinogram(pgs.nNumber)).arg(pgs.sGroupName);
			Json::Value blockItem = Json::Value::null;
			blockItem["type"] = "text";
			blockItem["value"] = (QString::fromLocal8Bit("%1、%2").arg(CCommonTools::Arab2Sinogram(pgs.nNumber)).arg(pgs.sGroupName)).toStdString();
			Json::Value block = Json::Value::null;
			block["blocks"].append(blockItem);
			jBody["sections"].append(block);
			for (CQuestionStruct &qs : pgs.vQuestionStruct)
			{
				if (!qs.sBody.isEmpty())
				{
					Json::Reader reader;
					Json::Value jQuestion = Json::Value::null;
					if (!reader.parse(qs.sBody.toStdString(), jQuestion))
					{
						//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
						myDebug() << QString::fromLocal8Bit("解析题干出错！");
					}
					for (int iq = 0; iq <  jQuestion["sections"].size(); ++iq)
					{
						jBody["sections"].append(jQuestion["sections"][iq]);
					}
					
				}

				for (CSubQuestionStruct &sqs : qs.vSubQuestionStruct)
				{
					if (!sqs.sBody.isEmpty())
					{
						Json::Reader reader;
						Json::Value jSubQuestion = Json::Value::null;
						if (!reader.parse(sqs.sBody.toStdString(), jSubQuestion))
						{
							//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
							myDebug() << QString::fromLocal8Bit("解析题干出错！");
						}
						if (jSubQuestion["sections"][0]["blocks"][0]["type"] == "text")
						{
							QString sValue = jSubQuestion["sections"][0]["blocks"][0]["value"].asString().c_str();
							jSubQuestion["sections"][0]["blocks"][0]["value"] = (QString::fromLocal8Bit("%1、%2").arg(nIndex).arg(sValue)).toStdString();
						}
						else
						{
							Json::Value blockItem = Json::Value::null;
							blockItem["type"] = "text";
							blockItem["value"] = QString::fromLocal8Bit("% 1、").arg(nIndex).toStdString();
							Json::Value block = Json::Value::null;
							block["blocks"].append(blockItem);
							jBody["sections"].append(block);
						}
						for (int isq = 0; isq < jSubQuestion["sections"].size(); ++isq)
						{
							jBody["sections"].append(jSubQuestion["sections"][isq]);
						}
					}
					else
					{
						Json::Value blockItem = Json::Value::null;
						blockItem["type"] = "text";
						blockItem["value"] = QString::fromLocal8Bit("% 1、").arg(nIndex).toStdString();
						Json::Value block = Json::Value::null;
						block["blocks"].append(blockItem);
						jBody["sections"].append(block);
					}
					nIndex++;
					for (int io = 0; io < sqs.vOptions.size(); ++io)
					{
						QString sOption = sqs.vOptions[io].sBody;
						Json::Reader reader;
						Json::Value jOption = Json::Value::null;
						if (!reader.parse(sOption.toStdString(), jOption))
						{
							//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
							myDebug() << QString::fromLocal8Bit("解析题干出错！");
						}

						if (jOption["sections"][0]["blocks"][0]["type"] == "text")
						{
							QString sValue = jOption["sections"][0]["blocks"][0]["value"].asString().c_str();
							jOption["sections"][0]["blocks"][0]["value"] = (QString::fromLocal8Bit("%1、%2").arg(QChar('A' + io)).arg(sValue)).toStdString();
						}
						else
						{
							Json::Value blockItem = Json::Value::null;
							blockItem["type"] = "text";
							blockItem["value"] = QString::fromLocal8Bit("% 1、").arg(nIndex).toStdString();
							Json::Value block = Json::Value::null;
							block["blocks"].append(blockItem);
							jBody["sections"].append(block);
						}

						for (int iop = 0; iop < jOption["sections"].size(); ++iop)
						{
							jBody["sections"].append(jOption["sections"][iop]);
						}
					}



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

                            for(int nrai = 0; nrai < jRightAnswer["sections"].size(); ++nrai)
                            {
                               Json::Value jBlocks =  jRightAnswer["sections"][nrai];
                               for(int nb = 0; nb < jBlocks["blocks"].size();  nb++)
                               {
                                    if(jBlocks["blocks"][nb]["type"] == "text")
                                    {
                                        if(sqs.sQuestionType != QUESTION_TYPE::TrueOrFalse)
                                        {
                                            sRightAnswer += 'A' + QString(jBlocks["blocks"][nb]["value"].asString().c_str()).toInt();
                                        }
                                        else
                                        {
											QString sAns = jBlocks["blocks"][nb]["value"].asString().c_str();
                                            sRightAnswer += jBlocks["blocks"][nb]["value"].asString() == "true" ? QString::fromLocal8Bit("正确") : QString::fromLocal8Bit("错误");
                                        }
                                    }
                               }                                
                            }

						}
						else if (sqs.sQuestionType == QUESTION_TYPE::FillUp ||
							sqs.sQuestionType == QUESTION_TYPE::Essay)
						{
                            sRightAnswer = sqs.vRightAnswer[ira];
                            Json::Reader reader;
                            Json::Value jRightAnswer = Json::Value::null;
                            if (!reader.parse(sRightAnswer.toStdString(), jRightAnswer))
                            {
                                //            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
                                myDebug() << QString::fromLocal8Bit("解析题干出错！");
                            }
                            if(ira == 0)
                            {
                                Json::Value blockItemAns = Json::Value::null;
                                blockItemAns["type"] = "text";
                                blockItemAns["value"] = QString::fromLocal8Bit("正确答案：").toStdString();
                                Json::Value blockAns = Json::Value::null;
                                blockAns["blocks"].append(blockItemAns);
                                jBody["sections"].append(blockAns);
                            }
                            for(int nrai = 0; nrai < jRightAnswer["sections"].size(); ++nrai)
                            {
                                jBody["sections"].append(jRightAnswer["sections"][nrai]);
                            }
						}
					}

                    if(sqs.sQuestionType == QUESTION_TYPE::SingleChoice ||
                        sqs.sQuestionType == QUESTION_TYPE::MultipleChoice ||
                        sqs.sQuestionType == QUESTION_TYPE::TrueOrFalse)
                    {
                        Json::Value blockItemAns = Json::Value::null;
                        blockItemAns["type"] = "text";
                        blockItemAns["value"] = (QString::fromLocal8Bit("正确答案：%1").arg(sRightAnswer)).toStdString();
                        Json::Value blockAns = Json::Value::null;
                        blockAns["blocks"].append(blockItemAns);
                        jBody["sections"].append(blockAns);
                    }



                    QString sStudentAnswer = "";

                    if (sqs.sQuestionType == QUESTION_TYPE::SingleChoice ||
                        sqs.sQuestionType == QUESTION_TYPE::MultipleChoice ||
                        sqs.sQuestionType == QUESTION_TYPE::TrueOrFalse)
                    {                        
						if (sqs.sQuestionType != QUESTION_TYPE::TrueOrFalse)
						{
							for (int isal = 0; isal < sqs.sStudentAnswer.length(); ++isal)
							{
								sStudentAnswer += 'A' + QString(sqs.sStudentAnswer[isal]).toInt();
							}
						}
						else
						{
							QString  sAns = sqs.sStudentAnswer;
                            sStudentAnswer = sqs.sStudentAnswer == "true" ? QString::fromLocal8Bit("正确") : sqs.sStudentAnswer == "false" ? QString::fromLocal8Bit("错误") : "";
						}                                                    
                    }
                    else if (sqs.sQuestionType == QUESTION_TYPE::FillUp ||
                        sqs.sQuestionType == QUESTION_TYPE::Essay)
                    {
                        sStudentAnswer += sqs.sStudentAnswer;
                    }

                    Json::Value blockItemStuAns = Json::Value::null;
                    blockItemStuAns["type"] = "text";
                    blockItemStuAns["value"] = (QString::fromLocal8Bit("考生答案：%1").arg(sStudentAnswer)).toStdString();
                    Json::Value blockStuAns = Json::Value::null;
                    blockStuAns["blocks"].append(blockItemStuAns);
                    jBody["sections"].append(blockStuAns);

					Json::Value blockItem = Json::Value::null;
					blockItem["type"] = "text";
					blockItem["value"] = "";
					Json::Value block = Json::Value::null;
					block["blocks"].append(blockItem);
					jBody["sections"].append(block);
				}
			}
		}

        initQuestion(jBody);
	}
}

void clopPaperDetail::initQuestion(Json::Value jBody)
{
	int nListHeight = 0;
	int nIndex = 1;
	int nSectionSize = jBody["sections"].size();
	Json::Value jSections = Json::Value::null;
	for (int i = 0; i < nSectionSize; i++)
	{
		Json::Value jblocks = Json::Value::null;
		int nBlockSize = jBody["sections"][i]["blocks"].size();
		for (int j = 0; j < nBlockSize; j++)
		{
			if (jBody["sections"][i]["blocks"][j]["type"].asString() == "audio")
			{
				if (jblocks != Json::Value::null ||
					jSections != Json::Value::null)
				{
					if (jblocks != Json::Value::null)
					{
						Json::Value jBlockItem = Json::Value::null;
						jBlockItem["blocks"] = jblocks;
						jblocks = Json::Value::null;
						jSections.append(jBlockItem);
					}
					Json::Value jQuestionBody = Json::Value::null;
					jQuestionBody["sections"] = jSections;
					jSections = Json::Value::null;
					jblocks = Json::Value::null;
					questionBody *wQB = new questionBody(jQuestionBody);
					QListWidgetItem *listItem = new QListWidgetItem;
					int nQBHeight = wQB->setUI(ui->lw_paperDetail->width() - 40, nIndex);
					listItem->setSizeHint(QSize(ui->lw_paperDetail->width() - 40, nQBHeight));
					ui->lw_paperDetail->addItem(listItem);
					ui->lw_paperDetail->setItemWidget(listItem, wQB);
					nListHeight += nQBHeight;
				}

				nIndex++;
				QString sAudioName = jBody["sections"][i]["blocks"][j]["ext2"].asString().c_str();
				QString sAudioUrl = jBody["sections"][i]["blocks"][j]["value"].asString().c_str();
				audioPlay *wAP = new audioPlay(sAudioName, sAudioUrl, 10);

				QListWidgetItem *listItem = new QListWidgetItem;
				int nAPHeight = wAP->setUI(ui->lw_paperDetail->width() - 40);
				listItem->setSizeHint(QSize(ui->lw_paperDetail->width() - 40, nAPHeight));
				ui->lw_paperDetail->addItem(listItem);
				ui->lw_paperDetail->setItemWidget(listItem, wAP);
				nListHeight += nAPHeight;
			}
			else
			{
				jblocks.append(jBody["sections"][i]["blocks"][j]);
			}
		}
		if (jblocks != Json::Value::null)
		{
			Json::Value jBlockItem = Json::Value::null;
			jBlockItem["blocks"] = jblocks;
			jblocks = Json::Value::null;
			jSections.append(jBlockItem);
		}
	}

	if (jSections != Json::Value::null)
	{
		Json::Value jQuestionBody = Json::Value::null;
		jQuestionBody["sections"] = jSections;
		jSections = Json::Value::null;
		questionBody *wQB = new questionBody(jQuestionBody);
		QListWidgetItem *listItem = new QListWidgetItem;
		int nQBHeight = wQB->setUI(ui->lw_paperDetail->width() - 40, nIndex);
		listItem->setSizeHint(QSize(ui->lw_paperDetail->width() - 40, nQBHeight));
		ui->lw_paperDetail->addItem(listItem);
		ui->lw_paperDetail->setItemWidget(listItem, wQB);
		nListHeight += nQBHeight;
	}
	
	ui->lw_paperDetail->setGeometry(ui->btn_expandPaper->x(), ui->btn_expandPaper->y() + ui->btn_expandPaper->height() + g_appInfoPtr->m_fRate * 19,
		width() - g_appInfoPtr->m_fRate * 30 * 2, nListHeight);
	ui->lw_paperDetail->setVisible(true);
	
	emit heightChange(ui->lw_paperDetail->y() + ui->lw_paperDetail->height() + g_appInfoPtr->m_fRate * 20);
}
