#include "clOfflineExam.h"
#include "ui_clOfflineExam.h"

#include "CAppInfo.h"
#include "clOperation.h"
#include "awMsgBox.h"
#include <QScrollBar>
#include <QFileDialog>


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

    setStyleSheet(g_appInfoPtr->m_sQssStr);

	qRegisterMetaType<CGetOfflineCourse>("CGetOfflineCourse");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetOfflineCourse, this, &clOfflineExam::onGetOfflineCourse);
	qRegisterMetaType<CGetOffLineExamAnswerSheet>("CGetOffLineExamAnswerSheet");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetOffLineExamAnswerSheet, this, &clOfflineExam::onGetOffLineExamAnswerSheet);
	qRegisterMetaType<CStartOfflineExam>("CStartOfflineExam");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnStartOfflineExam, this, &clOfflineExam::onStartOfflineExam);
	qRegisterMetaType<CGetOffLineExamPaper>("CGetOffLineExamPaper");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetOffLineExamPaper, this, &clOfflineExam::onGetOffLineExamPaper);
	qRegisterMetaType<CPreviewOffLineExamPaper>("CPreviewOffLineExamPaper");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnPreviewOffLineExamPaper, this, &clOfflineExam::onPreviewOffLineExamPaper);	
	qRegisterMetaType<CGetExamProperty>("CGetExamProperty");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnGetExamProperty, this, &clOfflineExam::onGetExamProperty);
    qRegisterMetaType<CDownLoadFileInfo>("CDownLoadFileInfo");
    connect(g_httpBllPtr.get(), &CHttpBll::sgnDownLoadFile, this, &clOfflineExam::onDownLoadFile);
}

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

void clOfflineExam::setUI(const int nWidth, const int nHeight)
{
    setGeometry(0, 0, nWidth, nHeight);
    ui->widget_offlineExam->setGeometry(0, 0, width(), height());
    ui->widget_op_top->setGeometry(0, 0, width(), g_appInfoPtr->m_fRate*72);
    ui->btn_downloadAnswerSheet->setGeometry(ui->widget_op_top->width() - g_appInfoPtr->m_fRate*30 - g_appInfoPtr->m_fRate*144,
                                             (ui->widget_op_top->height() - g_appInfoPtr->m_fRate*32)/2,
                                             g_appInfoPtr->m_fRate*144, g_appInfoPtr->m_fRate*32);
	ui->btn_downloadAnswerSheet->setVisible(false);
	ui->btn_downloadAnswerSheet->setIconSize(QSize(g_appInfoPtr->m_fRate*14, g_appInfoPtr->m_fRate*14));
    ui->btn_downloadAnswerSheet->setIcon(QIcon(":/images/icon-download-answer-sheet.png"));
    ui->tablewt_examList->setGeometry(g_appInfoPtr->m_fRate*30, ui->widget_op_top->height() + g_appInfoPtr->m_fRate*10,
                                      ui->widget_offlineExam->width() - g_appInfoPtr->m_fRate*30*2,
                                      ui->widget_offlineExam->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(5);

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

    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*240);
    ui->tablewt_examList->setColumnWidth(1, g_appInfoPtr->m_fRate*220);
    ui->tablewt_examList->setColumnWidth(2, g_appInfoPtr->m_fRate*340);
    ui->tablewt_examList->setColumnWidth(3, g_appInfoPtr->m_fRate*90);
    ui->tablewt_examList->setColumnWidth(4, g_appInfoPtr->m_fRate*232);

    ui->tablewt_examList->horizontalHeader()->setStretchLastSection(true);

    
}

void clOfflineExam::showEvent(QShowEvent *)
{
    refreshCourse();
}

void clOfflineExam::refreshCourse()
{
    CHttpRequestPackage hrp1;
    hrp1.sUri = "/api/ecs_core/org/getAnswersUrl/" + g_appInfoPtr->m_sRootOrgId;
    hrp1.nRequestType = RequestType::rtGetOffLineExamAnswerSheet;
    g_httpBllPtr->get(hrp1);

    CHttpRequestPackage hrp;
    hrp.sUri = "/api/ecs_oe_admin/client/exam/process/getOfflineCourse";
    hrp.nRequestType = RequestType::rtGetOfflineCourse;
    g_httpBllPtr->post(hrp);
}

void clOfflineExam::onGetOfflineCourse(CGetOfflineCourse getOfflineCourse)
{
	if (getOfflineCourse.nCode == 200)
	{
		int nSize = getOfflineCourse.vOfflineCourseInfo.size();
        ui->tablewt_examList->setRowCount(nSize);
		for (int i = 0; i < nSize; ++i)
		{
			COfflineCourseInfo oci = getOfflineCourse.vOfflineCourseInfo[i];
			ui->tablewt_examList->setItem(i, 0, new QTableWidgetItem(oci.sCourseName));
			ui->tablewt_examList->setItem(i, 1, new QTableWidgetItem(oci.sSpecialtyName));
			ui->tablewt_examList->setItem(i, 2, new QTableWidgetItem(QString::fromLocal8Bit("%1 ~ %2").arg(oci.sStartTime).arg(oci.sEndTime)));
            CL_OPERATION_TYPE sAnswerStatus = CL_OPERATION_TYPE::cot_offline_status_null;
			CL_OPERATION_TYPE otStatus = CL_OPERATION_TYPE::cot_offline_init_exam;
			if (!oci.sStatus.isEmpty())
			{
				otStatus = CL_OPERATION_TYPE::cot_offline_exam;
				if (oci.vOfflineFileInfo.size() > 0)
				{
                    sAnswerStatus = CL_OPERATION_TYPE::cot_offline_status_download;
				}				
			}
            clOperation *cloStatus = new clOperation(i, ui->tablewt_examList);
            connect(cloStatus, &clOperation::downloadOfflineAnswer, this, [&](int nRow){
                QString sExportDir = QFileDialog::getExistingDirectory(
                    this, QString::fromLocal8Bit("选择导出目录"),
                    "/");

                if (sExportDir.isEmpty())
                {
                    return;
                }

                //导出
                if (sExportDir.right(1) != "/")
                {
                    sExportDir += "/";
                }

                COfflineCourseInfo &oci = m_vOfflineCourseInfo[nRow];
                for (COfflineFileInfo &fileInfo : oci.vOfflineFileInfo)
                {
                    QString sFileName = fileInfo.sOfflineFileUrl.right(fileInfo.sOfflineFileUrl.length() - fileInfo.sOfflineFileUrl.lastIndexOf("/") - 1);
                    QString sAnswerFile = sExportDir + sFileName;
                    fileInfo.sLocalFileName = sAnswerFile;
                    CHttpRequestPackage hrp;
                    hrp.sUri = fileInfo.sOfflineFileUrl;
                    hrp.sCommonStr = sAnswerFile;
                    hrp.sAdditionStr = QString::number(nRow);
                    hrp.sCommonStr1 = __FILE__;
                    hrp.nRequestType = RequestType::rtDownLoadFile;
                    hrp.nRetryCount = 3;
                    g_httpBllPtr->downLoad(hrp);
                }
            });

            cloStatus->setUI(ui->tablewt_examList->columnWidth(4), ui->tablewt_examList->rowHeight(i), sAnswerStatus);
            ui->tablewt_examList->setCellWidget(i, 3, cloStatus);


			clOperation *clo = new clOperation(i, ui->tablewt_examList);
            connect(clo, &clOperation::offlineExamStart, this, [&](int nRow){
                COfflineCourseInfo oci = m_vOfflineCourseInfo[nRow];
				
				CHttpRequestPackage hrp;
				hrp.sUri = "/api/ecs_oe_admin/client/exam/process/startOfflineExam";
				hrp.sParamList.push_back(QString("examStudentId,%1").arg(oci.nExamStudentId));
				hrp.nRequestType = RequestType::rtStartOfflineExam;
				hrp.eParamType = HttpParamType::hptUrl;
				hrp.sCommonStr = QString::number(nRow);
				g_httpBllPtr->post(hrp);
            });

            connect(clo, &clOperation::viewOfflinePaper, this, [&](int nRow){
                COfflineCourseInfo oci = m_vOfflineCourseInfo[nRow];
				
				CHttpRequestPackage hrp;
				hrp.sUri = QString("/api/branch_ecs_ques/paper/%1").arg(oci.sPaperId);				
				hrp.nRequestType = RequestType::rtPreviewOffLineExamPaper;				
				hrp.sCommonStr = QString::number(nRow);
				g_httpBllPtr->get(hrp);
            });

            connect(clo, &clOperation::downloadOfflinePaper, this, [&](int nRow){
                COfflineCourseInfo oci = m_vOfflineCourseInfo[nRow];
								
//				QString sExportDir = QFileDialog::getExistingDirectory(
//                    this, QString::fromLocal8Bit("选择下载目录"),
//					"/");

//				if (sExportDir.isEmpty())
//				{
//					return;
//				}

//				//导出
//				if (sExportDir.right(1) != "/")
//				{
//					sExportDir += "/";
//				}

                QString sPaperFile = oci.sCourseCode + "_" + oci.sCourseName + ".zip";

                sPaperFile = QFileDialog::getSaveFileName(
                        this, oci.sPaperId, sPaperFile,
                        "All Files(*.*)");

                if(sPaperFile.isEmpty())
                {
                    return;
                }
				

				if (!QFile::exists(sPaperFile))
				{
					CHttpRequestPackage hrp;
					hrp.sUri = QString("/api/branch_ecs_ques/paper/export/%1/PAPER/offLine").arg(oci.sPaperId);
					hrp.nRequestType = RequestType::rtGetOffLineExamPaper;
					hrp.sCommonStr = sPaperFile;
					g_httpBllPtr->get(hrp);						
				}
				
            });

            connect(clo, &clOperation::uploadOfflineAnswer, this, [&](int nRow){
                COfflineCourseInfo oci = m_vOfflineCourseInfo[nRow];

				CHttpRequestPackage hrp;
				hrp.sUri = QString("/api/ecs_exam_work/exam/getExamPropertyFromCacheByStudentSession/%1/%2")
					.arg(oci.nExamId).arg("OFFLINE_UPLOAD_FILE_TYPE");
				hrp.nRequestType = RequestType::rtGetExamProperty;
				hrp.sCommonStr = "OFFLINE_UPLOAD_FILE_TYPE;" + QString::number(oci.nExamRecordDataId);
				g_httpBllPtr->get(hrp);								
            });

			clo->setUI(ui->tablewt_examList->columnWidth(4), ui->tablewt_examList->rowHeight(i), otStatus);
			ui->tablewt_examList->setCellWidget(i, 4, clo);
		}
        m_vOfflineCourseInfo.swap(getOfflineCourse.vOfflineCourseInfo);
	}
	else
	{
        if(getOfflineCourse.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取离线考试信息失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getOfflineCourse.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOfflineExam::onDownLoadFile(CDownLoadFileInfo downLoadFileInfo)
{
    if (downLoadFileInfo.sModuleName == __FILE__)
    {                        
        if(downLoadFileInfo.nCode == 200)
        {
            if(downLoadFileInfo.sAdditionStr == "downloadAnswerSheet")
            {
                ShowMsg(QString::fromLocal8Bit("下载完成"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_succeed);
            }
            else
            {
                int nRow = downLoadFileInfo.sAdditionStr.toInt();
                COfflineCourseInfo oci = m_vOfflineCourseInfo[nRow];
                QString sLocalFileName = oci.vOfflineFileInfo[oci.vOfflineFileInfo.size() - 1].sLocalFileName;

                if(sLocalFileName == downLoadFileInfo.sFileName)
                {
                    ShowMsg(QString::fromLocal8Bit("下载完成"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_succeed);
                }
            }
        }
        else
        {
            if(downLoadFileInfo.sMessage.isEmpty())
            {
                ShowMsg(QString::fromLocal8Bit("下载失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
            }
            else
            {
                ShowMsg(downLoadFileInfo.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
            }
        }
    }

//    downLoadFileInfo
//    QString sFileName = g_appInfoPtr->m_sStudentPhotoPath.right(g_appInfoPtr->m_sStudentPhotoPath.length() - g_appInfoPtr->m_sStudentPhotoPath.lastIndexOf("/") - 1);
//    QString sAudioFile = g_appInfoPtr->m_sCacheFileDir + "cache/" + sFileName;
//    if (downLoadFileInfo.sFileName == sAudioFile)
//    {
//        if (downLoadFileInfo.nCode == 200)
//        {
//            int nSecord = g_audioPalyerPtr->GetMediaDuration(sAudioFile);
//            m_nMaxTestSecord = nSecord;
//            QString sText = QString("00:00 / %1:%2")
//                    .arg((int)(nSecord/60), 2, 10, QChar('0'))
//                    .arg((int)(nSecord%60), 2, 10, QChar('0'));
//            ui->label_ap_time->setText(sText);
//        }
//        else
//        {

//        }
//    }
}

void clOfflineExam::onGetOffLineExamAnswerSheet(CGetOffLineExamAnswerSheet getOffLineExamAnswerSheet)
{
	if (getOffLineExamAnswerSheet.nCode == 200)
	{
		if (!getOffLineExamAnswerSheet.sAnswerSheetUrl.isEmpty())
		{
            m_sAnswerSheetUrl = getOffLineExamAnswerSheet.sAnswerSheetUrl;
			ui->btn_downloadAnswerSheet->setVisible(true);
		}
	}
	else
	{
        if(getOffLineExamAnswerSheet.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取离线考试信息失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getOffLineExamAnswerSheet.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOfflineExam::onStartOfflineExam(CStartOfflineExam startOfflineExam)
{
	if (startOfflineExam.nCode == 200)
	{
        refreshCourse();
//		int nRow = startOfflineExam.nRow;
//		COfflineCourseInfo &oci = m_vOfflineCourseInfo[nRow];
//		oci.sStatus = "EXAM_ING";
		
//		clOperation *op = dynamic_cast<clOperation*>(ui->tablewt_examList->cellWidget(nRow, 4));
//		if (op)
//		{
//			op->setOperationType(CL_OPERATION_TYPE::cot_offline_exam);
//		}

//		CHttpRequestPackage hrp;
//		hrp.sUri = QString("/api/branch_ecs_ques/paper/export/%1/PAPER/offLine").arg(oci.sPaperId);
//		hrp.nRequestType = RequestType::rtGetOffLineExamPaper;
//		hrp.sCommonStr = QString::number(nRow);
//		g_httpBllPtr->get(hrp);
	}
	else
	{
        if(startOfflineExam.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("离线考试开考失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(startOfflineExam.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOfflineExam::onGetOffLineExamPaper(CGetOffLineExamPaper getOffLineExamPaper)
{
	if (getOffLineExamPaper.nCode == 200)
	{
        ShowMsg(QString::fromLocal8Bit("下载试卷完成"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_succeed);
	}
	else
	{
        if(getOffLineExamPaper.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("离线考试下载试卷失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getOffLineExamPaper.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOfflineExam::onPreviewOffLineExamPaper(CPreviewOffLineExamPaper previewOffLineExamPaper)
{
	if (previewOffLineExamPaper.nCode == 200)
	{
		int nRow = previewOffLineExamPaper.nRow;		 
		if (m_pViewPaper == nullptr)
		{
			m_pViewPaper = std::make_shared<cloeViewPaper>(previewOffLineExamPaper.sUrl, (QWidget*)this->parent()->parent());
            connect(m_pViewPaper.get(), &cloeViewPaper::goback, this, [&](){
               m_pViewPaper.reset();
            });
		}
		if(nRow >= 0 && nRow < m_vOfflineCourseInfo.size())
		{
			COfflineCourseInfo oci = m_vOfflineCourseInfo[nRow];
			m_pViewPaper->setCourseCodeAndName(oci.sCourseCode, oci.sCourseName);
		}		
		m_pViewPaper->show();
	}
	else
	{
        if(previewOffLineExamPaper.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("离线考试下载试卷失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(previewOffLineExamPaper.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
	}
}

void clOfflineExam::onGetExamProperty(CGetExamProperty getExamProperty)
{
	if (getExamProperty.nCode == 200)
	{
		QStringList sList = getExamProperty.sType.split(";");
		if (sList.count() != 2)
		{
			return;
		}
		if (sList[0] == "OFFLINE_UPLOAD_FILE_TYPE")
		{
            if(m_pUploadFile == nullptr)
            {
                m_pUploadFile = std::make_shared<cloeUploadFile>(sList[1].toLongLong(), getExamProperty.vOfflineUploadFileType, (QWidget*)this->parent()->parent());
                connect(m_pUploadFile.get(), &cloeUploadFile::cancel, this, [&](){
                    m_pUploadFile.reset();
                });

				connect(m_pUploadFile.get(), &cloeUploadFile::uploadSucceed, this, [&]() {
					m_pUploadFile.reset();
				
					CHttpRequestPackage hrp;
					hrp.sUri = "/api/ecs_oe_admin/client/exam/process/getOfflineCourse";
					hrp.nRequestType = RequestType::rtGetOfflineCourse;
					g_httpBllPtr->post(hrp);
				});
            }
            m_pUploadFile->show();
		}
	}
    else
    {
        if(getExamProperty.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("获取离线考试信息失败"), g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(getExamProperty.sMessage, g_appInfoPtr->m_pAnsBgWidget, MSG_ICON_TYPE::mit_error);
        }
    }
}


void clOfflineExam::on_btn_downloadAnswerSheet_clicked()
{
//    QString sExportDir = QFileDialog::getExistingDirectory(
//        this, QString::fromLocal8Bit("选择下载目录"),
//        "/");

//    if (sExportDir.isEmpty())
//    {
//        return;
//    }

//    //导出
//    if (sExportDir.right(1) != "/")
//    {
//        sExportDir += "/";
//    }

    QString sFileName = m_sAnswerSheetUrl.right(m_sAnswerSheetUrl.length() - m_sAnswerSheetUrl.lastIndexOf("/") - 1);
//    QString sAnswerFile = sExportDir + sFileName;
    QString sAnswerFile = QFileDialog::getSaveFileName(
            this, m_sAnswerSheetUrl, QFileInfo(sFileName).fileName(),
            "All Files(*.*)");

    if(sAnswerFile.isEmpty())
    {
        return;
    }

    CHttpRequestPackage hrp;
    hrp.sUri = m_sAnswerSheetUrl;
    hrp.sCommonStr = sAnswerFile;
    hrp.sAdditionStr = "downloadAnswerSheet";
    hrp.sCommonStr1 = __FILE__;
    hrp.nRequestType = RequestType::rtDownLoadFile;
    hrp.nRetryCount = 3;
    g_httpBllPtr->downLoad(hrp);
}
