#include "clOnlinePractice.h"
#include "ui_clOnlinePractice.h"

#include "CAppInfo.h"
#include "clOperation.h"

#include <QScrollBar>
#include <QListView>
#include <QDateTime>
#include "awMsgBox.h"
#include "logproc.h"

clOnlinePractice::clOnlinePractice(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::clOnlinePractice)
{
    ui->setupUi(this);

    setStyleSheet(g_appInfoPtr->m_sQssStr);

    m_nCurExamId = 0;

	qRegisterMetaType<CQueryBatchList>("CQueryBatchList");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnQueryBatchList, this, &clOnlinePractice::onQueryBatchList);
	qRegisterMetaType<CQueryPracticeCourseList>("CQueryPracticeCourseList");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnQueryPracticeCourseList, this, &clOnlinePractice::onQueyPracticeCourseList);
	
}

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

void clOnlinePractice::setUI(const int nWidth, const int nHeight)
{
    setGeometry(0, 0, nWidth, nHeight);
    ui->widget_onlinePractice->setGeometry(0, 0, width(), height());
    ui->widget_op_top->setGeometry(0, 0, width(), g_appInfoPtr->m_fRate*72);
    ui->label_batch->adjustSize();
    ui->label_batch->setGeometry(g_appInfoPtr->m_fRate*30, (ui->widget_op_top->height() - ui->label_batch->height())/2,
                                 ui->label_batch->width(), ui->label_batch->height());
    ui->cbo_batch->setGeometry(ui->label_batch->x() + ui->label_batch->width() + g_appInfoPtr->m_fRate*10,
                               (ui->widget_op_top->height() - g_appInfoPtr->m_fRate*32)/2,
                               g_appInfoPtr->m_fRate*240, g_appInfoPtr->m_fRate*32);
	ui->cbo_batch->setView(new QListView);
	ui->tablewt_examList->setGeometry(g_appInfoPtr->m_fRate*30, ui->widget_op_top->height() + g_appInfoPtr->m_fRate*10,
                                      ui->widget_onlinePractice->width() - g_appInfoPtr->m_fRate*30*2,
                                      ui->widget_onlinePractice->height() - ui->widget_op_top->height() - g_appInfoPtr->m_fRate*(10 + 62));
    ui->tablewt_examList->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //整行选中的方式
    ui->tablewt_examList->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置为只能选中一行
    ui->tablewt_examList->setSelectionMode(QAbstractItemView::SingleSelection);
    //隐藏列表头
    ui->tablewt_examList->verticalHeader()->setVisible(false);
    //隐藏边框
    ui->tablewt_examList->setShowGrid(false);
    //表头不高亮显示
    ui->tablewt_examList->horizontalHeader()->setHighlightSections(false);
    //设置行数
    ui->tablewt_examList->setRowCount(10);
    //设置列数
    ui->tablewt_examList->setColumnCount(8);

    ui->tablewt_examList->setHorizontalScrollMode(QTableWidget::ScrollPerPixel);
    ui->tablewt_examList->horizontalScrollBar()->setSingleStep(g_appInfoPtr->m_fRate*5);

    QStringList sHeadStr;
    sHeadStr << QString::fromLocal8Bit("课程") <<
                QString::fromLocal8Bit("考试进入时间") <<
                QString::fromLocal8Bit("考试时间周期") <<
                QString::fromLocal8Bit("练习次数") <<
                QString::fromLocal8Bit("最近正确率") <<
                QString::fromLocal8Bit("平均正确率") <<
                QString::fromLocal8Bit("最高正确率") <<
                QString::fromLocal8Bit("操作");

    ui->tablewt_examList->setHorizontalHeaderLabels(sHeadStr);
    ui->tablewt_examList->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    ui->tablewt_examList->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    ui->tablewt_examList->verticalHeader()->setDefaultSectionSize(g_appInfoPtr->m_fRate*48);
    ui->tablewt_examList->setColumnWidth(0, g_appInfoPtr->m_fRate*116);
    ui->tablewt_examList->setColumnWidth(1, g_appInfoPtr->m_fRate*275);
    ui->tablewt_examList->setColumnWidth(2, g_appInfoPtr->m_fRate*280);
    ui->tablewt_examList->setColumnWidth(3, g_appInfoPtr->m_fRate*66);
    ui->tablewt_examList->setColumnWidth(4, g_appInfoPtr->m_fRate*80);
    ui->tablewt_examList->setColumnWidth(5, g_appInfoPtr->m_fRate*80);
    ui->tablewt_examList->setColumnWidth(6, g_appInfoPtr->m_fRate*80);
    ui->tablewt_examList->setColumnWidth(7, g_appInfoPtr->m_fRate*146);
    ui->tablewt_examList->horizontalHeader()->setStretchLastSection(true);


}

void clOnlinePractice::onQueryBatchList(CQueryBatchList queryBatchList)
{
	if (queryBatchList.nCode == 200)
	{
        __int64 nCurExamId = m_nCurExamId;
		ui->cbo_batch->clear();        
        int nIndex = 0;
        for (size_t i = 0; i < queryBatchList.vBatchList.size(); ++i)
		{
            CBatchInfo bi = queryBatchList.vBatchList[i];
			ui->cbo_batch->addItem(bi.sName, bi.nId);

            if(nCurExamId == bi.nId)
            {
                nIndex = i;
            }
		}

		if(queryBatchList.vBatchList.size() > 0 )
		{
			m_nCurExamId = queryBatchList.vBatchList[nIndex].nId;
			ui->cbo_batch->setCurrentIndex(nIndex);
			myDebug() << "m_nCurExamId" << m_nCurExamId;
		}
        
	}
	else
	{
        if(queryBatchList.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取批次信息失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(queryBatchList.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOnlinePractice::releaseClopResult()
{
    if(m_pResultList)
    {
        m_pResultList.reset();
    }
}

void clOnlinePractice::showEvent(QShowEvent *)
{    	   
	refreshExam();
}

void clOnlinePractice::refreshExamInfo()
{
    refreshExam();
}

void clOnlinePractice::refreshExam()
{
	CHttpRequestPackage hrp;
	hrp.sUri = "/api/ecs_exam_work/exam/queryByNameLike";
	hrp.sParamList.push_back("examTypes,PRACTICE");
	hrp.sParamList.push_back(QString("studentId,%1").arg(g_appInfoPtr->m_nStudentId));
	hrp.sParamList.push_back(QString("name,%1").arg(""));
	hrp.nRequestType = RequestType::rtQueryBatchList;
	g_httpBllPtr->get(hrp);
}

void clOnlinePractice::onQueyPracticeCourseList(CQueryPracticeCourseList queryPracticeCourseList)
{
	if (queryPracticeCourseList.nCode == 200)
	{        
		int nSize = queryPracticeCourseList.vPracticeCourseInfo.size();
        ui->tablewt_examList->setRowCount(nSize);
		for (int i = 0; i < nSize; ++i)
		{
			CPracticeCourseInfo pci = queryPracticeCourseList.vPracticeCourseInfo[i];
			ui->tablewt_examList->setItem(i, 0, new QTableWidgetItem(pci.sCourseName));
			ui->tablewt_examList->setItem(i, 1, new QTableWidgetItem(QString::fromLocal8Bit("%1 ~ %2").arg(pci.sStartTime).arg(pci.sEndTime)));
			QString sWeekCycle = CWeekTransform::getWeekCycles(pci.vExamCycleWeek);
			QString sTimeRange = pci.sExamCycleTimeRange.join(",");
			QDateTime dtCurrent = QDateTime::fromMSecsSinceEpoch(g_appInfoPtr->serverMTime());
			QDateTime dtStartTime = QDateTime::fromString(pci.sStartTime, "yyyy-MM-dd hh:mm:ss");
			QDateTime dtEndTime = QDateTime::fromString(pci.sEndTime, "yyyy-MM-dd hh:mm:ss");
			bool bIsInExamTime = dtCurrent > dtStartTime && dtCurrent < dtEndTime;
			QString sWeek = dtCurrent.toString("ddd");
			bool bIsInWeek = sWeekCycle.size() == 0 || sWeekCycle.indexOf(sWeek) >= 0;
			QTime tCurrent = QDateTime::fromMSecsSinceEpoch(g_appInfoPtr->serverMTime()).time();
			bool bIsInTimeRange = pci.sExamCycleTimeRange.size() == 0 || CWeekTransform::isInTimeRange(tCurrent, pci.sExamCycleTimeRange);
			ui->tablewt_examList->setItem(i, 2, new QTableWidgetItem(QString::fromLocal8Bit("%1 %2").arg(sWeekCycle).arg(sTimeRange)));
			ui->tablewt_examList->setItem(i, 3, new QTableWidgetItem(QString::number(pci.nPracticeCount)));
			ui->tablewt_examList->setItem(i, 4, new QTableWidgetItem(QString::fromLocal8Bit("%1%").arg(pci.fRecentObjectiveAccuracy)));
			ui->tablewt_examList->setItem(i, 5, new QTableWidgetItem(QString::fromLocal8Bit("%1%").arg(pci.fAveObjectiveAccuracy)));
			ui->tablewt_examList->setItem(i, 6, new QTableWidgetItem(QString::fromLocal8Bit("%1%").arg(pci.fMaxObjectiveAccuracy)));
			clOperation *clo = new clOperation(i, ui->tablewt_examList);
			
            connect(clo, &clOperation::enterExam, this, [&](CL_OPERATION_TYPE cot, int nRow){
                if (cot == CL_OPERATION_TYPE::cot_online_practice )
                {
                    QString sWeekCycle = CWeekTransform::getWeekCycles(m_vPracticeCourseInfo[nRow].vExamCycleWeek);
                    QString sTimeRange = m_vPracticeCourseInfo[nRow].sExamCycleTimeRange.join(",");
                    QDateTime dtCurrent = QDateTime::fromMSecsSinceEpoch(g_appInfoPtr->serverMTime());
                    QDateTime dtStartTime = QDateTime::fromString(m_vPracticeCourseInfo[nRow].sStartTime, "yyyy-MM-dd hh:mm:ss");
                    QDateTime dtEndTime = QDateTime::fromString(m_vPracticeCourseInfo[nRow].sEndTime, "yyyy-MM-dd hh:mm:ss");
                    bool bIsInExamTime = dtCurrent > dtStartTime && dtCurrent < dtEndTime;
                    QString sWeek = dtCurrent.toString("ddd");
                    bool bIsInWeek = sWeekCycle.size() == 0 || sWeekCycle.indexOf(sWeek) >= 0;
                    QTime tCurrent = QDateTime::fromMSecsSinceEpoch(g_appInfoPtr->serverMTime()).time();
                    bool bIsInTimeRange = m_vPracticeCourseInfo[nRow].sExamCycleTimeRange.size() == 0 || CWeekTransform::isInTimeRange(tCurrent, m_vPracticeCourseInfo[nRow].sExamCycleTimeRange);
                    if(bIsInWeek && bIsInTimeRange && bIsInExamTime)
                    {
                        emit enterExam(cot, m_vPracticeCourseInfo[nRow].nExamId, m_vPracticeCourseInfo[nRow].nExamStudentId,
                                   m_vPracticeCourseInfo[nRow].sCourseCode, m_vPracticeCourseInfo[nRow].sCourseName);					
                    }
                }
            });
            connect(clo, &clOperation::viewPracticeDetail, this, [&](int nRow){
                if(m_pResultList == nullptr)
                {
                    m_pResultList = std::make_shared<clopResultList>(m_vPracticeCourseInfo[nRow],  ui->cbo_batch->currentText(), this);
                    connect(m_pResultList.get(), &clopResultList::goback, this, [&](){
                        m_pResultList.reset();
                    });
                    m_pResultList->setUI(0, 0, width(), height());
                }

                m_pResultList->show();
            });
			clo->setUI(ui->tablewt_examList->columnWidth(7), ui->tablewt_examList->rowHeight(i), CL_OPERATION_TYPE::cot_online_practice);
			clo->setBtn1Enable(bIsInWeek && bIsInTimeRange && bIsInExamTime );
			ui->tablewt_examList->setCellWidget(i, 7, clo);
		}
        m_vPracticeCourseInfo.swap(queryPracticeCourseList.vPracticeCourseInfo);
	}
	else
	{
        if(queryPracticeCourseList.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取练习列表失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(queryPracticeCourseList.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOnlinePractice::on_cbo_batch_currentIndexChanged(int index)
{
    QString sExamId = ui->cbo_batch->currentData().toString();    
    if(!sExamId.isEmpty())
    {
        m_nCurExamId = sExamId.toULongLong();
		myDebug() << "on_cbo_batch_currentIndexChanged"<<sExamId;        
        CHttpRequestPackage hrp;
        hrp.sUri = "/api/ecs_oe_admin/client/exam/process/queryPracticeCourseList";
        hrp.sParamList.push_back(QString("examId,%1").arg(sExamId));
        hrp.nRequestType = RequestType::rtQueryPracticeCourseList;
        hrp.eParamType = HttpParamType::hptUrl;
        g_httpBllPtr->post(hrp);
    }
}
