#include "choiceQuesiton.h"
#include "ui_choiceQuesiton.h"

#include <QFile>

#include "questionBody.h"
#include "questionOption.h"
#include "audioPlay.h"
#include "CCommonTools.h"
#include "CSqlite3DBProc.h"
//#include "MsgDlg.h"
#include "CAppInfo.h"
#include "logproc.h"

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

    setAttribute(Qt::WA_DeleteOnClose);

    b_isPressed = false;

    setStyleSheet(g_appInfoPtr->m_sQssStr);
}

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

int choiceQuesiton::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);
    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(m_sqs.vOptions.size() <= 0 )
    {
        if(m_sqs.sQuestionType == QUESTION_TYPE::TrueOrFalse)
        {
            initJudgeOptions();
        }
    }
    else
    {
        initOptions(m_sqs.voptionPermutation, m_sqs.vOptions, m_sqs.sQuestionType);
    }
    setAnswer(m_sqs.sStudentAnswer);


    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*10);

    setMarkStyle();

    return height();
}

void choiceQuesiton::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 choiceQuesiton::initJudgeOptions()
{
    Json::Value jOption = Json::Value::null;
    jOption["number"] = 0;

    Json::Value jBlosk = Json::Value::null;
    jBlosk["type"] = "text";
    jBlosk["value"] = QString::fromLocal8Bit("正确").toStdString();
    Json::Value jBloskItem = Json::Value::null;
    jBloskItem.append(jBlosk);
    Json::Value jSection = Json::Value::null;
    jSection["blocks"] = jBloskItem;
    Json::Value jSectionItem = Json::Value::null;
    jSectionItem.append(jSection);
    jOption["sections"] = jSectionItem;

    questionOption *wQO = new questionOption(1, jOption, m_sqs.nLimitedPlayTimes);
    connect(wQO, &questionOption::answered, this, &choiceQuesiton::onAnswered);
    connect(wQO, &questionOption::cancelAnswered, this, &choiceQuesiton::onCancelAnswered);
    connect(wQO, &questionOption::answerChanged, this, &choiceQuesiton::onAnswerChanged);
    QListWidgetItem *listItem = new QListWidgetItem;
    int nQBHeight = wQO->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, wQO);


    Json::Value jOption1 = Json::Value::null;
    jOption1["number"] = 1;
    Json::Value jBlosk1 = Json::Value::null;
    jBlosk1["type"] = "text";
    jBlosk1["value"] = QString::fromLocal8Bit("错误").toStdString();
    Json::Value jBloskItem1 = Json::Value::null;
    jBloskItem1.append(jBlosk1);
    Json::Value jSection1 = Json::Value::null;
    jSection1["blocks"] = jBloskItem1;
    Json::Value jSectionItem1 = Json::Value::null;
    jSectionItem1.append(jSection1);    
    jOption1["sections"] = jSectionItem1;

    questionOption *wQO1 = new questionOption(2, jOption1, m_sqs.nLimitedPlayTimes);
    connect(wQO1, &questionOption::answered, this, &choiceQuesiton::onAnswered);
    connect(wQO1, &questionOption::cancelAnswered, this, &choiceQuesiton::onCancelAnswered);
    connect(wQO1, &questionOption::answerChanged, this, &choiceQuesiton::onAnswerChanged);
    QListWidgetItem *listItem1 = new QListWidgetItem;
    int nQBHeight1 = wQO1->setUI(ui->list_choiceQuestion->width());
    m_nListHeight += nQBHeight1;
    listItem1->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQBHeight1));
    ui->list_choiceQuestion->addItem(listItem1);
    ui->list_choiceQuestion->setItemWidget(listItem1, wQO1);
}

void choiceQuesiton::initOptions(std::vector<int> voptionPermutation, std::vector<COption> vOptions, QString sQuestionType)
{
    if(voptionPermutation.size() <= 0)
    {
        int nOptionSize = vOptions.size();

        for(int i = 0; i < nOptionSize; i++)
        {
            COption Option = vOptions[i];
			Json::Reader reader;
			Json::Value jBody = Json::Value::null;
			if (!reader.parse(Option.sBody.toStdString(), jBody))
			{
				//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
				myDebug() << QString::fromLocal8Bit("解析题干出错！");
			}
            jBody["number"] = i;
            questionOption *wQO = new questionOption(i+1, jBody, m_sqs.nLimitedPlayTimes);
            connect(wQO, &questionOption::answered, this, &choiceQuesiton::onAnswered);
            connect(wQO, &questionOption::cancelAnswered, this, &choiceQuesiton::onCancelAnswered);
            connect(wQO, &questionOption::answerChanged, this, &choiceQuesiton::onAnswerChanged);
            connect(wQO, &questionOption::mutiAnswerChanged, this, &choiceQuesiton::onMutiAnswerChanged);
            connect(wQO, &questionOption::audioPlayCountChange, this, [&](){audioPlayCountChange();});

            if(sQuestionType == QUESTION_TYPE::MultipleChoice)
            {
                wQO->setMultiChoice(true);
            }
            QListWidgetItem *listItem = new QListWidgetItem;
            int nQBHeight = wQO->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, wQO);
        }
    }
    else
    {
     //   QStringList strList = QString(sOrderStr.c_str()).split(",");
        for(int i = 0; i < voptionPermutation.size(); i++)
        {
            COption Option = vOptions[voptionPermutation[i]];
			Json::Reader reader;
			Json::Value jBody = Json::Value::null;
			if (!reader.parse(Option.sBody.toStdString(), jBody))
			{
				//            ShowMsg(QString::fromLocal8Bit("解析题干出错！"), g_appInfoPtr->m_answerWidget);
				myDebug() << QString::fromLocal8Bit("解析题干出错！");
			}

            jBody["number"] = voptionPermutation[i];
            questionOption *wQO = new questionOption(i+1, jBody, m_sqs.nLimitedPlayTimes);
            connect(wQO, &questionOption::answered, this, &choiceQuesiton::onAnswered);
            connect(wQO, &questionOption::cancelAnswered, this, &choiceQuesiton::onCancelAnswered);
            connect(wQO, &questionOption::answerChanged, this, &choiceQuesiton::onAnswerChanged);
            connect(wQO, &questionOption::mutiAnswerChanged, this, &choiceQuesiton::onMutiAnswerChanged);
            connect(wQO, &questionOption::audioPlayCountChange, this, [&](){audioPlayCountChange();});

            if(sQuestionType == QUESTION_TYPE::MultipleChoice)
            {
                wQO->setMultiChoice(true);
            }
            QListWidgetItem *listItem = new QListWidgetItem;
            int nQBHeight = wQO->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, wQO);
        }
    }
}

void choiceQuesiton::setAnswer(QString sAnswer)
{
    if(sAnswer.isEmpty())
    {
        return;
    }


    if(m_sqs.sQuestionType == QUESTION_TYPE::TrueOrFalse)
    {
        sAnswer = sAnswer == "true" ? "0" : "1";
    }
    bool bAnswered = false;
//    QStringList list = sAnswer.split(",");
    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_optionItem)//选项
        {
            questionOption *wQO = dynamic_cast<questionOption*>(baseWidget);
            if(sAnswer.indexOf(QString::number(wQO->optionMumber())) >= 0)
            {
                wQO->setChecked(true);
                wQO->setAnswered(true);
                bAnswered = true;
            }
        }
    }

    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_optionItem)//选项
        {
            questionOption *wQO = dynamic_cast<questionOption*>(baseWidget);
            wQO->setAnswered(true);
        }
    }
}

void choiceQuesiton::onAnswerChanged(int nOrderIndex)
{
    int nIdex = 1;
    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_optionItem)//选项
        {
            questionOption *wQO = dynamic_cast<questionOption*>(baseWidget);
            if(nIdex == nOrderIndex)
            {
                wQO->setChecked(true);
            }
            else
            {
                wQO->setChecked(false);
            }
            wQO->setAnswered(true);
            nIdex++;
        }
    }
    answerChange();
}


void choiceQuesiton::onAnswered()
{
    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_optionItem)//选项
        {
            questionOption *wQO = dynamic_cast<questionOption*>(baseWidget);
            wQO->setAnswered(true);            
        }
    }
    answerChange();
}

void choiceQuesiton::onCancelAnswered()
{
    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_optionItem)//选项
        {
            questionOption *wQO = dynamic_cast<questionOption*>(baseWidget);
            wQO->setAnswered(false);            
        }
    }
    answerChange();
}

void choiceQuesiton::onMutiAnswerChanged()
{
    answerChange();
}

void choiceQuesiton::answerChange()
{
    Json::Value jAudioPlayedInfo = Json::Value::null;
    QString sAnsStr = "";


    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_optionItem)//选项
        {
            questionOption *wQO = dynamic_cast<questionOption*>(baseWidget);
            if(wQO->checked())
            {
                int nNumber = wQO->optionMumber();
                if(m_sqs.sQuestionType == QUESTION_TYPE::TrueOrFalse)
                {
                    sAnsStr += nNumber == 0 ? "true" : "false";
                }
                else
                {
                    sAnsStr += QString::number(nNumber);
                }
            }
        }
        else 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();
    }

    updateAnswer(sAnsStr, sAudioPalyedInfo);

    if(!sAnsStr.isEmpty())
    {
        m_sqs.bAnswered = true;
        emit questionAnswered(true, m_sqs.nOrder);
    }
    else
    {
        m_sqs.bAnswered = false;
        emit questionAnswered(false, m_sqs.nOrder);
    }
}

void choiceQuesiton::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;
                    questionBody *wQB = new questionBody(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(), nIndex);
                    m_nListHeight += nQBHeight;
                    listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQBHeight));
                    ui->list_choiceQuestion->addItem(listItem);
                    ui->list_choiceQuestion->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_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;
        questionBody *wQB = new questionBody(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(), nIndex);
        m_nListHeight += nQBHeight;
        listItem->setSizeHint(QSize(ui->list_choiceQuestion->width(), nQBHeight));
        ui->list_choiceQuestion->addItem(listItem);
        ui->list_choiceQuestion->setItemWidget(listItem, wQB);        
    }
}

void choiceQuesiton::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 choiceQuesiton::updateAnswer(QString sAnsStr, QString sAudioPalyedInfo)
{
    QString sUploadAnswer = "";
    Json::Value jAnswerJson = Json::Value::null;

    __int64 timeStamp = g_appInfoPtr->serverMTime();



    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"] = sAnsStr.toStdString();
    jAnswer.append(jAnswerItem);
    sUploadAnswer = jAnswer.toStyledString().c_str();
    qDebug()<<sUploadAnswer;
    m_sqs.nVersion++;
    m_sqs.bUpload = false;
    m_sqs.sStudentAnswer = sAnsStr;
    m_sqs.sUploadAnswer = sUploadAnswer;
    emit uploadAnswer(m_sqs.nOrder, timeStamp, sUploadAnswer);
}

void choiceQuesiton::audioPlayCountChange()
{
    answerChange();
}

void choiceQuesiton::handinPaper()
{

}

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