#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
#include <QDebug>
#include <QProcess>
#include <QSerialPort>
#include <QSerialPortInfo>
#include "sqliteassistant/sqliteassistant.h"
#include "myhelper.h"
#include <QRegExp>
#include "vehinfo.h"
extern QString DataBase_ServerIP;
extern QString DataBase_ServerProt;
extern QString DataBase_ComName;
extern QString DataBase_ComBund;

QString ServerIP = "ServerIP";
QString ServerProt = "ServerProt";
QString ComName = "ComName";
QString ComBund = "ComBund";
static QDateTime c_1;
static int timeFlag = 0;
;
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_Bridge = new Bridge();
    EPCUpDate();

    //dataUpDate();
    m_SoftBreath = new QTimer(this);
    m_systemTime = new QLabel();
    m_EPCstatus = new QLabel();
    m_EPCstatus->setText("射频读卡器状态");
    m_EPCstatus->setStyleSheet("background-color: rgb(255, 0, 0);");
    statusBar()->addPermanentWidget(m_EPCstatus);
    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)+"秒"+"--");
    });
    PubClicked();
    SoftStart();
    Windowsinit();

}

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

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    // 针对lbShow控件
    if (watched == ui->lab_title)
    {
        //判断双击事件
        if (event->type() == QEvent::MouseButtonDblClick)
        {
            // 双击显示
            ui->pbn_config->show();
            return true;
        }
        //判断单击事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            // 单击显示
            ui->pbn_config->hide();
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return QMainWindow::eventFilter(watched, event);
    }
}

void MainWindow::closeEvent(QCloseEvent *ev)
{
    int result = myHelper::ShowMessageBoxQuesion("确定要关闭了吗?");
    if (result == 1) {
        ev->accept();
    } else {
        ev->ignore();
    }
}

void MainWindow::Windowsinit()
{

    setWindowTitle("信湖矿产车辆ID管理");
    //setWindowIcon(QIcon(""));
    ui->lab_title->installEventFilter(this);    //注册事件
    ui->pbn_config->hide();
    ui->widget_title->setFixedHeight(this->height()/8);
    ui->groupBox->setVisible(false);
    ui->lineEdit_EPC->setReadOnly(true);
    ///车牌正则
    QRegExp iptext("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$");
    ///IP正则
    QRegExp iptext2("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
    QRegExp iptext3("^([0-9]|[1-9]\\d|[1-9]\\d{2}|[1-9]\\d{3}|[1-5]\\d{4}|6[0-4]\\d{3}|65[0-4]\\d{2}|655[0-2]\\d|6553[0-5])$");
    ui->lineEdit_CarPlnum->setValidator(new QRegExpValidator(iptext));
    ui->lineEdit_serverIP->setValidator(new QRegExpValidator(iptext2));
    ui->lineEdit_serverPort->setValidator(new QRegExpValidator(iptext3));
    //ui->comboBox_comName->addItems(getAvailablePort());
    ///显示首页
    ui->stackedWidget->setCurrentWidget(ui->page);
    QStringList baudList;   //波特率
    QStringList nameList;   //串口名
    // 波特率    //波特率默认选择下拉第三项：9600

    baudList<<"1200"<<"2400"<<"4800"<<"9600"
           <<"14400"<<"19200"<<"38400"<<"56000"
          <<"57600"<<"115200";
    nameList<<"COM1"<<"COM2"<<"COM3"<<"COM4"<<"COM5"<<"COM6"
           <<"COM7"<<"COM8"<<"COM9"<<"COM10"<<"COM11"<<"COM12"
          <<"COM13"<<"COM14"<<"COM15"<<"COM16"<<"COM17"<<"COM18";
    ui->comboBox_baudRate->addItems(baudList);
    ui->comboBox_comName->addItems(nameList);
    ui->lineEdit_serverIP->setText(DataBase_ServerIP);
    ui->lineEdit_serverPort->setText(DataBase_ServerProt);

    ui->comboBox_comName->setCurrentIndex(m_SqliteAssistant->Select_SystemConfigInfo(DataBase_ComName).toInt());
    ui->comboBox_baudRate->setCurrentIndex(m_SqliteAssistant->Select_SystemConfigInfo(DataBase_ComBund).toInt());
    ///快捷输入
    //1-10京津沪渝，桂蒙宁新藏，港澳，粤湘鄂冀豫，黑吉辽晋陕，青鲁苏皖浙，闽赣琼甘贵川，
    //ABCDEFGHJKLMNPQRSTUVWXYZ
    //0123456789
    //    ui->pushButton_1->setText("京");
    //    ui->pushButton_2->setText("津");
    //    ui->pushButton_3->setText("沪");
    //    ui->pushButton_4->setText("渝");
    //    ui->pushButton_5->setText("桂");
    //    ui->pushButton_6->setText("蒙");
    //    ui->pushButton_7->setText("宁");
    //    ui->pushButton_8->setText("新");
    //    ui->pushButton_9->setText("藏");
    //    ui->pushButton_10->setText("港");

    //    ui->pushButton_11->setText("澳");
    //    ui->pushButton_12->setText("粤");
    //    ui->pushButton_13->setText("湘");
    //    ui->pushButton_14->setText("鄂");
    //    ui->pushButton_15->setText("冀");
    //    ui->pushButton_16->setText("豫");
    //    ui->pushButton_17->setText("黑");
    //    ui->pushButton_18->setText("吉");
    //    ui->pushButton_19->setText("辽");
    //    ui->pushButton_20->setText("晋");

    //    ui->pushButton_21->setText("陕");
    //    ui->pushButton_22->setText("青");
    //    ui->pushButton_23->setText("鲁");
    //    ui->pushButton_24->setText("苏");
    //    ui->pushButton_25->setText("皖");
    //    ui->pushButton_26->setText("浙");
    //    ui->pushButton_27->setText("闽");
    //    ui->pushButton_28->setText("赣");
    //    ui->pushButton_29->setText("琼");
    //    ui->pushButton_30->setText("甘");

    //    ui->pushButton_31->setText("贵");
    //    ui->pushButton_32->setText("川");
    //    ui->pushButton_33->setText("0");
    //    ui->pushButton_34->setText("1");
    //    ui->pushButton_35->setText("2");
    //    ui->pushButton_36->setText("3");
    //    ui->pushButton_37->setText("4");
    //    ui->pushButton_38->setText("5");
    //    ui->pushButton_39->setText("6");
    //    ui->pushButton_40->setText("7");

    //    ui->pushButton_41->setText("8");
    //    ui->pushButton_42->setText("9");
    //    ui->pushButton_43->setText("A");
    //    ui->pushButton_44->setText("B");
    //    ui->pushButton_45->setText("C");
    //    ui->pushButton_46->setText("D");
    //    ui->pushButton_47->setText("E");
    //    ui->pushButton_48->setText("F");
    //    ui->pushButton_49->setText("G");
    //    ui->pushButton_50->setText("H");

    //    ui->pushButton_51->setText("I");
    //    ui->pushButton_52->setText("J");
    //    ui->pushButton_53->setText("K");
    //    ui->pushButton_54->setText("L");
    //    ui->pushButton_55->setText("M");
    //    ui->pushButton_56->setText("N");
    //    ui->pushButton_57->setText("O");
    //    ui->pushButton_58->setText("P");
    //    ui->pushButton_59->setText("Q");
    //    ui->pushButton_60->setText("R");

    //    ui->pushButton_61->setText("S");
    //    ui->pushButton_62->setText("T");
    //    ui->pushButton_63->setText("U");
    //    ui->pushButton_64->setText("V");
    //    ui->pushButton_65->setText("W");
    //    ui->pushButton_66->setText("X");
    //    ui->pushButton_67->setText("Y");
    //    ui->pushButton_68->setText("Z");
    //    ui->pushButton_69->setText("撤销");
    //    ui->pushButton_70->setText("清空");
    ui->lineEdit_EPC->setPlaceholderText("请将ID卡放到读卡器");
    ui->lineEdit_CarPlnum->setPlaceholderText("请输入车牌号");

}

void MainWindow::SoftStart()
{
    QDateTime time =QDateTime::currentDateTime();
    QString str=time.toString("yyyy-MM-dd hh:mm:ss");
    qDebug()<<"软件启动时间:"<<str;
    emit m_Bridge->SendToReadEPCControl_Connect();
    QString serIp =  m_SqliteAssistant->Select_SystemConfigInfo(ServerIP);
    QString serprot =  m_SqliteAssistant->Select_SystemConfigInfo(ServerProt);
    qDebug()<<"QtPing(serIp):"<<QtPing(serIp);
    if(!QtPing(serIp)){
        myHelper::ShowMessageBoxError(QString("服务器IP:%1异常,请检查服务器连接").arg(serIp));
        return;
    }
    emit m_Bridge->SendToTCPSocketHelper_Connect(serIp,serprot.toLong());
}

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

void MainWindow::EPCUpDate()
{
    connect(m_Bridge,&Bridge::SendToWindow,this,[=](QString data){
        if(data.isEmpty()){
            myHelper::ShowMessageBoxError("PEC读取错误");
            return ;
        }
        ui->lineEdit_EPC->setText(data);
    });
    connect(m_Bridge,&Bridge::SendReadEPCControlStyatusToWindow,this,[=](bool sta){
        qDebug()<<"win"<<sta;
        if(sta){
            m_EPCstatus->setStyleSheet("background-color: rgb(0, 255, 0);");
            return;
        }
        if(!sta){
            m_EPCstatus->setStyleSheet("background-color: rgb(255, 0, 0);");
            myHelper::ShowMessageBoxError("射频读卡器异常,请检查读卡器连接后重启软件");
            return;
        }
    });
    connect(this,&MainWindow::SendToBridge,m_Bridge,&Bridge::SendToTCPSocketHelper);
    connect(m_Bridge,&Bridge::SendBindingStatusToWindow,this,[=](bool status){
        if(!status){
            myHelper::ShowMessageBoxInfo("数据发送失败,请重新发送");
        }
    });
}

void MainWindow::PubClicked()
{
    connect(ui->pbn_Bind,&QPushButton::clicked,this,[=](){
        QString str = ui->lineEdit_CarPlnum->text();
        if(ui->lineEdit_EPC->text().isEmpty()){
            myHelper::ShowMessageBoxError("请检查射频识别卡是否正常");
            return ;
        }
        if(ui->lineEdit_CarPlnum->text().isEmpty()){
            myHelper::ShowMessageBoxError("请输入车牌号");
            return ;
        }
        //发送数据
        QString str_EPC = ui->lineEdit_EPC->text();
        QString str_CarPlnum = ui->lineEdit_CarPlnum->text();
        if(!m_SqliteAssistant->Insert_CarIDConfigInfo(str_CarPlnum,str_EPC)){
            PacketBinding from;
            from.plateNum = str_CarPlnum.toStdString();
            from.vehicleId = str_EPC.toStdString();
            emit SendToBridge(from);
            //myHelper::ShowMessageBoxInfo(QString("绑定成功车牌号为:%1").arg(str_CarPlnum));
            ui->lineEdit_EPC->clear();
            ui->lineEdit_CarPlnum->clear();
            ui->lineEdit_CarPlnum->setFocus();
        }else {
            myHelper::ShowMessageBoxInfo("绑定失败");
        }
    });
    connect(ui->pbn_config,&QPushButton::clicked,this,[=](){
        ui->stackedWidget->setCurrentWidget(ui->page_2);
    });
    connect(ui->pbn_cancel,&QPushButton::clicked,this,[=](){
        ui->pbn_config->hide();
        ui->stackedWidget->setCurrentWidget(ui->page);
    });
    connect(ui->pbn_sure,&QPushButton::clicked,this,[=](){
        if(ui->lineEdit_serverIP->text().isEmpty()){
            myHelper::ShowMessageBoxError("请完善服务器IP");
            return ;
        }
        if(ui->lineEdit_serverPort->text().isEmpty()){
            myHelper::ShowMessageBoxError("请完善服务器Prot");
            return ;
        }
        //配置暂存
        QString str_ServerIP = ui->lineEdit_serverIP->text();
        QString str_ServerProt= ui->lineEdit_serverPort->text();
        QString str_ComName = ui->comboBox_comName->currentText();
        QString str_ComBund = ui->comboBox_baudRate->currentText();
        //配置写入
        long a1 =  m_SqliteAssistant->Insert_SystemConfigInfo(ServerIP,str_ServerIP);
        long a2 =m_SqliteAssistant->Insert_SystemConfigInfo(ServerProt,str_ServerProt);
        long a3 =m_SqliteAssistant->Insert_SystemConfigInfo(ComName,str_ComName);
        long a4 =m_SqliteAssistant->Insert_SystemConfigInfo(ComBund,str_ComBund);
        if(!a1||!a2||!a3||!a4){
            myHelper::ShowMessageBoxInfo("配置保存成功,软件将退出,请重新启动软件");
            this->close();
        }
    });
}

bool MainWindow::QtPing(const QString ip)
{
    // #Linux指令 "ping -s 1 -c 1 IP"
    //QString cmdstr = QString("ping -s 1 -c 1 %1")
    //      .arg(ip);

    // #Windows指令 "ping IP -n 1 -w 超时(ms)"
    QString cmdstr = QString("ping %1 -n 1 -w %2")
            .arg(ip).arg(1000);

    QProcess cmd;
    cmd.start(cmdstr);
    cmd.waitForReadyRead(1000);
    cmd.waitForFinished(1000);

    QString response = cmd.readAll();
    if (response.indexOf("TTL") == -1)
    {
        return false;
    }
    else
    {
        return true;
    }
}

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;
}

//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;
//    }
//}
