#include "clOnlineExam.h"
#include "ui_clOnlineExam.h"

#include "CAppInfo.h"
#include "logproc.h"
#include <QScrollBar>
#include "awMsgBox.h"

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

    setStyleSheet(g_appInfoPtr->m_sQssStr);

	qRegisterMetaType<CQueryExamList>("CQueryExamList");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnQueryExamList, this, &clOnlineExam::onQueryExamList);
	qRegisterMetaType<CQueryExamEndList>("CQueryExamEndList");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnQueryExamEndList, this, &clOnlineExam::onQueryExamEndList);

	m_pObjectiveScoreTimer = std::make_shared<QTimer>();
	m_pObjectiveScoreTimer->setInterval(200);
	connect(m_pObjectiveScoreTimer.get(), &QTimer::timeout, this, [&]() {
		m_pObjectiveScoreTimer->stop();
		if (m_pObjectiveScore != nullptr)
		{
			m_pObjectiveScore.reset();
		}
	});

    m_pRefreshTimer = std::make_shared<QTimer>();
    m_pRefreshTimer->setInterval(1000);
    connect(m_pRefreshTimer.get(), &QTimer::timeout, this, [&]() {
        --m_nRefreshSeconds;
        ui->btn_refresh->setText(QString::fromLocal8Bit("倒计时%1s").arg(m_nRefreshSeconds));


        if(m_nRefreshSeconds <= 0)
        {
            m_pRefreshTimer->stop();
            ui->btn_refresh->setEnabled(true);
            ui->btn_refresh->setText(QString::fromLocal8Bit("刷新"));
        }
    });
}

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

void clOnlineExam::setUI(const int nWidth, const int nHeight)
{
    setGeometry(0, 0, nWidth, nHeight);
//    ui->tabw_onlineExam->setGeometry(0, 0, nWidth, nHeight);
//    ui->tabw_onlineExam->setTabText(0, QString::fromLocal8Bit("待考列表"));
//    ui->tabw_onlineExam->setTabText(1, QString::fromLocal8Bit("已完成考试"));
    ui->tabw_onlineExam->setCurrentIndex(0);
    ui->btn_examList->setFixedSize(QSize(g_appInfoPtr->m_fRate*86, g_appInfoPtr->m_fRate*30));
    ui->btn_endExamList->setFixedSize(QSize(g_appInfoPtr->m_fRate*100, g_appInfoPtr->m_fRate*30));
    ui->btn_refresh->setFixedSize(QSize(g_appInfoPtr->m_fRate*86, g_appInfoPtr->m_fRate*30));
    ui->btn_examList->setStyleSheet(QString(R"(QPushButton{
                                            outline:none;
                                            border-radius:%1px;
                                            border:0px solid rgba(255,255,255,1);
                                            background:rgba(19, 187, 138, 1);

                                            font-size:%2px;
                                            font-family:"Microsoft YaHei";
                                            font-weight:500;
                                            color:rgba(255,255,255,1);
                                        })").arg((int)(g_appInfoPtr->m_fRate*15))
                                    .arg((int)(g_appInfoPtr->m_fRate*12)));
    ui->btn_endExamList->setStyleSheet(QString(R"(QPushButton{
                                            outline:none;
                                            border-radius:%1px;
                                            border:0px solid rgba(255,255,255,1);
                                            background:rgba(239, 240, 245, 1);

                                            font-size:%2px;
                                            font-family:"Microsoft YaHei";
                                            font-weight:500;
                                            color:rgba(153, 153, 153, 1);
                                        })").arg((int)(g_appInfoPtr->m_fRate*15))
                                    .arg((int)(g_appInfoPtr->m_fRate*12)));


    ui->vlayout_el->setContentsMargins(g_appInfoPtr->m_fRate*30, 0, g_appInfoPtr->m_fRate*30, 0);
    ui->vlayout_fel->setContentsMargins(g_appInfoPtr->m_fRate*30, 0, g_appInfoPtr->m_fRate*30, 0);

    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(7);

    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("操作");

    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*56);
    ui->tablewt_examList->setColumnWidth(2, g_appInfoPtr->m_fRate*104);
    ui->tablewt_examList->setColumnWidth(3, g_appInfoPtr->m_fRate*277);
    ui->tablewt_examList->setColumnWidth(4, g_appInfoPtr->m_fRate*305);
    ui->tablewt_examList->setColumnWidth(5, g_appInfoPtr->m_fRate*102);
    ui->tablewt_examList->setColumnWidth(6, g_appInfoPtr->m_fRate*146);
    ui->tablewt_examList->horizontalHeader()->setStretchLastSection(true);

    ui->tablew_finishExamList->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //整行选中的方式
    ui->tablew_finishExamList->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置为只能选中一行
    ui->tablew_finishExamList->setSelectionMode(QAbstractItemView::SingleSelection);
    //隐藏列表头
    ui->tablew_finishExamList->verticalHeader()->setVisible(false);
    //隐藏边框
    ui->tablew_finishExamList->setShowGrid(false);
    //表头不高亮显示
    ui->tablew_finishExamList->horizontalHeader()->setHighlightSections(false);
    //设置行数
    ui->tablew_finishExamList->setRowCount(10);
    //设置列数
    ui->tablew_finishExamList->setColumnCount(7);

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



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

    ui->tablew_finishExamList->verticalHeader()->setDefaultSectionSize(g_appInfoPtr->m_fRate*48);
    ui->tablew_finishExamList->setColumnWidth(0, g_appInfoPtr->m_fRate*116);
    ui->tablew_finishExamList->setColumnWidth(1, g_appInfoPtr->m_fRate*56);
    ui->tablew_finishExamList->setColumnWidth(2, g_appInfoPtr->m_fRate*104);
    ui->tablew_finishExamList->setColumnWidth(3, g_appInfoPtr->m_fRate*277);
    ui->tablew_finishExamList->setColumnWidth(4, g_appInfoPtr->m_fRate*305);
    ui->tablew_finishExamList->setColumnWidth(5, g_appInfoPtr->m_fRate*102);
    ui->tablew_finishExamList->setColumnWidth(6, g_appInfoPtr->m_fRate*146);
    ui->tablew_finishExamList->horizontalHeader()->setStretchLastSection(true);

}

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

void clOnlineExam::refreshExam()
{
    CHttpRequestPackage hrp;
    hrp.sUri = "/api/ecs_oe_admin/client/exam/process/queryExamList";
    hrp.nRequestType = RequestType::rtQueryExamList;
    g_httpBllPtr->post(hrp);

    CHttpRequestPackage hrp1;
    hrp1.sUri = "/api/ecs_oe_admin/client/exam/process/queryExamEndList";
    hrp1.nRequestType = RequestType::rtQueryExamEndList;
    g_httpBllPtr->post(hrp1);
}



void clOnlineExam::onQueryExamList(CQueryExamList queryExamList)
{
	if (queryExamList.nCode == 200)
	{
		qDebug() << "onQueryExamList";
		int nSize = queryExamList.vOnlieExamList.size();
        ui->tablewt_examList->setRowCount(nSize);
		for (int i = 0; i < nSize; ++i)
		{
            CExamCourseInfo eci = queryExamList.vOnlieExamList[i];
			ui->tablewt_examList->setItem(i, 0, new QTableWidgetItem(eci.sCourseName));
			ui->tablewt_examList->setItem(i, 1, new QTableWidgetItem(eci.sCourseLevel));
			ui->tablewt_examList->setItem(i, 2, new QTableWidgetItem(eci.sSpecialtyName));
			ui->tablewt_examList->setItem(i, 3, new QTableWidgetItem(QString::fromLocal8Bit("%1 ~ %2").arg(eci.sStartTime).arg(eci.sEndTime)));
            QString sWeekCycle = CWeekTransform::getWeekCycles(eci.vExamCycleWeek);
            QString sTimeRange = eci.sExamCycleTimeRange.join(QString::fromLocal8Bit(","));
			QDateTime dtCurrent = QDateTime::fromMSecsSinceEpoch(g_appInfoPtr->serverMTime());			
			QDateTime dtStartTime = QDateTime::fromString(eci.sStartTime, "yyyy-MM-dd hh:mm:ss");
			QDateTime dtEndTime = QDateTime::fromString(eci.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 = eci.sExamCycleTimeRange.size() == 0 || CWeekTransform::isInTimeRange(tCurrent, eci.sExamCycleTimeRange);
            ui->tablewt_examList->setItem(i, 4, new QTableWidgetItem(QString::fromLocal8Bit("%1 %2").arg(sWeekCycle).arg(sTimeRange)));
			ui->tablewt_examList->setItem(i, 5, new QTableWidgetItem(QString::number(eci.nAllowExamCount)));
			clOperation *clo = new clOperation(i, ui->tablewt_examList);
			clo->setUI(ui->tablewt_examList->columnWidth(6), ui->tablewt_examList->rowHeight(i), CL_OPERATION_TYPE::cot_online_exam);
            clo->setBtn1Enable(bIsInWeek && bIsInTimeRange && bIsInExamTime && eci.nAllowExamCount>0);
            clo->setBtn2Enable(eci.bIsObjScoreView);
			ui->tablewt_examList->setCellWidget(i, 6, clo);
            connect(clo, &clOperation::enterExam, this, [&](CL_OPERATION_TYPE cot, int nRow){
                if (cot == CL_OPERATION_TYPE::cot_online_exam )
                {
                    QString sWeekCycle = CWeekTransform::getWeekCycles(m_vOnlieExamList[nRow].vExamCycleWeek);
                    QString sTimeRange = m_vOnlieExamList[nRow].sExamCycleTimeRange.join(QString::fromLocal8Bit(","));
                    QDateTime dtCurrent = QDateTime::fromMSecsSinceEpoch(g_appInfoPtr->serverMTime());
                    QDateTime dtStartTime = QDateTime::fromString(m_vOnlieExamList[nRow].sStartTime, "yyyy-MM-dd hh:mm:ss");
                    QDateTime dtEndTime = QDateTime::fromString(m_vOnlieExamList[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_vOnlieExamList[nRow].sExamCycleTimeRange.size() == 0 || CWeekTransform::isInTimeRange(tCurrent, m_vOnlieExamList[nRow].sExamCycleTimeRange);
                    if(bIsInWeek && bIsInTimeRange && bIsInExamTime && m_vOnlieExamList[nRow].nAllowExamCount > 0)
                    {
                        emit enterExam(cot, m_vOnlieExamList[nRow].nExamId, m_vOnlieExamList[nRow].nExamStudentId,
                                       m_vOnlieExamList[nRow].sCourseCode, m_vOnlieExamList[nRow].sCourseName);
                    }
                }
            });
			connect(clo, &clOperation::showObjectiveScore, this, [&](CL_OPERATION_TYPE cot, int nRow) {
				if (cot == CL_OPERATION_TYPE::cot_online_exam )
				{					
					m_pObjectiveScoreTimer->stop();
					
					if (m_pObjectiveScore != nullptr &&
						m_pObjectiveScore->getRow() != nRow)
					{
						m_pObjectiveScore.reset();
					}
					
					if (m_pObjectiveScore == nullptr)
					{
						m_pObjectiveScore = std::make_shared<clObjectiveScore>(nRow, QString::number(m_vOnlieExamList[nRow].nExamStudentId), this);
						connect(m_pObjectiveScore.get(), &clObjectiveScore::objectiveScoreHeight, this, [&](int nRow, int nHeight) {
							int ntableTop =  ui->tabw_onlineExam->y() + g_appInfoPtr->m_fRate*70;
							int nTop = ntableTop + (nRow + 2)* ui->tablewt_examList->verticalHeader()->defaultSectionSize() - nHeight / 2;
                            if (nHeight > ui->tabw_onlineExam->height())
                            {
                                nHeight = ui->tabw_onlineExam->height();
                            }

                            if (nTop < ui->tabw_onlineExam->y())
							{
								nTop = ui->tabw_onlineExam->y();
							}
							else if ((nTop + nHeight) > (ntableTop + ui->tablewt_examList->height()))
							{
								nTop = ntableTop + ui->tablewt_examList->height() - nHeight;
							}


							m_pObjectiveScore->setUI(ui->tablewt_examList->x() + ui->tablewt_examList->width() - ui->tablewt_examList->columnWidth(6) - g_appInfoPtr->m_fRate * 530,
								nTop, g_appInfoPtr->m_fRate * 530, nHeight);
							m_pObjectiveScore->show();
						});
						
					}
				}
			    
			});

			connect(clo, &clOperation::hideObjectiveScore, this, [&](CL_OPERATION_TYPE cot, int nRow) {
				if (cot == CL_OPERATION_TYPE::cot_online_exam)
				{
					m_pObjectiveScoreTimer->start();	
				}
			});
		}
		m_vOnlieExamList.swap(queryExamList.vOnlieExamList);
	}
	else
	{
        if(queryExamList.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取在线考试信息失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(queryExamList.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOnlineExam::onQueryExamEndList(CQueryExamEndList queryExamEndList)
{
	if (queryExamEndList.nCode == 200)
	{
		int nSize = queryExamEndList.vOnlieEndExamList.size();
        ui->tablew_finishExamList->setRowCount(nSize);
		for (int i = 0; i < nSize; ++i)
		{
			CExamCourseInfo eci = queryExamEndList.vOnlieEndExamList[i];
			ui->tablew_finishExamList->setItem(i, 0, new QTableWidgetItem(eci.sCourseName));
			ui->tablew_finishExamList->setItem(i, 1, new QTableWidgetItem(eci.sCourseLevel));
			ui->tablew_finishExamList->setItem(i, 2, new QTableWidgetItem(eci.sSpecialtyName));
			ui->tablew_finishExamList->setItem(i, 3, new QTableWidgetItem(QString::fromLocal8Bit("%1 ~ %2").arg(eci.sStartTime).arg(eci.sEndTime)));
			QString sWeekCycle = CWeekTransform::getWeekCycles(eci.vExamCycleWeek);
			QString sTimeRange = eci.sExamCycleTimeRange.join(",");
			
			ui->tablew_finishExamList->setItem(i, 4, new QTableWidgetItem(QString::fromLocal8Bit("%1 %2").arg(sWeekCycle).arg(sTimeRange)));
			ui->tablew_finishExamList->setItem(i, 5, new QTableWidgetItem(QString::number(eci.nAllowExamCount)));
			clOperation *clo = new clOperation(i, ui->tablew_finishExamList);
			clo->setUI(ui->tablew_finishExamList->columnWidth(6), ui->tablew_finishExamList->rowHeight(i), CL_OPERATION_TYPE::cot_online_finish_exam);
            clo->setBtn1Enable(eci.bIsObjScoreView);
			ui->tablew_finishExamList->setCellWidget(i, 6, clo);

            connect(clo, &clOperation::showObjectiveScore, this, [&](CL_OPERATION_TYPE cot, int nRow) {
                if (cot == CL_OPERATION_TYPE::cot_online_finish_exam )
                {
                    m_pObjectiveScoreTimer->stop();

                    if (m_pObjectiveScore != nullptr &&
                        m_pObjectiveScore->getRow() != nRow)
                    {
                        m_pObjectiveScore.reset();
                    }

                    if (m_pObjectiveScore == nullptr)
                    {
                        m_pObjectiveScore = std::make_shared<clObjectiveScore>(nRow, QString::number(m_vOnlieEndExamList[nRow].nExamStudentId), this);
                        connect(m_pObjectiveScore.get(), &clObjectiveScore::objectiveScoreHeight, this, [&](int nRow, int nHeight) {
                            int ntableTop =  ui->tablew_finishExamList->y() + g_appInfoPtr->m_fRate*70;
                            int nTop = ntableTop + (nRow + 2)* ui->tablew_finishExamList->verticalHeader()->defaultSectionSize() - nHeight / 2;
                            if (nHeight > ui->tabw_onlineExam->height())
                            {
                                nHeight = ui->tabw_onlineExam->height();
                            }

                            if (nTop < ui->tablew_finishExamList->y())
                            {
                                nTop = ui->tablew_finishExamList->y();
                            }
                            else if ((nTop + nHeight) > (ntableTop + ui->tablew_finishExamList->height()))
                            {
                                nTop = ntableTop + ui->tablew_finishExamList->height() - nHeight;
                            }
                            m_pObjectiveScore->setUI(ui->tablew_finishExamList->x() + ui->tablew_finishExamList->width() - ui->tablew_finishExamList->columnWidth(6) - g_appInfoPtr->m_fRate * 530,
                                nTop, g_appInfoPtr->m_fRate * 530, nHeight);
                            m_pObjectiveScore->show();
                        });

                    }
                }

            });

            connect(clo, &clOperation::hideObjectiveScore, this, [&](CL_OPERATION_TYPE cot, int nRow) {
                if (cot == CL_OPERATION_TYPE::cot_online_finish_exam)
                {
                    m_pObjectiveScoreTimer->start();
                }
            });
		}
        m_vOnlieEndExamList.swap(queryExamEndList.vOnlieEndExamList);
	}
	else
	{
        if(queryExamEndList.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取在线考试信息失败"), (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(queryExamEndList.sMessage, (QWidget*)(this->parent()), MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOnlineExam::on_btn_examList_clicked()
{
    ui->tabw_onlineExam->setCurrentIndex(0);

    ui->btn_examList->setStyleSheet(QString(R"(QPushButton{
                                            outline:none;
                                            border-radius:%1px;
                                            border:0px solid rgba(255,255,255,1);
                                            background:rgba(19, 187, 138, 1);

                                            font-size:%2px;
                                            font-family:"Microsoft YaHei";
                                            font-weight:500;
                                            color:rgba(255,255,255,1);
                                        })").arg((int)(g_appInfoPtr->m_fRate*15))
                                    .arg((int)(g_appInfoPtr->m_fRate*12)));
    ui->btn_endExamList->setStyleSheet(QString(R"(QPushButton{
                                            outline:none;
                                            border-radius:%1px;
                                            border:0px solid rgba(255,255,255,1);
                                            background:rgba(239, 240, 245, 1);

                                            font-size:%2px;
                                            font-family:"Microsoft YaHei";
                                            font-weight:500;
                                            color:rgba(153, 153, 153, 1);
                                        })").arg((int)(g_appInfoPtr->m_fRate*15))
                                    .arg((int)(g_appInfoPtr->m_fRate*12)));

}

void clOnlineExam::on_btn_endExamList_clicked()
{
    ui->tabw_onlineExam->setCurrentIndex(1);
    ui->btn_endExamList->setStyleSheet(QString(R"(QPushButton{
                                            outline:none;
                                            border-radius:%1px;
                                            border:0px solid rgba(255,255,255,1);
                                            background:rgba(19, 187, 138, 1);

                                            font-size:%2px;
                                            font-family:"Microsoft YaHei";
                                            font-weight:500;
                                            color:rgba(255,255,255,1);
                                        })").arg((int)(g_appInfoPtr->m_fRate*15))
                                    .arg((int)(g_appInfoPtr->m_fRate*12)));
    ui->btn_examList->setStyleSheet(QString(R"(QPushButton{
                                            outline:none;
                                            border-radius:%1px;
                                            border:0px solid rgba(255,255,255,1);
                                            background:rgba(239, 240, 245, 1);

                                            font-size:%2px;
                                            font-family:"Microsoft YaHei";
                                            font-weight:500;
                                            color:rgba(153, 153, 153, 1);
                                        })").arg((int)(g_appInfoPtr->m_fRate*15))
                                    .arg((int)(g_appInfoPtr->m_fRate*12)));

}


void clOnlineExam::on_btn_refresh_clicked()
{
    ui->btn_refresh->setEnabled(false);
    refreshExam();
    m_pRefreshTimer->start();
    m_nRefreshSeconds = 20;
    ui->btn_refresh->setText(QString::fromLocal8Bit("倒计时%1s").arg(m_nRefreshSeconds));
}
