#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QMessageBox>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <windows.h>
#include "dbt.h"
#include "myhelper.h"

#include "sqliteassistant/sqliteassistant.h"
/**
 * 变量说明
 * 1
 * 2
 * 3
 * 4
 * 5
 * 6
 * 78*/
///信湖项目
extern QString DB_ServerIP;  //服务器IP
extern QString DB_ServerProt;

extern QString DB_HkIP;  //抓拍机IP
extern QString DB_HkProt;
extern QString DB_HkUser;
extern QString DB_HkPwd;

extern QString DB_RFIDComName;   //读卡器
extern QString DB_RFIDComBund;

extern QString DB_ScanComName;   //扫码器
extern QString DB_ScanComBund;

extern QString DB_HTrunkComName;   //道闸
extern QString DB_HTrunkComBund;

extern QString DB_HkVideoIP;  //监控机IP
extern QString DB_HkVideoProt;
extern QString DB_HkVideoUser;
extern QString DB_HkVideoPwd;

///信湖项目
static QDateTime c_1;
static int timeFlag = 0;
QString m_selectVehPlnum = nullptr;
//数据库配置Key
QString RFIDComName = "RFIDComName";
QString RFIDComBund = "RFIDComBund";

QString ScanComName = "ScanComName";
QString ScanComBund = "ScanComBund";

QString HkIP = "HkIP";
QString HkProt = "HkProt";
QString HkUser = "HkUser";
QString HkPwd = "HkPwd";

QString HTrunkComName = "HTrunkComName";
QString HTrunkComBund = "HTrunkComBund";

QString HkVideoIP = "HkVideoIP";
QString HkVideoProt = "HkVideoProt";
QString HkVideoUser = "HkVideoUser";
QString HkVideoPwd = "HkVideoPwd";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_Bridge = new Bridge();
    m_VoiceForm = new VoiceForm();
    dataUpDate();
    SoftStart();
    Pbn_clicked();
    m_SoftBreath = new QTimer(this);
    //状态栏显示内容
    m_systemTime = new QLabel();
    m_Rfid = new QLabel();
    m_ScanCode = new QLabel();
    m_Trunk = new QLabel();
    m_SportsCamera = new QLabel();
    m_monitorCamera = new QLabel();
    m_ServerStatus = new QLabel();

    m_carplnumPic = new QLabel(ui->lab_carPic);
    m_carplnumPic->move(10,10);
    m_carplnumPic->setFixedSize(224,80);
    m_carplnumPic->setText("        此处显示车牌图片");
    m_carplnumPic->setStyleSheet("	QLabel{border:1px solid #50A3F0;border-radius:5px;}");
    statusBar()->setFixedHeight(30);
    //this->setFont(QFont("Microsoft YaHei"));
    statusBar()->addPermanentWidget(m_Rfid);
    statusBar()->addPermanentWidget(m_ScanCode);
    statusBar()->addPermanentWidget(m_Trunk);
    statusBar()->addPermanentWidget(m_SportsCamera);
    statusBar()->addPermanentWidget(m_monitorCamera);
    statusBar()->addPermanentWidget(m_ServerStatus);
    statusBar()->addPermanentWidget(m_systemTime);
    m_SoftBreath->start(1000);
    connect(m_SoftBreath,&QTimer::timeout,this,[=](){
        //软件心跳
        m_SoftBreath_s = m_SoftBreath_s+1;
        if(m_SoftBreath_s>59){
            m_SoftBreath_s = 0;
            m_SoftBreath_m = m_SoftBreath_m + 1;
            if(m_SoftBreath_m>59){
                m_SoftBreath_m = 0;
                m_SoftBreath_h = m_SoftBreath_h+1;
            }
            if(m_SoftBreath_h>23){
                m_SoftBreath_h = 0;
                m_SoftBreath_d = m_SoftBreath_d + 1;
            }
        }
        m_systemTime->setText("系统累计运行时间--"+
                              QString::number(m_SoftBreath_d)+"天"+":"+
                              QString::number(m_SoftBreath_h)+"时"+":"+
                              QString::number(m_SoftBreath_m)+"分"+":"+
                              QString::number(m_SoftBreath_s)+"秒"+"--");
        //CheckComIsAlive();
    });

    connect(m_Bridge,&Bridge::SendToWindow,this,[=](QString data){
        if(data.isEmpty()){
            myHelper::ShowMessageBoxError("PEC读取错误");
            return ;
        }
        ui->lineEdit_Frid_1->setText(data);
    });
    connect(m_Bridge,&Bridge::SendToWindowRFIDStatus,this,[=](bool sta){
        qDebug()<<"win"<<sta;
        if(sta){
            m_Rfid->setStyleSheet("background-color: rgb(0, 255, 0);");
            ui->action_RFID->setEnabled(false);
            return;
        }
        if(!sta){
            m_Rfid->setStyleSheet("background-color: rgb(255, 0, 0);");
            myHelper::ShowMessageBoxError("射频读卡器异常,请检查读卡器连接后重启软件");
            ui->action_RFID->setEnabled(true);
            return;
        }
    });
    CheckAll();
    init();
}

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

long MainWindow::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();
        QMessageBox::warning(this,"error","NET_DVR_RealPlay_V40 error;error number "+QString::number(NET_DVR_GetLastError()));
        NET_DVR_Logout(userID);
        userID=-1;
        return -1;
    }

    return IRealPlayHandle;
}

void MainWindow::init()
{
    //设置整体布局
    setWindowTitle("信湖煤矿");
    ui->widget_title->setFixedHeight(this->height()/8);
    ui->lab_Title->setText("信湖煤矿——门禁系统");
    ui->widget_pbn->setFixedHeight(this->height()/10);
    //ui->stackedWidget->setFixedHeight(this->height()/10*9);
    ui->stackedWidget->setCurrentWidget(ui->page_1);
    ui->pbn_navigation_1->setFixedHeight(this->height()/8);
    ui->pbn_navigation_2->setFixedHeight(this->height()/8);
    ui->pbn_navigation_3->setFixedHeight(this->height()/8);
    ui->pbn_navigation_4->setFixedHeight(this->height()/8);
    ui->groupBox_frid->setFixedWidth(this->width()/3);
    ui->groupBox_scan->setFixedWidth(this->width()/3);
    ui->groupBox->setFixedWidth(this->width()/3);
    ui->groupBox_2->setFixedWidth(this->width()/3);
    //车辆黑白名单
    ui->tabWidget->setTabText(0,"车辆黑白名单管理");
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior ( QAbstractItemView::SelectRows);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableWidget->sortByColumn(0, Qt::AscendingOrder);
    //设置提示语
    ui->lineEdit_carPlnum->setPlaceholderText("请输入要查询的车牌号");
    //安装事件
    ui->lab_Title->installEventFilter(this);
    SetLineEdit(true);
    ui->spinBox_logKeepDays->setEnabled(false);
    ui->spinBox_logKeepDays->setMaximum(30);
    ui->spinBox_logKeepDays->setToolTip("日志最大保存天数30天");
    //获取串口
    QStringList comBaud;
    comBaud<<"1200"<<"2400"<<"4800"<<"9600"
          <<"14400"<<"19200"<<"38400"<<"56000"
         <<"57600"<<"115200";

    //串口名字
    ui->comboBox_RFIDComName->addItems(getAvailablePort());
    ui->comboBox_ScanComName->addItems(getAvailablePort());
    ui->comboBox_HTrunkComName->addItems(getAvailablePort());
    //串口波特率
    ui->comboBox_RFIDComBund->addItems(comBaud);
    ui->comboBox_ScanComBund->addItems(comBaud);
    ui->comboBox_HTrunkBund->addItems(comBaud);
    //设置状态栏的状态
    m_Rfid->setText("RFID读卡器状态");
    m_Rfid->setStyleSheet("QLabel{background-color: rgb(255,0,0);}");
    m_ScanCode->setText("二维码识别器状态");
    m_ScanCode->setStyleSheet("QLabel{background-color: rgb(255,0,0);}");
    m_Trunk->setText("道闸状态");
    m_Trunk->setStyleSheet("QLabel{background-color: rgb(255,0,0);}");
    m_SportsCamera->setText("抓拍机状态");
    m_SportsCamera->setStyleSheet("QLabel{background-color: rgb(255,0,0);}");
    m_monitorCamera->setText("监控机状态");
    m_monitorCamera->setStyleSheet("QLabel{background-color: rgb(255,0,0);}");
    m_ServerStatus->setText("服务器状态");
    m_ServerStatus->setStyleSheet("QLabel{background-color: rgb(255,0,0);}");
    QPixmap *pixmap = new QPixmap("E:\\ZYL_JM\\GitLab\\Git_JM_ACS\\JM_PRO\\QUI_MVC\\pic\\1.jpg");
    pixmap->scaled(ui->lab_carPic->size(),Qt::KeepAspectRatio);
    ui->lab_carPic->setScaledContents(true);
    ui->lab_carPic->setPixmap(*pixmap);
    QPixmap *pixmap1 = new QPixmap("E:\\ZYL_JM\\GitLab\\Git_JM_ACS\\JM_PRO\\QUI_MVC\\pic\\2.jpg");
    pixmap1->scaled(m_carplnumPic->size(),Qt::KeepAspectRatio);
    m_carplnumPic ->setScaledContents(true);
    m_carplnumPic->setPixmap(*pixmap1);
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);
    ui->lcdNumber->setStyleSheet("border:0px;");
    ui->pbn_urgent_4->setText("手动抓拍");
    ui->pbn_urgent_5->setText("抬起道闸");
    ui->pbn_urgent_6->setText("落下道闸");
    //读取配置
    ReadSystemInfo();

}

void MainWindow::SoftStart()
{
    QDateTime time =QDateTime::currentDateTime();
    QString str=time.toString("yyyy-MM-dd hh:mm:ss");
    qDebug()<<"软件启动时间:"<<str;
}

void MainWindow::ReadSystemInfo()
{
    //填写配置
    ui->lineEdit_HkIP->setText(DB_HkIP);
    ui->lineEdit_HkProt->setText(DB_HkProt);
    ui->lineEdit_HkUser->setText(DB_HkUser);
    ui->lineEdit_HkPwd->setText(DB_HkPwd);
    ui->lineEdit_HkIP_2->setText(DB_HkVideoIP);
    ui->lineEdit_HkProt_2->setText(DB_HkVideoProt);
    ui->lineEdit_HkUser_2->setText(DB_HkVideoUser);
    ui->lineEdit_HkPwd_2->setText(DB_HkVideoPwd);
}

void MainWindow::CheckAll()
{
    if(DB_RFIDComName.isEmpty()||DB_RFIDComBund.isEmpty()){
        myHelper::ShowMessageBoxError("请配置读卡器");
    }else {
        qDebug()<<"发送连接打卡器";
        //emit m_Bridge->SendToReadEPCControl_Connect(DB_RFIDComName,DB_RFIDComBund.toLong());
    }
    if(DB_ScanComName.isEmpty()||DB_ScanComBund.isEmpty()){
        myHelper::ShowMessageBoxError("请配置扫码器");
    }
    if(DB_HkIP.isEmpty()||DB_HkProt.isEmpty()||DB_HkUser.isEmpty()||DB_HkPwd.isEmpty()){
        myHelper::ShowMessageBoxError("请配置抓拍机");
    }

    //emit m_Bridge->SendToScanCodeControl_Start();
    //emit m_Bridge->SendToCameraControl_Login();
}

bool MainWindow::CheckComIsAlive()
{
    QSerialPort com1;
    com1.setPortName(DB_RFIDComName);
    qDebug()<<com1.isBreakEnabled();
    return false;
}


void MainWindow::SoftClose()
{
    QDateTime time =QDateTime::currentDateTime();
    QString str=time.toString("yyyy-MM-dd hh:mm:ss");
    qDebug()<<"软件关闭时间:"<<str;
}

void MainWindow::dataUpDate()
{
    //        connect(m_Bridge->m_ScanCodeControl,&ScanCodeControl::SendToBridge_ScanCodeData,this,[=](QString data){
    //            ui->lineEdit_Code_1->setText(data);
    //        });
    //        connect(m_Bridge->m_ScanCodeControl,&ScanCodeControl::SendToBridge_ScanCodeDataisOk,this,[=](){
    //            m_ScanCode->setStyleSheet("QLabel{background-color: rgb(0,255,0);}");
    //        });
    //            connect(m_Bridge->m_ScanCodeControl,&ScanCodeControl::SendToBridge_ScanCodeData,this,[=](QString data){
    //                ui->lineEdit_Code_1->setText(data);
    //            });
    connect(m_Bridge->m_EqptControl,&EqptControl::SendRFIDStatus,this,[=](bool sta){
        //外围设备状态
        if(sta){
            m_Trunk->setStyleSheet("QLabel{background-color: rgb(0,255,0);}");
            ui->action_HTrunk->setEnabled(false);
        }
    });

    connect(m_Bridge->m_CameraControl,&CameraControl::SendToBridge_LoginOk,this,[=](){
        //抓拍机状态
        m_SportsCamera->setStyleSheet("QLabel{background-color: rgb(0,255,0);}");
        ui->action_Snap->setEnabled(false);
    });
    connect(m_Bridge->m_CameraControl,&CameraControl::SendToBridge_CarPic,this,
            [=](QString data1,QString data2,QString data3){
        QPixmap *pixmap = new QPixmap(data1);
        pixmap->scaled(ui->lab_carPic->size(),Qt::KeepAspectRatio);
        ui->lab_carPic->setScaledContents(true);
        ui->lab_carPic->setPixmap(*pixmap);
        //
        if(!data2.isNull()){
            QPixmap *pixmap3 = new QPixmap(data2);
            pixmap3->scaled(m_carplnumPic->size(),Qt::KeepAspectRatio);
            m_carplnumPic->setScaledContents(true);
            m_carplnumPic->setPixmap(*pixmap3);
        }
        if(data2.isNull()){
            m_carplnumPic->setText("未检测到车牌");
        }
        ui->lineEdit_Frid_5->setText(data3);
    });

    connect(m_Bridge->m_HkVideoControl,&HkVideoControl::Send_UserID,this,[=](long num){
        //qDebug()<<"**********************"<<num;
        UserID = num;
        m_monitorCamera->setStyleSheet("QLabel{background-color: rgb(0,255,0);}");
    });
}

void MainWindow::Pbn_clicked()
{
    //系统按键
    connect(ui->action_RFID,&QAction::triggered,this,[=](){
        emit m_Bridge->SendToReadEPCControl_Connect(DB_RFIDComName,DB_RFIDComBund.toLong());
    });
    connect(ui->action_HTrunk,&QAction::triggered,this,[=](){
        //连接道闸
        emit m_Bridge->SendToEqptControl_Connect(DB_HTrunkComName,DB_HTrunkComBund.toLong());
    });
    connect(ui->action_Snap,&QAction::triggered,this,[=](){
        //连接抓拍机
        emit m_Bridge->SendToCameraControl_Connect(DB_HkIP,DB_HkProt.toInt(),DB_HkUser,DB_HkPwd);
    });
    connect(ui->action_Monitor,&QAction::triggered,this,[=](){
        //连接监控机
        emit m_Bridge->SendToHkVideoControl_Connect(DB_HkVideoIP,DB_HkVideoProt.toInt(),DB_HkVideoUser,DB_HkVideoPwd);
    });
    connect(ui->action_Voice,&QAction::triggered,this,[=](){
        //连接语音
        m_VoiceForm->show();
    });
    //导航键
    connect(ui->pbn_navigation_1,&QPushButton::clicked,this,[=](){
        ui->stackedWidget->setCurrentWidget(ui->page_2);
    });
    connect(ui->pbn_navigation_2,&QPushButton::clicked,this,[=](){
        ui->stackedWidget->setCurrentWidget(ui->page_3);
    });
    connect(ui->pbn_navigation_3,&QPushButton::clicked,this,[=](){
        ui->stackedWidget->setCurrentWidget(ui->page_4);
        ui->lineEdit_adminPwd->setFocus();
        ui->lineEdit_adminPwd->setText("jm123456");
    });
    connect(ui->pbn_navigation_4,&QPushButton::clicked,this,[=](){
        this->close();
    });
    //应急按键
    connect(ui->pbn_urgent_1,&QPushButton::clicked,this,[=](){
        //应急按键1手动保存车辆信息,查验三证是否齐全
        QString VehID = ui->lineEdit_Frid_1->text(); //FRID的车辆ID
        QString VehPlnum = ui->lineEdit_Frid_2->text(); //FRID的车辆车牌
        QString VehBusinessNum = ui->lineEdit_Code_1->text(); //二维码业务流水号

        if(VehID.isEmpty()){
            myHelper::ShowMessageBoxError("未识别到车辆ID");
        }
        if(VehPlnum.isEmpty()){
            myHelper::ShowMessageBoxError("未识别到车辆车牌号");
        }
        if(VehBusinessNum.isEmpty()){
            myHelper::ShowMessageBoxError("请检查车辆是否已扫码");
        }

        SetLineEdit(true);
    });
    connect(ui->pbn_urgent_2,&QPushButton::clicked,this,[=](){
        //应急按键2管理员手动填写车辆信息
        SetLineEdit(false);
    });
    connect(ui->pbn_urgent_3,&QPushButton::clicked,this,[=](){
        m_VoiceForm->sayVoice("当前厂区车辆过多,请等待");
    });
    connect(ui->pbn_urgent_4,&QPushButton::clicked,this,[=](){
        //手动抓拍
        emit m_Bridge->SendToEqptControl_SnapByHand();
    });
    connect(ui->pbn_urgent_5,&QPushButton::clicked,this,[=](){
        //抬起道闸
        emit m_Bridge->SendToEqptControl_HTrunkUp();
        statusBar()->showMessage("警告,手动抬杆请记录允许通过的车辆信息,以免造成损失",3000);
        myHelper::ShowMessageBoxInfo("请对手动抬杆的车辆做记录,以免造成损失");
        qDebug()<<"手动抬杆入场标记:车牌号:"<<ui->lineEdit_Frid_5->text()<<"车辆ID:"<<ui->lineEdit_Frid_1->text();
    });
    connect(ui->pbn_urgent_6,&QPushButton::clicked,this,[=](){
        //落下道闸
        emit m_Bridge->SendToEqptControl_HTrunkDown();
    });

    connect(ui->pbn_setVehTotal,&QPushButton::clicked,this,[=](){
        //设置厂区车辆
        VehTotal = ui->spinBox_VehTotal->value();
        myHelper::ShowMessageBoxInfo(QString("当前设置厂区容纳车辆: %1 辆").arg(QString::number(VehTotal)));
    });


    //监控按键
    connect(ui->pbn_Preview,&QPushButton::clicked,this,[=](){
        //开启预览
        ShowMessage("开启预览",3);
        ui->label_Video->clear();
        //HWND hWnd = ::FindWindowW(NULL,L"");
        HWND hWnd = (HWND)ui->label_Video->winId();
        //ui->label_video->setStyleSheet("QLabel#label_video{border: 1px solid rgb(0, 170, 255);border-radius: 10px;}");
        NET_DVR_PREVIEWINFO struPlayInfo;
        previewID = play(hWnd,struPlayInfo,UserID);
        if(previewID==-1)
        {
            return;
        }
        ui->label_Video->clear();
        ui->pbn_closePreview->setEnabled(true);
        ui->pbn_Preview->setEnabled(false);
    });
    connect(ui->pbn_closePreview,&QPushButton::clicked,this,[=](){
        //关闭预览
        if(previewID!=-1)
        {
            if(NET_DVR_StopRealPlay(previewID)==false)
            {
                qDebug() << "NET_DVR_StopRealPlay error;" << "error number is " << NET_DVR_GetLastError();
                QMessageBox::warning(this,"error","NET_DVR_StopRealPlay error;error number "+QString::number(NET_DVR_GetLastError()));
                return;
            }
            previewID=-1;
            //qDebug() <<"Stop Preview Success!"<<endl;
        }
        ui->pbn_closePreview->setEnabled(false);
        ui->pbn_Preview->setEnabled(true);
    });

    //功能键
    connect(ui->pbn_ToSetting,&QPushButton::clicked,this,[=](){
        QString adminPwd = ui->lineEdit_adminPwd->text();
        QString pwd = "jm123456";
        if(adminPwd == pwd){
            ui->stackedWidget->setCurrentWidget(ui->page_5);
            ui->lineEdit_adminPwd->clear();
        }else {
            myHelper::ShowMessageBoxError("管理员密码错误,请重新输入!");
            ui->lineEdit_adminPwd->clear();
            ui->lineEdit_adminPwd->setFocus();
        }
    });
    //查询车辆
    connect(ui->pbn_selectVeh,&QPushButton::clicked,this,[=](){
        QString adminPwd = ui->lineEdit_carPlnum->text();
        if(adminPwd.isEmpty()){
            //车牌判断
            myHelper::ShowMessageBoxError("请输入车牌号后查询");
        }else {
            //数据库操作
        }
    });
    //车辆信息表选择
    connect(ui->tableWidget,&QTableWidget::cellPressed,this,[=](int row,int column){
        //m_selectVehPlnum = ui->tableWidget->item(row,0)->text();
    });
    //设置受限车辆状态
    connect(ui->pbn_setVehLimit,&QPushButton::clicked,this,[=](){

        if(m_selectVehPlnum.isNull()){
            //车牌判断
            myHelper::ShowMessageBoxError("请选择要设置受限的车辆");
        }else {
            //数据库操作,判断是否已经是受限车辆,
            if(/* DISABLES CODE */ (true)){
                myHelper::ShowMessageBoxError("当前车辆已经受限,是否解除受限");
            }else {
                //数据库操作,添加受限
                myHelper::ShowMessageBoxInfo(QString("车牌为: %1添加受限成功").arg(m_selectVehPlnum));
            }
        }
    });
    //配置界面

    connect(ui->pbn_Setting_RFID,&QPushButton::clicked,this,[=](){
        //射频卡读卡器配置
        m_SqliteAssistant->Insert_SystemConfigInfo(RFIDComName,ui->comboBox_RFIDComName->currentText());
        if(m_SqliteAssistant->Insert_SystemConfigInfo(RFIDComBund,ui->comboBox_RFIDComBund->currentText())){
            myHelper::ShowMessageBoxInfo("读卡器配置已保存,重启后生效");
        }
    });
    connect(ui->pbn_Setting_Scan,&QPushButton::clicked,this,[=](){
        //扫码器配置
        m_SqliteAssistant->Insert_SystemConfigInfo(ScanComName,ui->comboBox_ScanComName->currentText());
        m_SqliteAssistant->Insert_SystemConfigInfo(ScanComBund,ui->comboBox_ScanComBund->currentText());
        myHelper::ShowMessageBoxInfo("扫码配置已保存,重启后生效");

    });
    connect(ui->pbn_Setting_HkSnap,&QPushButton::clicked,this,[=](){
        //抓拍机配置
        m_SqliteAssistant->Insert_SystemConfigInfo(HkIP,ui->lineEdit_HkIP->text());
        m_SqliteAssistant->Insert_SystemConfigInfo(HkProt,ui->lineEdit_HkProt->text());
        m_SqliteAssistant->Insert_SystemConfigInfo(HkUser,ui->lineEdit_HkUser->text());
        m_SqliteAssistant->Insert_SystemConfigInfo(HkPwd,ui->lineEdit_HkPwd->text());
        myHelper::ShowMessageBoxInfo("抓拍相机配置已保存,重启后生效");
    });
    connect(ui->pbn_Setting_HTrunk,&QPushButton::clicked,this,[=](){
        //道闸配置
        long a = m_SqliteAssistant->Insert_SystemConfigInfo(HTrunkComName,ui->comboBox_HTrunkComName->currentText());
        long b = m_SqliteAssistant->Insert_SystemConfigInfo(HTrunkComBund,ui->comboBox_HTrunkBund->currentText());
        if(!a&&!b){
            myHelper::ShowMessageBoxInfo("道闸配置已保存,重启后生效");

        }
    });

    connect(ui->pbn_Setting_HkVideo,&QPushButton::clicked,this,[=](){
        //监控机配置
        long a = m_SqliteAssistant->Insert_SystemConfigInfo(HkVideoIP,ui->lineEdit_HkIP_2->text());
        long b = m_SqliteAssistant->Insert_SystemConfigInfo(HkVideoProt,ui->lineEdit_HkProt_2->text());
        long c = m_SqliteAssistant->Insert_SystemConfigInfo(HkVideoUser,ui->lineEdit_HkUser_2->text());
        long d = m_SqliteAssistant->Insert_SystemConfigInfo(HkVideoPwd,ui->lineEdit_HkPwd_2->text());
        if(!a&&!b&&!c&&!d){
            myHelper::ShowMessageBoxInfo("监控机配置已保存,重启后生效");

        }
    });
    //日志保存
    connect(ui->rbn_logKeep_3,&QRadioButton::toggled,this,[=](bool click){
        if(click){
            ui->spinBox_logKeepDays->setEnabled(true);
        }
    });
    connect(ui->rbn_logKeep_2,&QRadioButton::toggled,this,[=](bool click){
        if(click){
            ui->spinBox_logKeepDays->setEnabled(false);
        }
    });
    connect(ui->rbn_logKeep_1,&QRadioButton::toggled,this,[=](bool click){
        if(click){
            ui->spinBox_logKeepDays->setEnabled(false);
        }
    });
}

void MainWindow::SetLineEdit(bool status)
{
    ui->lineEdit_Frid_1->setReadOnly(status);
    ui->lineEdit_Frid_2->setReadOnly(status);
    ui->lineEdit_Frid_3->setReadOnly(status);
    ui->lineEdit_Frid_4->setReadOnly(status);
    ui->lineEdit_Frid_5->setReadOnly(status);
    ui->lineEdit_Code_1->setReadOnly(status);
    ui->lineEdit_Code_2->setReadOnly(status);
    ui->lineEdit_Code_3->setReadOnly(status);
    ui->lineEdit_Code_4->setReadOnly(status);
    ui->lineEdit_Code_5->setReadOnly(status);
}

QStringList MainWindow::getAvailablePort()
{
    QStringList strName;
    foreach(const QSerialPortInfo& info, QSerialPortInfo::availablePorts())
    {
        QSerialPort port(info);
        if(port.open(QIODevice::ReadWrite))
        {
            strName << info.portName();
            port.close();
        }
    }
    return strName;
}

char *MainWindow::StrToChar(QString data)
{
    QString  str = data;
    char*  ch;
    QByteArray ba = str.toLatin1(); // 这一行不可少
    ch=ba.data();
    return ch;
}

void MainWindow::ShowMessage(QString msg, int time)
{
    statusBar()->showMessage(msg,time*1000);
}

//软件配置事件
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    // 针对lbShow控件
    if (watched == ui->lab_Title)
    {
        //判断双击事件
        if (event->type() == QEvent::MouseButtonDblClick)
        {
            // 双击显示
            ui->stackedWidget->setCurrentWidget(ui->page_6);
            return true;
        }
        //判断单击事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            // 单击显示
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return QMainWindow::eventFilter(watched, event);
    }
}

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);
    if(msg->message == WM_DEVICECHANGE)                // 通知应用程序设备或计算机的硬件配置发生更改。
    {
        PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
        //qDebug() << msg->wParam;
        switch (msg->wParam)
        {
        case DBT_DEVICEARRIVAL:             // 插入
        {
            if (lpdb->dbch_devicetype == DBT_DEVTYP_PORT)           // 设备类型为串口
            {
                PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
                QString strName = QString::fromWCharArray(lpdbv->dbcp_name);  //插入的串口名
                qDebug() << strName;
                //QApplication::beep();
            }
            break;
        }
        case DBT_DEVICEREMOVECOMPLETE:      // 拔出
        {
            if (lpdb->dbch_devicetype == DBT_DEVTYP_PORT)           // 设备类型为串口
            {
                PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
                QString strName = QString::fromWCharArray(lpdbv->dbcp_name);  //拔出的串口名
                if(strName == DB_RFIDComName){
                    m_Bridge->SendToReadEPCControl_Close(); //串口脱落,关闭串口
                    myHelper::ShowMessageBoxError("读卡器接头已脱落,请检查");
                }
                if(strName == DB_ScanComName){
                    myHelper::ShowMessageBoxError("扫码器接头已脱落,请检查");
                }

            }
            break;
        }
        default:
            break;
        }
    }

    return false;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    int result = myHelper::ShowMessageBoxQuesion("确定要关闭了吗?");
    if (result == 1) {
        //emit m_Bridge->CloseAllThread();
        SoftClose();
        event->accept();
    } else {
        event->ignore();
    }

}
