#include "questionAndAnswer.h"
#include "ui_questionAndAnswer.h"

#include <QFile>
#include "fbFillBlankBody.h"
#include "audioPlay.h"
#include "qaaBlank.h"
#include "CCommonTools.h"
#include "CSqlite3DBProc.h"
//#include "MsgDlg.h"
#include "CAppInfo.h"
#include "addPic.h"
#include "wxAnswer.h"
#include "logproc.h"

questionAndAnswer::questionAndAnswer(CSubQuestionStruct &sqs, QWidget *parent) :
    CQuestionBaseWidget(parent),
    ui(new Ui::questionAndAnswer), m_sqs(sqs)
{
    ui->setupUi(this);

    setAttribute(Qt::WA_DeleteOnClose);

    b_isPressed = false;
    m_bAnswerChange = false;
    m_sAnswer = "";
    m_nTimeStap = 0;


    setStyleSheet(g_appInfoPtr->m_sQssStr);

    m_pTimer = new QTimer;
    m_pTimer->setInterval(5*1000);
    connect(m_pTimer, &QTimer::timeout, this, &questionAndAnswer::onTimeout);
    m_pTimer->start();

    this->installEventFilter(this);
}

questionAndAnswer::~questionAndAnswer()
{
    if(m_bAnswerChange)
    {
        updateAnswer();
        m_bAnswerChange = false;
    }

    m_pTimer->stop();
    RELEASE_PTR(m_pTimer);

    delete ui;
}

int questionAndAnswer::setUI(const int nWidth)
{
    setGeometry(0, 0, nWidth, g_appInfoPtr->m_fRate*300);
    ui->btn_mark->setGeometry(0, g_appInfoPtr->m_fRate*24, g_appInfoPtr->m_fRate*20, g_appInfoPtr->m_fRate*20);
    ui->list_choiceQuestion->setGeometry(ui->btn_mark->x() + ui->btn_mark->width() + g_appInfoPtr->m_fRate*20,
                                         g_appInfoPtr->m_fRate*20, width() - g_appInfoPtr->m_fRate*80, g_appInfoPtr->m_fRate*280);
    QString sAnswerStr = m_sqs.sStudentAnswer;
    m_nListHeight = 0;
    Json::Reader reader;
    Json::Value jBody = Json::Value::null;
    if(!reader.parse(m_sqs.sBody.toStdString(), jBody))
    {
//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
        myDebug()<<QString::fromLocal8Bit("解析题干出错！");
    }
    initBody(jBody, m_sqs.nShowNumber);



    if(g_appInfoPtr->m_bWeiXinAnswerEnabled)
    {
        if(m_sqs.sAnswerType == "SINGLE_AUDIO")
        {
			Json::Value jAnswer = Json::Value::null;
			if (!sAnswerStr.isEmpty())
			{				
				if (!reader.parse(sAnswerStr.toStdString(), jAnswer))
				{
					//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
					myDebug() << QString::fromLocal8Bit("解析答案出错！");
				}
			}
			QStringList sFileList;
			int nSize = jAnswer["sections"].size();
			for (int i = 0; i < nSize; i++)
			{
				Json::Value blocks = jAnswer["sections"][i];
				for (int j = 0; j < (int)blocks["blocks"].size(); j++)
				{
					if (blocks["blocks"][j]["type"].asString() == "text")
					{
						sFileList << blocks["blocks"][j]["value"].asString().c_str();
					}
				}
			}
			
            wxAnswer *widget = new wxAnswer(m_sqs.sAnswerType, m_sqs.nOrder);
            connect(widget, &wxAnswer::audioAnswered, this, [&](QString sFileUrl){
                onAnswerChanged(true);
            });
            QListWidgetItem *listItem = new QListWidgetItem;
            int nQAABHeight = widget->setUI(ui->list_choiceQuestion->width());
            m_nListHeight += nQAABHeight;
            listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQAABHeight));
            widget->setAnswer(sFileList.join(","));
            ui->list_choiceQuestion->addItem(listItem);
            ui->list_choiceQuestion->setItemWidget(listItem, widget);
        }
        else
        {            
			Json::Value jAnswer = Json::Value::null;
			if (!sAnswerStr.isEmpty())
			{				
				if (!reader.parse(sAnswerStr.toStdString(), jAnswer))
				{
					//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
					myDebug() << QString::fromLocal8Bit("解析答案出错！");
				}
			}
			QStringList sFileList;
			Json::Value jTextAnswer = Json::Value::null;
			int nSize = jAnswer["sections"].size();
			for (int i = 0; i < nSize; i++)
			{
				Json::Value jTextblocks = Json::Value::null;
				Json::Value blocks = jAnswer["sections"][i];
				for (int j = 0; j < (int)blocks["blocks"].size(); j++)
				{
					if (blocks["blocks"][j]["type"].asString() == "text")
					{
						jTextblocks["blocks"].append(blocks["blocks"][j]);

					}
					else if (blocks["blocks"][j]["type"].asString() == "image")
					{
						sFileList << blocks["blocks"][j]["value"].asString().c_str();
					}
				}
				if(jTextblocks != Json::Value::null)
				{ 
					jTextAnswer["sections"].append(jTextblocks);
				}
				
			}
			
			qaaBlank *wQAAB = new qaaBlank;
            qDebug()<<jTextAnswer.toStyledString().c_str();
            wQAAB->setAnswer(jTextAnswer.toStyledString().c_str());
			connect(wQAAB, &qaaBlank::answerChanged, this, &questionAndAnswer::onAnswerChanged);
			QListWidgetItem *listItem = new QListWidgetItem;
			int nQAABHeight = wQAAB->setUI(ui->list_choiceQuestion->width());
			m_nListHeight += nQAABHeight;
			listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQAABHeight));
			ui->list_choiceQuestion->addItem(listItem);
			ui->list_choiceQuestion->setItemWidget(listItem, wQAAB);
			{
				addPic *widget = new addPic(m_sqs.nOrder);
                connect(widget, &addPic::answerChanged, this, &questionAndAnswer::onAnswerChanged);
				QListWidgetItem *listItem = new QListWidgetItem;
				int nQAABHeight = widget->setUI(ui->list_choiceQuestion->width());
				m_nListHeight += nQAABHeight;
				listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQAABHeight));
                widget->setAnswer(sFileList.join(","));
				ui->list_choiceQuestion->addItem(listItem);
				ui->list_choiceQuestion->setItemWidget(listItem, widget);
			}
        }
    }
    else
    {
        qaaBlank *wQAAB = new qaaBlank;
        wQAAB->setAnswer(sAnswerStr);
        connect(wQAAB, &qaaBlank::answerChanged, this, &questionAndAnswer::onAnswerChanged);
        QListWidgetItem *listItem = new QListWidgetItem;
        int nQAABHeight = wQAAB->setUI(ui->list_choiceQuestion->width());
        m_nListHeight += nQAABHeight;
        listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQAABHeight));
        ui->list_choiceQuestion->addItem(listItem);
        ui->list_choiceQuestion->setItemWidget(listItem, wQAAB);
    }


    ui->list_choiceQuestion->setGeometry(ui->btn_mark->x() + ui->btn_mark->width() + g_appInfoPtr->m_fRate*20,
                                         g_appInfoPtr->m_fRate*20, width() - g_appInfoPtr->m_fRate*80, m_nListHeight + g_appInfoPtr->m_fRate*10);
    setGeometry(0, 0, nWidth, ui->list_choiceQuestion->y() + m_nListHeight + g_appInfoPtr->m_fRate*30);

    setMarkStyle();
    return height();
}

void questionAndAnswer::setMarkStyle()
{
    QString sMaredStyle = QString(R"(QPushButton#btn_mark
        {
            outline:none;
            border-image:url(:/images/btn-mark-hover.png);
        })");

    QString sUnmaredStyle = QString(R"(QPushButton#btn_mark
        {
            outline:none;
            border-image:url(:/images/btn-mark.png);
        })");
    if(m_sqs.bMarked)
    {
        ui->btn_mark->setStyleSheet(sMaredStyle);
    }
    else
    {
        ui->btn_mark->setStyleSheet(sUnmaredStyle);
    }
}


void questionAndAnswer::initBody(Json::Value jBody, int nOrderIndex)
{
    int nIndex = 1;
    bool isSetItemNo = false;
    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;
                    fbFillBlankBody *wQB = new fbFillBlankBody(jQuestionBody);
                    if(!isSetItemNo)
                    {
                        wQB->setQuesionNo(QString::fromLocal8Bit("%1．").arg(QString::number(nOrderIndex)));
                        isSetItemNo = true;
                    }
                    QListWidgetItem *listItem = new QListWidgetItem;
                    int nQBHeight = wQB->setUI(ui->list_choiceQuestion->width());
                    m_nListHeight += nQBHeight;
                    listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQBHeight));
                    ui->list_choiceQuestion->addItem(listItem);
                    ui->list_choiceQuestion->setItemWidget(listItem, wQB);
                    wQB = nullptr;
                }

                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_sqs.nLimitedPlayTimes);
                connect(wAP, &audioPlay::playedCountChange, this, [&](){audioPlayCountChange();});

                QListWidgetItem *listItem = new QListWidgetItem;
                int nAPHeight = wAP->setUI(ui->list_choiceQuestion->width());
                m_nListHeight += nAPHeight;
                listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nAPHeight));
                ui->list_choiceQuestion->addItem(listItem);
                ui->list_choiceQuestion->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;
        fbFillBlankBody *wQB = new fbFillBlankBody(jQuestionBody);
        if(!isSetItemNo)
        {
            wQB->setQuesionNo(QString::fromLocal8Bit("%1．").arg(QString::number(nOrderIndex)));
            isSetItemNo = true;
        }
        QListWidgetItem *listItem = new QListWidgetItem;
        int nQBHeight = wQB->setUI(ui->list_choiceQuestion->width());
        m_nListHeight += nQBHeight;
        listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQBHeight));
        ui->list_choiceQuestion->addItem(listItem);
        ui->list_choiceQuestion->setItemWidget(listItem, wQB);
        wQB = nullptr;
    }
}

void questionAndAnswer::on_btn_mark_clicked()
{
    if(!b_isPressed)
    {
        b_isPressed = true;
        ui->btn_mark->setStyleSheet("QPushButton{border-image:url(:/images/icon-marked.png);}");
    }
    else
    {
        b_isPressed = false;
        ui->btn_mark->setStyleSheet("QPushButton{border-image:url(:/images/icon-unmark.png);}");
    }

    m_sqs.bMarked = b_isPressed;
    setMarkStyle();
    emit markedItem(b_isPressed, m_sqs.nOrder);
}

void questionAndAnswer::onAnswerChanged(bool bAnswer)
{
    m_sAnswer = generateAnswer(bAnswer);
    m_bAnswerChange = true;
    m_nTimeStap = g_appInfoPtr->serverMTime();
    m_sqs.bAnswered = bAnswer;
    emit questionAnswered(bAnswer, m_sqs.nOrder);
}

void questionAndAnswer::onTimeout()
{
    if(m_bAnswerChange)
    {
        updateAnswer();
        m_bAnswerChange = false;
    }
}


void questionAndAnswer::updateAnswer()
{      
    Json::Value jAudioPlayedInfo = Json::Value::null;

    for(int i = 0; i < ui->list_choiceQuestion->count(); i++)
    {
        CBaseWidget *baseWidget = dynamic_cast<CBaseWidget*>(ui->list_choiceQuestion->itemWidget(ui->list_choiceQuestion->item(i)));
        if(baseWidget->widgetType() == wt_aduioPlay)
        {
            audioPlay *wAp = dynamic_cast<audioPlay*>(baseWidget);
            QString sAudioName = "";
            int nCount = 0;
            wAp->getPalyedCount(sAudioName, nCount);

            Json::Value jPlayedInfo = Json::Value::null;
            jPlayedInfo["name"] = sAudioName.toStdString();
            jPlayedInfo["times"] = nCount;
            jAudioPlayedInfo.append(jPlayedInfo);
        }
    }

    QString sAudioPalyedInfo = "";
    if(jAudioPlayedInfo != Json::Value::null)
    {
        sAudioPalyedInfo = jAudioPlayedInfo.toStyledString().c_str();
    }


    Json::Value jAnswer = Json::Value::null;
    Json::Value jAnswerItem = Json::Value::null;
    if (!m_sqs.sAnswerType.isEmpty())
    {
        jAnswerItem["answerType"] = m_sqs.sAnswerType.toStdString();
    }
    jAnswerItem["audioPlayTimes"] = sAudioPalyedInfo.toStdString();
    jAnswerItem["isSign"] = m_sqs.bMarked;
    jAnswerItem["order"] = m_sqs.nOrder;
    jAnswerItem["studentAnswer"] = m_sAnswer.toStdString();
    jAnswer.append(jAnswerItem);
    QString sUploadAnswer = jAnswer.toStyledString().c_str();
    qDebug()<<sUploadAnswer;
    m_sqs.nVersion++;
    m_sqs.bUpload = false;
    m_sqs.sUploadAnswer = sUploadAnswer;
    emit uploadAnswer(m_sqs.nOrder, m_nTimeStap, sUploadAnswer);

}

QString questionAndAnswer::generateAnswer(bool &bAnswered)
{
    bAnswered = false;
    Json::Value jAnswer = Json::Value::null;
    QString sAnswerStr = "";
    QString sAnswer = "";

    for(int i = 0; i < ui->list_choiceQuestion->count(); i++)
    {
        CBaseWidget *baseWidget = dynamic_cast<CBaseWidget*>(ui->list_choiceQuestion->itemWidget(ui->list_choiceQuestion->item(i)));
        if(baseWidget)
        {
            Json::Value jBolcks = Json::Value::null;
            if(baseWidget->widgetType() == wt_QAABlank)
            {
                qaaBlank *wQO = dynamic_cast<qaaBlank*>(baseWidget);
                wQO->getAnswer(sAnswer);
                sAnswerStr +=  sAnswer;
				if(!sAnswer.isEmpty())
				{ 
                    bAnswered = true;
					Json::Value jBolckItem = Json::Value::null;
					jBolckItem["type"] = "text";
					jBolckItem["value"] = sAnswer.toStdString();
					jBolcks["blocks"].append(jBolckItem);
				}
					
            }

            if(baseWidget->widgetType() == wt_photoAnswer)
            {
                addPic *wPA = dynamic_cast<addPic*>(baseWidget);
                QString sFileUrls = wPA->getFileUrl();
				if(!sFileUrls.isEmpty())
				{ 
                    bAnswered = true;
                    QString sTempAns = "";
					QStringList sList = sFileUrls.split(",");
					for (QString sFileUrl : sList)
					{
                        QString sAns = QString(R"(
                                           <a href='%1' >
                                           <img class='photo-answer' src='%2' />
                                           </a>                                           
                                           )").arg(sFileUrl).arg(sFileUrl);
                        sTempAns += sAns;
					}

                    sAnswerStr += QString(R"(<div class='photo-answers-block'>%1</div>)").arg(sTempAns);
					if (!sFileUrls.isEmpty())
					{
						for (QString sFile : sFileUrls.split(","))
						{
							Json::Value jBolckItem = Json::Value::null;
							jBolckItem["type"] = "image";
							jBolckItem["value"] = sFile.toStdString();
							jBolcks["blocks"].append(jBolckItem);
						}
					}
					
				}
                
            }

            if(baseWidget->widgetType() == wt_WXAnswer)
            {
                wxAnswer *wPA = dynamic_cast<wxAnswer*>(baseWidget);
				QString sFileUrl = wPA->getFileUrl();
				sAnswerStr += sFileUrl;
				if(!sFileUrl.isEmpty())
				{ 
                    bAnswered = true;
					Json::Value jBolckItem = Json::Value::null;
					jBolckItem["type"] = "text";
					jBolckItem["value"] = sFileUrl.toStdString();
					jBolcks["blocks"].append(jBolckItem);
				}
                
            }
			if(jBolcks != Json::Value::null)
			{
				jAnswer["sections"].append(jBolcks);
			}           
        }
    }

    m_sqs.sStudentAnswer = jAnswer.toStyledString().c_str();
    qDebug()<<m_sqs.sStudentAnswer;
    return sAnswerStr;
}

bool questionAndAnswer::eventFilter(QObject *obj, QEvent *ev)
{
    if(obj == this)
    {
      //判断事件
        if(ev->type() == QEvent::Hide)
        {           
            myDebug()<<"widgetFillBlank::QEvent::Hide";
            if(m_bAnswerChange)
            {
                updateAnswer();
                m_bAnswerChange = false;
            }

        }
    }
    return QWidget::eventFilter(obj, ev);
}

void questionAndAnswer::handinPaper()
{
    m_pTimer->stop();
    if(m_bAnswerChange)
    {
        updateAnswer();
        m_bAnswerChange = false;
    }
}

int questionAndAnswer::widgetType()
{
    return wt_question;
}

void questionAndAnswer::audioPlayCountChange()
{
    m_bAnswerChange = true;
}
