#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QSerialPort>
#include <QSerialPortInfo>
#include "myhelper.h"
#include "bridge.h"
#include "sqliteassistant/sqliteassistant.h"
static QDateTime c_1;
static int timeFlag = 0;
QString m_selectVehPlnum = nullptr;

QString SerialNameCode = "SerialNameCode";
QString SerialBaudCode = "SerialBaudCode";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Bridge::GetInstance();
    SoftStart();
    //dataUpDate();
    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_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()->addPermanentWidget(m_Rfid);
    statusBar()->addPermanentWidget(m_ScanCode);
    statusBar()->addPermanentWidget(m_Trunk);
    statusBar()->addPermanentWidget(m_SportsCamera);
    statusBar()->addPermanentWidget(m_monitorCamera);
    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)+"秒"+"--");
    });
    init();
}

MainWindow::~MainWindow()
{
    delete m_systemTime;
    delete m_Rfid;
    delete m_ScanCode;
    delete ui;

}

void MainWindow::init()
{
    //设置整体布局
    setWindowTitle("信湖煤矿");
    ui->widget_title->setFixedHeight(this->height()/7);
    ui->lab_Title->setText("信湖煤矿——门禁系统");
    ui->widget_pbn->setFixedHeight(this->height()/7);
    ui->stackedWidget->setCurrentWidget(ui->page_1);
    ui->pbn_navigation_1->setFixedHeight(this->height()/10);
    ui->pbn_navigation_2->setFixedHeight(this->height()/10);
    ui->pbn_navigation_3->setFixedHeight(this->height()/10);
    ui->pbn_navigation_4->setFixedHeight(this->height()/10);
    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 comName;
    QStringList comBaud;
    comBaud<<"1200"<<"2400"<<"9600"<<"19200"<<"38400"<<"115200";
    //读取串口信息
//    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
//    {
//        // 自动读取串口号添加到端口portBox中
//        QSerialPort serial;
//        serial.setPort(info);
//        if(serial.open(QIODevice::ReadOnly))
//        {
//            comName<<info.portName();
//            serial.close();
//        }
//    }
    //串口名字
    ui->comboBox_serialNameRfid->addItems(comName);
    ui->comboBox_serialNameCode->addItems(comName);
    //串口波特率
    ui->comboBox_serialBaudCode->addItems(comBaud);
    ui->comboBox_serialBaudRfid->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);}");
    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;");

    //读取配置
    ReadSystemInfo();
    CheckAll();
}

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

void MainWindow::ReadSystemInfo()
{
    if(m_SqliteAssistant->Select_SystemConfigInfo(SerialNameCode).isEmpty()){
        myHelper::ShowMessageBoxError("请配置扫码器设置");
    }else {
        ui->comboBox_serialNameCode->setCurrentText(m_SqliteAssistant->Select_SystemConfigInfo(SerialNameCode));
        ui->comboBox_serialBaudCode->setCurrentText(m_SqliteAssistant->Select_SystemConfigInfo(SerialBaudCode));
    }

}

void MainWindow::CheckAll()
{
    emit Bridge::GetInstance()->SendToScanCodeControl_Start();
    if(!m_SqliteAssistant->Select_SystemConfigInfo(SerialNameCode).isEmpty()){
        //m_Bridge->SendToScanCodeControl_Connect(m_SqliteAssistant->Select_SystemConfigInfo(SerialNameCode),m_SqliteAssistant->Select_SystemConfigInfo(SerialBaudCode).toLong());
    }
}


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

void MainWindow::dataUpDate()
{
    if(timeFlag == 0){
        c_1 = QDateTime::currentDateTime();
        QTimer *timer = new QTimer(this);
        connect(timer,&QTimer::timeout,this,[=](){
            QDateTime c_2 = QDateTime::currentDateTime();
            m_systemTime->setText("系统累计运行时间--"+
                                  QString::number(c_1.msecsTo(c_2)/3600000)+":"+
                                  QString::number(c_1.msecsTo(c_2)%3600000/60000)+":"+
                                  QString::number(c_1.msecsTo(c_2)%60000/1000)+"--");
        });
        timer->start(1000);
        timeFlag = 1;
    }

    connect(Bridge::GetInstance()->m_ScanCodeControl,&ScanCodeControl::SendToBridge_ScanCodeData,this,[=](QString data){
        ui->lineEdit_Code_1->setText(data);
    });
    connect(Bridge::GetInstance()->m_ScanCodeControl,&ScanCodeControl::SendToBridge_ScanCodeDataisOk,this,[=](){
        m_ScanCode->setStyleSheet("QLabel{background-color: rgb(0,255,0);}");
    });
}

void MainWindow::Pbn_clicked()
{
    //导航键
    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,[=](){

    });
    connect(ui->pbn_urgent_4,&QPushButton::clicked,this,[=](){

    });
    connect(ui->pbn_urgent_5,&QPushButton::clicked,this,[=](){

    });
    //功能键
    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_2,&QPushButton::clicked,this,[=](){
        //扫码器配置
        m_SqliteAssistant->Insert_SystemConfigInfo(SerialNameCode,ui->comboBox_serialNameCode->currentText());
        m_SqliteAssistant->Insert_SystemConfigInfo(SerialBaudCode,ui->comboBox_serialBaudCode->currentText());
        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);
}
//软件配置事件
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);
    }
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    int result = myHelper::ShowMessageBoxQuesion("确定要关闭了吗?");
    if (result == 1) {
        //emit m_Bridge->CloseAllThread();
        SoftClose();
        event->accept();
    } else {
        event->ignore();
    }

}
