#include "cameracontrol.h"
#include <QDebug>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <time.h>
#include <conio.h>//getch()函数用
#include <QMessageBox>
#include "myhelper.h"
using namespace std;

//参数定义
static int iNum = 1; 	//车图片名称序号
static int pNum = 1;   //车牌图序号
string LineByLine;//逐行读取文件
string carNum;//车牌号
QString carNum1 = nullptr;
QString car_pic;
QString carplnum_pic;

//判断是否有车
bool IsSendCarPic = false;
CameraControl::CameraControl(QObject *parent) : QObject(parent)
{
    CarIsComingTimer = new QTimer;
    CarIsComingTimer->start(800);
    connect(CarIsComingTimer,&QTimer::timeout,this,[=](){
        //轮询是否有车辆进入识别区
        if(carNum1.isEmpty()){
            //无预警
            return;
        }
        if(!carNum1.isEmpty()){
            if(carNum1 == "无车牌"){
                //未识别到车牌，有车辆到来，语音提示；
                qDebug()<<"未识别到车牌，有车辆到来，语音提示；";
                emit SendToBridge_CarPic(car_pic,nullptr,nullptr);
            }else {
                //识别车牌成功，语音提示上磅；
                QString carPlnum = carNum1;
                qDebug()<<"carPlnum"<<carPlnum;
                //emit SendToBridge_CarPlnum(carPlnum);
                emit SendToBridge_CarPic(car_pic,carplnum_pic,carPlnum);
                //emit SendToBridge_CarPlnumPic(carplnum_pic);
            }
        }
        carNum1 = nullptr;
    });
}

BOOL CALLBACK MSesGCallback(LONG lCommand, NET_DVR_ALARMER *pAlarmer, char *pAlarmInfo, DWORD dwBufLen, void* pUser)
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString str_time = currentDateTime.toString("yyyyMMddhhmmss");
    string s_time = str_time.toStdString();
    DWORD i=0;
    char filename[100];
    FILE *fSnapPic=nullptr;
    FILE *fSnapPicPlate=nullptr;
    //以下代码仅供参考，实际应用中不建议在该回调函数中直接处理数据保存文件，
    //例如可以使用消息的方式(PostMessage)在消息响应函数里进行处理。
    switch (lCommand)
    {
    case COMM_ITS_PLATE_RESULT:
    {
        NET_ITS_PLATE_RESULT struITSPlateResult={0};
        memcpy(&struITSPlateResult, pAlarmInfo, sizeof(struITSPlateResult));
        string plateNum(struITSPlateResult.struPlateInfo.sLicense);
        QString str =QString::fromLocal8Bit(plateNum.c_str());
        carNum1 = str;
        if(carNum1!="无车牌"){
            carNum1 =  carNum1.right(carNum1.size()-1);
        }
        //qDebug()<<"车牌号:"<<carNum1;//车牌号
        for (i=0;i<struITSPlateResult.dwPicNum;i++)
        {
            if ((struITSPlateResult.struPicInfo[i].dwDataLen != 0)
                    &&
                    (struITSPlateResult.struPicInfo[i].byType==1)
                    ||
                    (struITSPlateResult.struPicInfo[i].byType == 2))
            {
                sprintf(filename,"C:\\AFrontPicture\\%s_%s_CarPic.jpg",plateNum.c_str(),s_time.c_str());
                car_pic = QString::fromLocal8Bit(filename);
                qDebug()<<"car_pic:"<<car_pic;
                fSnapPic=fopen(filename,"wb");
                fwrite(struITSPlateResult.struPicInfo[i].pBuffer, struITSPlateResult.struPicInfo[i].dwDataLen,1,fSnapPic);
                //iNum++;
                fclose(fSnapPic);

                //SendCarPic_True();
            }
            //车牌小图片
            if ((struITSPlateResult.struPicInfo[i].dwDataLen != 0)&&(struITSPlateResult.struPicInfo[i].byType == 0))
            {
                sprintf(filename,"C:\\AFrontPicture\\%s_%s_PlatePic.jpg",plateNum.c_str(),s_time.c_str());
                fSnapPicPlate=fopen(filename,"wb");
                carplnum_pic = QString::fromLocal8Bit(filename);
                qDebug()<<"carplnum_pic:"<<carplnum_pic;
                fwrite(struITSPlateResult.struPicInfo[i].pBuffer, struITSPlateResult.struPicInfo[i].dwDataLen, 1, \
                       fSnapPicPlate);
                fclose(fSnapPicPlate);
            }
            //其他信息处理......
            iNum++;
            ++pNum;
        }
        break;
    }
    default:
        break;
    }
}

long CameraControl::play(HWND hWnd, NET_DVR_PREVIEWINFO struPlayInfo, long userID)
{
    struPlayInfo={0};
    struPlayInfo.hPlayWnd = hWnd;//需要 SDK 解码时句柄设为有效值，仅取流不解码时可设为空
    struPlayInfo.lChannel = 1;//预览通道号
    struPlayInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-三码流，3-虚拟码流，以此类推
    struPlayInfo.dwLinkMode = 0;//0- TCP 方式，1- UDP 方式，2- 多播方式，3- RTP 方式，4-RTP/RTSP，5-RSTP/HTTP
    struPlayInfo.bBlocked = 1;//0- 非阻塞取流，1- 阻塞取流

    long IRealPlayHandle = NET_DVR_RealPlay_V40(userID,&struPlayInfo,NULL,NULL);

    if(IRealPlayHandle <0)
    {
        qDebug() << "NET_DVR_RealPlay_V40 error;error number " <<NET_DVR_GetLastError();
        myHelper::ShowMessageBoxError(QString::number(NET_DVR_GetLastError()));
        //QMessageBox::warning(NULL,"error","NET_DVR_RealPlay_V40 error;error number "+);
        NET_DVR_Logout(userID);
        userID=-1;
        return -1;
    }

    return IRealPlayHandle;
}

long CameraControl::setupAlarm()
{
    //设置报警回调函数
    char logInfo[128] = { 0 };
    NET_DVR_SetDVRMessageCallBack_V31(MSesGCallback,&userID);
    //启用布防
    NET_DVR_SETUPALARM_PARAM struSetupParam = { 0 };
    struSetupParam.dwSize = sizeof(NET_DVR_SETUPALARM_PARAM);
    struSetupParam.byLevel = 1; //布防优先级：0- 一等级（高），1- 二等级
    struSetupParam.byAlarmInfoType = 1; //上传报警信息类型: 0- 老报警信息(NET_DVR_PLATE_RESULT), 1- 新报警信息(NET_ITS_PLATE_RESULT)
    struSetupParam.byDeployType = 1;
    LONG lHandle = NET_DVR_SetupAlarmChan_V41(userID, &struSetupParam);
    if (lHandle < 0)
    {
        sprintf_s(logInfo, "Thread-Alarm-In 启用布防失败 %s,error,%d", userID, NET_DVR_GetLastError());
        isAlarm =false;
        return lHandle;
    }
    qDebug()<<"Thread-Alarm-In 启用布防成功"<< userID<<"error"<<NET_DVR_GetLastError();
    isAlarm =true;
    return lHandle;
}

bool CameraControl::initSDK()
{
    bool isok = NET_DVR_Init();
    if(isok == false)
    {
        qDebug()<< "NET_DVR_Init error;error number is " <<NET_DVR_GetLastError();
        QMessageBox::warning(NULL,"error","NET_DVR_Init error;error number is "+QString::number(NET_DVR_GetLastError()));
        return isok;
    }
    //设置连接时间与重连时间
    NET_DVR_SetConnectTime(2000, 1);
    NET_DVR_SetReconnect(10000, true);
    return isok;
}

bool CameraControl::uninitSDK()
{
    bool isok = NET_DVR_Cleanup();
    if(isok == false)
    {
        qDebug()<< "NET_DVR_Cleanup error;error number is " <<NET_DVR_GetLastError();
        QMessageBox::warning(NULL,"error","NET_DVR_Cleanup error;error number "+QString::number(NET_DVR_GetLastError()));
        return isok;
    }
    return isok;
}

void CameraControl::OnClickedLogin(QString ip, int port, QString user, QString pwd)
{
    initSDK();
    NET_DVR_DEVICEINFO_V30 DeviceInfoTmp;
    char * ipc = new char[strlen(ip.toStdString().c_str()) + 1];
    strcpy_s(ipc, strlen(ip.toStdString().c_str()) + 1, ip.toStdString().c_str());

    char * userc = new char[strlen(user.toStdString().c_str()) + 1];
    strcpy_s(userc, strlen(user.toStdString().c_str()) + 1, user.toStdString().c_str());

    char * pwdc = new char[strlen(pwd.toStdString().c_str()) + 1];
    strcpy_s(pwdc, strlen(pwd.toStdString().c_str()) + 1, pwd.toStdString().c_str());
    //NET_DVR_Login_V30(char *sDVRIP, WORD wDVRPort, char *sUserName, char *sPassword, LPNET_DVR_DEVICEINFO_V30 lpDeviceInfo);
    userID=NET_DVR_Login_V30(ipc,port,userc,pwdc,&DeviceInfoTmp);
    if(userID<0)
    {
        qDebug() << "NET_DVR_Login_V30 error;" << "error number is " << NET_DVR_GetLastError();
        QMessageBox::warning(NULL,"error","NET_DVR_Login_V30 error;error number "+QString::number(NET_DVR_GetLastError()));
        return;
    }
    qDebug()<<"车牌识别相机 Login Success,userID:" << userID<<endl;
    setupAlarm();
    emit SendToBridge_LoginOk();
}

void CameraControl::OnClickedLogout()
{

}
void CameraControl::OnClickedPreview()
{

}

void CameraControl::OnClickedStopPreview()
{

}

void CameraControl::OnClickedCapture()
{

}

void CameraControl::Picinfo(QByteArray ba)
{

}

void CameraControl::Get_PlateNum()
{

}

void CameraControl::Get_PlatePic()
{

}

void CameraControl::Get_CarPic()
{

}
