#include "inprogressFace.h"

#include "logproc.h"
#include "CCommonTools.h"
#include "CFaceRecProc.h"
#include "CAppInfo.h"

std::shared_ptr<CInprogressFace> g_inProcessFace = nullptr;

CInprogressFace::CInprogressFace()
{
    m_bIsRun = true;
    m_thread = std::thread(std::bind(&CInprogressFace::threadProc, this));
}

CInprogressFace::~CInprogressFace()
{
    m_bIsRun = false;
    m_thread.join();
}

void CInprogressFace::startFaceVerify(bool bVerify)
{
    m_bStart = bVerify;
}

void CInprogressFace::addImage(cv::Mat matImage)
{
    if(m_bStart)
    {
        std::scoped_lock lock(m_mImgList);
        m_vImgList.push_back(matImage);
        qDebug()<<"add image"<<m_vImgList.size();
    }
}

void CInprogressFace::threadProc()
{
	if (g_faceRecProcPtr == nullptr)
	{
		g_faceRecProcPtr = std::make_shared<CFaceRecProc>();

		if (!g_appInfoPtr->m_sStudentPhotoPath.isEmpty())
		{
			QString sFileName = g_appInfoPtr->m_sStudentPhotoPath.right(g_appInfoPtr->m_sStudentPhotoPath.length() - g_appInfoPtr->m_sStudentPhotoPath.lastIndexOf("/") - 1);
			sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
			if (!QFile::exists(sFileName))
			{
				emit compareFailed(QString::fromLocal8Bit("底照下载失败，请检查网络"));
				return;
			}
			
			g_faceRecProcPtr->setBaseImage(sFileName);
		}
		else
		{
			emit compareFailed(QString::fromLocal8Bit("当前考试未底照"));
			return;
		}
	}

    while(m_bIsRun)
    {
        if(m_bStart)
        {
            if(m_vImgList.begin() != m_vImgList.end())
            {                

                cv::Mat matImage;
                {
                    std::scoped_lock lock(m_mImgList);

                    matImage = (*m_vImgList.begin()).clone();
                    m_vImgList.erase(m_vImgList.begin());
                }

                if(matImage.empty())
                {
                    myDebug()<<"matImage.empty";
                    continue;
                }

                int nFaceCount = 0;
                float fScore = 0;
                bool bRealness = false;
                int nTime = 0;
                if(!g_faceRecProcPtr->getMaxFaceScoreWithBase(matImage, nFaceCount, fScore, bRealness, nTime))
                {
                    //比对失败
                    QString sErrorMsg = g_faceRecProcPtr->errorMsg();
                    uploadFile(matImage, nFaceCount, fScore, bRealness);
                    emit compareFailed(sErrorMsg);
                }
                else
                {
                    if(nFaceCount == 0)
                    {
                        //无人脸
                        uploadFile(matImage, nFaceCount, fScore, bRealness);
                        emit compareFailed(QString::fromLocal8Bit("请让我看到您的正脸"));
                    }
                    else if(nFaceCount > 1 && g_appInfoPtr->m_oExamInfo.bIsStrangerEnable)
                    {
                        //陌生人
                        uploadFile(matImage, nFaceCount, fScore, bRealness);
                        emit compareFailed(QString::fromLocal8Bit("检测到陌生人"));
                    }
                }


            }
        }
        else
        {
            Sleep(100);
        }
    }
}

void CInprogressFace::uploadFile(cv::Mat faceMat, int nFaceCount, float fScore, int nRealness)
{
    QString sFileName = QString("temp/photo/%1.png").arg(CCommonTools::getUuid());
    QImage imgCompare = CCommonTools::Mat2QImage(faceMat);
    imgCompare.save(sFileName, "PNG");

    CHttpRequestPackage hrp;
    hrp.sUri = "/api/ecs_oe_student/client/exam/process/upload";
    hrp.nRequestType = RequestType::rtProcessUpload;
    hrp.sParamList.push_back(QString("formdataFileType,file,%1").arg(sFileName));
    hrp.sParamList.push_back(QString("md5,%1").arg(CCommonTools::fileMd5(sFileName)));
    hrp.sCommonStr = QString("%1,%2,%3").arg(nFaceCount).arg(fScore).arg(nRealness);
    hrp.eParamType = HttpParamType::hptFormdata;
    g_httpBllPtr->post(hrp);
}

//文件上传
void CInprogressFace::onProcessUpload(CProcessUpload processUpload)
{
    if(processUpload.nCode == 200)
    {
        QStringList list = processUpload.sCommonStr.split(",");
        if(list.count() == 3)
        {
            int nFaceCount = list[0].toInt();
            float fScore = list[1].toFloat();
            int nRealness = list[2].toInt();
            CHttpRequestPackage hrp;
            hrp.sUri = "/api/ecs_oe_student/client/exam/process/saveFaceCaptureResult";
            hrp.nRequestType = RequestType::rtSaveFaceCaptureResult;
            Json::Value jBody = Json::Value::null;
            jBody["faceCompareResult"] = fScore;
            jBody["facelivenessResult"] = nRealness;
            jBody["fileUrl"] = processUpload.sFileUrl.toStdString();
            jBody["pass"] = false;
            jBody["stranger"] = nFaceCount > 1;
            hrp.sParamList.push_back(QString("CustomBody,%1").arg(jBody.toStyledString().c_str()));
            hrp.eParamType = HttpParamType::hptCustomBody;

            g_httpBllPtr->post(hrp);
        }
    }
    else
    {

    }
}


//保存人脸抓拍比对验证结果
void CInprogressFace::onSaveFaceCaptureResult(CBaseResponsePackage res)
{
    if(res.nCode == 200)
    {

    }
    else
    {

    }
}
