#include "questionSet.h"
#include "ui_questionSet.h"

#include <QFile>
#include <QScrollBar>

#include "choiceQuesiton.h"
#include "fillBlank.h"
#include "questionAndAnswer.h"
#include "questionBody.h"
#include "audioPlay.h"
#include "standardAnswer.h"
#include "CAppInfo.h"
#include "logproc.h"

questionSet::questionSet(CQuestionStruct &qs, int nOrder, int nTotalSubQuestion,  QWidget *parent) :
    QWidget(parent),
    ui(new Ui::questionSet), m_qs(qs), m_nOrder(nOrder), m_nTotalSubQuestion(nTotalSubQuestion)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose);

    m_pWidgetChangeQuestion = nullptr;

    setStyleSheet(g_appInfoPtr->m_sQssStr);

    ui->list_question->setVerticalScrollMode(QListWidget::ScrollPerPixel);
    ui->list_question->verticalScrollBar()->setSingleStep(g_appInfoPtr->m_fRate * 5);
    ui->list_body->setVerticalScrollMode(QListWidget::ScrollPerPixel);
    ui->list_body->verticalScrollBar()->setSingleStep(g_appInfoPtr->m_fRate * 5);
}

questionSet::~questionSet()
{
    if(m_pWidgetChangeQuestion != nullptr)
    {
        delete m_pWidgetChangeQuestion;
        m_pWidgetChangeQuestion = nullptr;
    }
    delete ui;
}

void questionSet::setUI(const int nLeft, const int nTop, const int nWidth, const int nHeight)
{
    setGeometry(nLeft, nTop, nWidth, nHeight);

    ui->label_bigQuesionName->adjustSize();
    ui->label_bigQuesionName->setGeometry(g_appInfoPtr->m_fRate*40, 0, ui->label_bigQuesionName->width(), ui->label_bigQuesionName->height());
    ui->label_groupProgress->adjustSize();
    ui->label_groupProgress->setGeometry(width() - g_appInfoPtr->m_fRate*40*2 - ui->label_groupProgress->width(),
                                         ui->label_bigQuesionName->y() + ui->label_bigQuesionName->height() - ui->label_groupProgress->height(),
                                         ui->label_groupProgress->width(), ui->label_groupProgress->height());
    int nNameWidth = ui->label_groupProgress->x() - ui->label_bigQuesionName->x() - g_appInfoPtr->m_fRate*20;
    int nRowCount = (ui->label_bigQuesionName->width() + nNameWidth - 1)/nNameWidth;
    if(nRowCount > 1)
    {
         ui->label_bigQuesionName->setWordWrap(true);
         ui->label_bigQuesionName->setGeometry(g_appInfoPtr->m_fRate*40, 0,
                                               nNameWidth, nRowCount*ui->label_bigQuesionName->height());
    }
    ui->line_question->setGeometry(g_appInfoPtr->m_fRate*40, ui->label_bigQuesionName->y() + ui->label_bigQuesionName->height() + g_appInfoPtr->m_fRate*20, width() - g_appInfoPtr->m_fRate*40*2, g_appInfoPtr->m_fRate*2);
//    ui->list_question->setGeometry(0, ui->label_bigQuesionName->y() + ui->label_bigQuesionName->height() + 40,
//                                         width() - 6, 280);
    ui->splitter->setGeometry(g_appInfoPtr->m_fRate*40, ui->label_bigQuesionName->y() + ui->label_bigQuesionName->height() + g_appInfoPtr->m_fRate*40,
                            width() - g_appInfoPtr->m_fRate*40 - g_appInfoPtr->m_fRate*6, nHeight - ui->label_bigQuesionName->y() - ui->label_bigQuesionName->height() - g_appInfoPtr->m_fRate*40 - g_appInfoPtr->m_fRate*52);
//    ui->splitter->setStretchFactor(0, 1);
//    ui->splitter->setStretchFactor(1, 2);

    ui->list_body->setGeometry(0, 0, ui->splitter->width(), ui->splitter->height()/3);
    ui->list_question->setGeometry(0, ui->splitter->height()/3, ui->splitter->width(), 2*ui->splitter->height()/3);
    

    initBody();

	for (int i = 0; i < m_qs.vSubQuestionStruct.size(); ++i)
	{
        if (m_qs.vSubQuestionStruct[i].nOrder == m_nOrder)
		{
			initSubQuestionItem(m_qs.vSubQuestionStruct[i]);
		}
	}
           

    if(m_pWidgetChangeQuestion == nullptr)
    {
        m_pWidgetChangeQuestion = new changeQuestion(this);
        m_pWidgetChangeQuestion->setUI(0, ui->splitter->y() + ui->splitter->height(), width(), g_appInfoPtr->m_fRate*52);
    }
    m_pWidgetChangeQuestion->show();
    connect(m_pWidgetChangeQuestion, &changeQuestion::previousQuestion, this, &questionSet::onPreviousQuestion);
    connect(m_pWidgetChangeQuestion, &changeQuestion::nextQuestion, this, &questionSet::onNextQuestion);

    m_pWidgetChangeQuestion->showBtn(3);
    if(m_nOrder == 1)
    {
        m_pWidgetChangeQuestion->showBtn(1);
    }
    else if(m_nOrder == m_nTotalSubQuestion)
    {
        m_pWidgetChangeQuestion->showBtn(2);
    }
}

void questionSet::questionSet::showBtn(int nType)
{
    m_pWidgetChangeQuestion->showBtn(nType);
}

void questionSet::onPreviousQuestion()
{
    emit previousQuestion(m_nOrder);
}

void questionSet::onNextQuestion()
{
    emit nextQuestion(m_nOrder);
}


void questionSet::initBody()
{       
    Json::Reader reader;
    Json::Value jBody = Json::Value::null;
    if(!reader.parse(m_qs.sBody.toStdString(), jBody))
    {
//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
        myDebug()<<QString::fromLocal8Bit("解析题干出错！");
    }


    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->list_body->width() - 40, nIndex);
                    listItem->setSizeHint(QSize(ui->list_body->width() - 40, nQBHeight));
                    ui->list_body->addItem(listItem);
                    ui->list_body->setItemWidget(listItem, wQB);
                }

                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, m_qs.nLimitedPlayTimes);
                connect(wAP, &audioPlay::playedCountChange, this, [&](){
                    for(int i = 0; i < ui->list_question->count(); i++)
                    {
                        CQuestionBaseWidget *item = dynamic_cast<CQuestionBaseWidget*>(ui->list_question->itemWidget(ui->list_question->item(i)));
                        if(item && item->widgetType() == wt_question)
                        {
                            item->audioPlayCountChange();
                        }
                    }
                });


                QListWidgetItem *listItem = new QListWidgetItem;
                int nAPHeight = wAP->setUI(ui->list_body->width() - 40);
                listItem->setSizeHint(QSize(ui->list_body->width() - 40, nAPHeight));
                ui->list_body->addItem(listItem);
                ui->list_body->setItemWidget(listItem, wAP);
            }
            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->list_body->width() - 40, nIndex);
        listItem->setSizeHint(QSize(ui->list_body->width() - 40, nQBHeight));
        ui->list_body->addItem(listItem);
        ui->list_body->setItemWidget(listItem, wQB);
    }
}

void questionSet::initSubQuestionItem(CSubQuestionStruct &subQuestionItem)
{
    if(subQuestionItem.sQuestionType == QUESTION_TYPE::SingleChoice ||
            subQuestionItem.sQuestionType == QUESTION_TYPE::MultipleChoice ||
            subQuestionItem.sQuestionType == QUESTION_TYPE::TrueOrFalse)
    {

            choiceQuesiton *wCQ = new choiceQuesiton(subQuestionItem);
            connect(wCQ, &choiceQuesiton::markedItem, this, &questionSet::onMarkedItem);
            connect(wCQ, &choiceQuesiton::questionAnswered, this, &questionSet::onQuestionAnswered);
            connect(wCQ, &choiceQuesiton::uploadAnswer, this, &questionSet::onUploadAnswer);
            int nHeight = wCQ->setUI(ui->list_question->width());
            QListWidgetItem *listItem = new QListWidgetItem;
            listItem->setSizeHint(QSize(ui->list_question->width(), nHeight));
            ui->list_question->addItem(listItem);
            ui->list_question->setItemWidget(listItem, wCQ);
        }
    else if(subQuestionItem.sQuestionType == QUESTION_TYPE::FillUp)
    {
        fillBlank *wFB = new fillBlank(subQuestionItem);
        connect(wFB, &fillBlank::markedItem, this, &questionSet::onMarkedItem);
        connect(wFB, &fillBlank::questionAnswered, this, &questionSet::onQuestionAnswered);
        connect(wFB, &fillBlank::uploadAnswer, this, &questionSet::onUploadAnswer);
        int nHeight = wFB->setUI(ui->list_question->width());
        QListWidgetItem *listItem = new QListWidgetItem;
        listItem->setSizeHint(QSize(ui->list_question->width(), nHeight));
        ui->list_question->addItem(listItem);
        ui->list_question->setItemWidget(listItem, wFB);
    }
    else if(subQuestionItem.sQuestionType == QUESTION_TYPE::Essay)
    {
        questionAndAnswer *wQAA = new questionAndAnswer(subQuestionItem);
        connect(wQAA, &questionAndAnswer::markedItem, this, &questionSet::onMarkedItem);
        connect(wQAA, &questionAndAnswer::questionAnswered, this, &questionSet::onQuestionAnswered);
        connect(wQAA, &questionAndAnswer::uploadAnswer, this, &questionSet::onUploadAnswer);

        int nHeight = wQAA->setUI(ui->list_question->width());
        QListWidgetItem *listItem = new QListWidgetItem;
        listItem->setSizeHint(QSize(ui->list_question->width(), nHeight));
        ui->list_question->addItem(listItem);
        ui->list_question->setItemWidget(listItem, wQAA);
    }

    if(g_appInfoPtr->m_oExamInfo.sExamType == "PRACTICE" && g_appInfoPtr->m_oExamInfo.sPracticeType == "IN_PRACTICE")
    {
        standardAnswer *wSA = new standardAnswer(subQuestionItem);
        connect(wSA, &standardAnswer::heightChange, this, [&](int nH){
            for(int i = 0; i < ui->list_question->count(); i++)
            {
                CQuestionBaseWidget *item = dynamic_cast<CQuestionBaseWidget*>(ui->list_question->itemWidget(ui->list_question->item(i)));
                if(item && item->widgetType() == wt_standardAnswer)
                {
                     QListWidgetItem *pItem = ui->list_question->item(i);
                     pItem->setSizeHint(QSize(ui->list_question->width() - 8, nH));
                }
            }
        });

        int nHeight = wSA->setUI(ui->list_question->width() - 8);

        QListWidgetItem *listItem = new QListWidgetItem;
        listItem->setSizeHint(QSize(ui->list_question->width() - 8, nHeight));
        ui->list_question->addItem(listItem);
        ui->list_question->setItemWidget(listItem, wSA);
    }
}

void questionSet::setGroupInfo(QString sTitle, QString sProgress)
{
    if(!sTitle.isEmpty())
    {
        ui->label_bigQuesionName->setText(sTitle);
    }
    ui->label_groupProgress->setText(sProgress);
}


void questionSet::onMarkedItem(bool bMarked, int nOrder)
{
    emit markedItem(bMarked, nOrder);
}

void questionSet::onQuestionAnswered(bool bAnswered, int nOrder)
{
    emit questionAnswered(bAnswered, nOrder);
}

void questionSet::onUploadAnswer(int nOrder, __int64 timeStamp, QString sAnswer)
{
    emit uploadAnswer(nOrder, timeStamp, sAnswer);
}

void questionSet::handinPaper()
{
    for(int i = 0; i < ui->list_question->count(); i++)
    {
        CQuestionBaseWidget *item = dynamic_cast<CQuestionBaseWidget*>(ui->list_question->itemWidget(ui->list_question->item(i)));
        if(item && item->widgetType() == wt_question)
        {
            item->handinPaper();
        }
    }
}
