#include "com_1.h"
#include "ui_com_1.h"

com_1::com_1(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::com_1)
{
    ui->setupUi(this);
    SerRefresh();
    on_port_refresh_VT_clicked();
    ui->port_list_VT->setCurrentIndex(1);
    connect(ui->port_refresh,&QPushButton::clicked,this,&com_1::SerRefresh);
    connect(ui->listWidget,&QListWidget::doubleClicked,this,&com_1::on_BuletoothOnlineList_doubleClicked);
    connect(&roll_time,&QTimer::timeout,this,&com_1::roll);
}

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

void com_1::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == bluetoothinfoupdata)
    {
        for(int i = 0; i < ui->listWidget->count() ;i ++)
        {
            ui->listWidget->item(BluetoothGetTheQListIndex(GetBluetoothMAC(i)))->setText(BluetoothGetShowString(GetBluetoothMAC(i)));
        }
    }
}

void com_1::SerOpen(int data)
{
    if(data == 115200)
    {
        if(com_BT.isOpen())
        {
            com_BT.close();
            return;
        }
        com_BT.setBaudRate(QSerialPort::Baud115200);
        com_BT.setDataBits(QSerialPort::Data8);
        com_BT.setParity(QSerialPort::NoParity);
        com_BT.setStopBits(QSerialPort::OneStop);
        com_BT.setPortName(ui->port_list->currentText());
        com_BT.open(QIODevice::ReadWrite);
        connect(&com_BT,&QSerialPort::readyRead,[=](){BT_port_read_timer.start(25);});
        connect(&BT_port_read_timer,&QTimer::timeout,this,&com_1::BT_port_read);
    }

    if(data == 9600)
    {
        if(com_VT.isOpen())
        {
            com_VT.close();
            return;
        }
        com_VT.setBaudRate(QSerialPort::Baud9600);
        com_VT.setDataBits(QSerialPort::Data8);
        com_VT.setParity(QSerialPort::NoParity);
        com_VT.setStopBits(QSerialPort::OneStop);
        com_VT.setPortName(ui->port_list_VT->currentText());
        com_VT.open(QIODevice::ReadWrite);
        connect(&com_VT,&QSerialPort::readyRead,this,&com_1::VT_port_read);
    }
}

void com_1::SerRefresh()
{
    ui->port_list->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->port_list->addItem(info.portName());
    }
}

void com_1::on_port_open_clicked()
{
    if(ui->port_list->currentText() == ui->port_list_VT->currentText())
    {
        QMessageBox::information(this,"错误！！！","蓝牙串口COM口与虚拟串口COM口相同，请重新选择",QMessageBox::Ok);
        return;
    }
    if(com_BT.isOpen())
    {
        com_BT.close();
        ui->port_open->setText("打开串口");
        ui->port_state->setText("串口未连接");
        ui->port_refresh->setEnabled(true);
        ui->port_list->setEnabled(true);
        return;
    }
    else
    {
        if(ui->port_list->count() == 0)
        {
            QMessageBox::information(this,"错误！！！","请先点击刷新串口",QMessageBox::Ok);
            return;
        }
        ui->port_open->setText("关闭串口");
        ui->port_state->setText("串口已连接");
        ui->port_refresh->setEnabled(false);
        ui->port_list->setEnabled(false);
        BT_port_open_work();
    }
}

void com_1::BT_port_open_work()
{
    if(com_BT.isOpen())
    {
        QTimer::singleShot(10,[=](){com_BT.write(GetSendAtCommand("AT+AUTOCONN_ENABLE=0"));});

        QTimer::singleShot(20,[=](){com_BT.write(GetSendAtCommand("AT+SHUTDOWN"));});

        if(bluetoothinfoupdata)killTimer(bluetoothinfoupdata);

        ui->port_open->setEnabled(false);

        QTimer::singleShot(1000,[=]()
                           {
                               SerOpen(115200);
                           });
        return;
    }

    SerOpen(115200);

    if(com_BT.isOpen())
    {
        ClearTheBuletoothOnlineDeciveQmap();        //BluetoothOnlineMan.clear();

        ui->listWidget->clear();
        ui->BT_state->setText("正在搜索附近蓝牙");
        bluetoothinfoupdata = startTimer(500);
        com_BT.write(GetSendAtCommand("AT+SHUTDOWN"));
        QTimer::singleShot(1000,[=](){com_BT.write(GetSendAtCommand("AT+START_SCAN=1"));});
        QTimer::singleShot(1100,[=](){com_BT.write(GetSendAtCommand("AT+SCAN_RES=3"));});
        QTimer::singleShot(1200,[=](){com_BT.write(GetSendAtCommand("AT+AUTOCONN_ENABLE=0"));});
    }
}

void com_1::BT_port_read()
{
    BT_port_read_timer.stop();
    if(!com_BT.isOpen())
    {
        return;
    }
    QByteArray port_read_buffer= com_BT.readAll();
    if(port_read_buffer.isEmpty())
    {
        qDebug()<<"串口无返回数据";
        return;
    }
    QString BT_str = port_read_buffer.toHex();
    ui->plainTextEdit->insertPlainText("【" + QDateTime::currentDateTime().toString("hh:mm:ss zzz(yyyy-MM-dd)") + "】" + " [已接收]: " + BT_str + "\n");
    fmt.setUnderlineColor("blue");
    com_VT.write(port_read_buffer);
//    qDebug()<<QDateTime::currentDateTime().toString("hh:mm:ss zzz(yyyy-MM-dd)")<<port_read_buffer;
    if(ui->BT_state->text() == "正在搜索附近蓝牙")
    {
        BluetoothReceiveDataDeal(port_read_buffer);
//        qDebug()<<QDateTime::currentDateTime().toString("hh:mm:ss zzz(yyyy-MM-dd)")<<port_read_buffer;
        return;
    }
}

void com_1::BluetoothReceiveDataDeal(QByteArray data)
{
    QByteArray CommandContent;

    int MeetTheAtCommand = 0;

    QByteArray NeedInsertData;

    while(!BulueQueueIsEmty(&BLQ))
    {
        NeedInsertData.append(BulueQueue_out_data(&BLQ));
    }

    if(!NeedInsertData.isEmpty())
    {
        data.insert(0,NeedInsertData);
    }

    for(int i = 0; i <data.length();i ++)
    {
        if(data[i]=='A')
        {
            MeetTheAtCommand =1 ;
            CommandContent.append(data[i]);
        }
        else if(data[i]=='T'&&(MeetTheAtCommand==1))
        {
            MeetTheAtCommand =2 ;
            while((data[i]!='\r')||(data[i+1]!='\n'))
            {
                CommandContent.append(data[i]);
                if(i <data.length()-1)
                {
                   i++;
                }
                else
                {
                    if(BulueQueueIsBusy(&BLQ))
                    {
                        QMessageBox::information(this,"错误！！！","蓝牙名称存储过多，请重启",QMessageBox::Ok);
                        return;
                    }
                    else
                    {
                        for(int i = 0; i < CommandContent.length();i ++)
                        {
                          BulueQueue_in_data(&BLQ,CommandContent[i]);
                        }
                        QMessageBox::information(this,"错误！！！","产生断包数据，请重启",QMessageBox::Ok);
                        return;
                    }
                }
            }
            AtAnslysis(CommandContent);
//            qDebug()<<CommandContent;
            MeetTheAtCommand = 0 ;
            CommandContent.clear();
            i++;
        }
        else
        {
            QMessageBox::information(this,"警告！！！","AT指令集数据解析异常，请重启",QMessageBox::Ok);
            return;
        }
    }
}

void com_1::AtAnslysis(QByteArray str)
{
    if(QString(str) == "AT+OK")
    {
       qDebug()<<"蓝牙模块开启成功";
        return;
    }
    else   if(QString(str).contains("CON_SUCCESS") && (QString(str).contains("DISCON_SUCCESS")==false))
    {
        ui->BT_state->setText("蓝牙已连接");
        QMessageBox::information(this,"成功！！！","蓝牙连接成功，可以读取数据",QMessageBox::Ok);
        ui->plainTextEdit->clear();
        return;
    }
    int i =0;
    QByteArray tem_athead;
    for(;((i<str.length())&& (str[i] != '+'));i ++)
    {
       tem_athead.append(str[i]);
    }
    if(i < str.length()){i ++;}else{return;}//remove+
    QByteArray temATContent;
    for(;((i<str.length())&& (str[i] != '='));i ++)
    {
       temATContent.append(str[i]);
    }
    if((QString(temATContent) == "SCAN") || (QString(temATContent) == "BOARD"))
    {
        if(i < str.length()){i ++;}else{return;}//remove the =
        if(i < str.length()){i ++;}else{return;}//remove the 0
        if(i < str.length()){i ++;}else{return;}//remove the x
        QByteArray tem_MAC;
        for(;((i<str.length())&& (str[i] != '-'));i ++)
        {
            tem_MAC.append(str[i]);
        }

        QByteArray tem_Signal;
        for(;((i<str.length())&& (str[i] != ','));i ++)
        {
            tem_Signal.append(str[i]);
        }
        if((QString(temATContent) == "BOARD"))BluetoothSignalUpdata(tem_MAC,tem_Signal);
        if(i < str.length()){i ++;}else{return;}//  move  the ","

        if(BluetoothIsExist(tem_MAC))
        {
            int GetBluetoothMacRow = BluetoothGetTheQListIndex(tem_MAC);
            if(GetBluetoothMacRow == 255)
            {
                BluetoothAddTheQListIndex(tem_MAC,ui->listWidget->count());
                ui->listWidget->addItem(BluetoothGetShowString(tem_MAC));
            }
        }

        unsigned char LengthData;
        unsigned char TypeData;
        QByteArray ValueData;
        while(i < str.length())
        {
            LengthData =  str[i++];
            TypeData   =  str[i++];
            for(unsigned char j = 0; j < (LengthData-1); j++)
            {
                ValueData[j] = str[i++];
            }
            if(TypeData == 1)
            {//广播模式

            }
            else if(TypeData == 2)
            {// 16bit uuid

            }
            else if(TypeData == 6)
            {// 128bit uuid

            }
            else if(TypeData == 8 || TypeData == 9)
            {// 设备名称 Complete    local name
                QString ShowNameStatus;
                if(TypeData == 8)
                {
                    ShowNameStatus = "蓝牙名称(简洁): ";
                }
                else
                {
                    ShowNameStatus = "蓝牙名称(完整): ";
                }
                if(BluetoothScanDataDeal(tem_MAC,ValueData,ShowNameStatus))
                {
                    qDebug()<<"发现蓝牙-->MAC地址:"<<tem_MAC+ShowNameStatus+ValueData;
                }
                else
                {
                    if(BluetoothBoradNameIsChanged(tem_MAC,ValueData))
                    {
                      qDebug()<<"蓝牙名称发生变更-->产生变更的MAC地址为:"<<tem_MAC<<"新蓝牙名称为:"<<ValueData;
                    }
                }
            }
            else if(TypeData == 0XA)
            {// 发射功率: 0xXX: -127 to +127 dBm

            }
            else if(TypeData == 0X1A)
            {// 广播间隔

            }
            else if(TypeData == 0X1B)
            {// 设备地址

            }
            else if(TypeData == 0XFF)
            {// 厂商标识，用户可以自己任意填写内容。

            }
            else
            {
                qDebug()<<"接收到未定义广播关键字";
            }
            ValueData.clear();
        }
    }
}

void com_1::on_BuletoothOnlineList_doubleClicked(const QModelIndex &index)
{
    if(com_BT.isOpen() == false)
    {
        return;
    }

    if(QMessageBox::warning(this,"提示","是否连接此蓝牙:\n"+index.data().toString(),QMessageBox::Yes|QMessageBox::No) == QMessageBox::No)
    {
        return;
    }

    if(bluetoothinfoupdata)killTimer(bluetoothinfoupdata);

    com_BT.write(GetSendAtCommand("AT+SCAN_RES=0"));

//    QTimer::singleShot(10,[=]()
//                       {
//                            QByteArray SendCombin;

//                            SendCombin.append(QString("AT+CON_16=").toLocal8Bit()).append(GetBluetoothMAC(index.row())).append(QString(",FFD0").toLocal8Bit()).append('\r').append('\n');

//                            send(SendCombin);
//                       });

//    QTimer::singleShot(20,[=]()
//                       {
//                           send(GetSendAtCommand("AT+W_DCH=0,0"));
//                       });

//    QTimer::singleShot(25,[=]()
//                       {
//                            QByteArray SendCombinN;

//                            SendCombinN.append(QString("AT+CON_16=").toLocal8Bit()).append(GetBluetoothMAC(index.row())).append(QString(",FFF0").toLocal8Bit()).append('\r').append('\n');

//                            send(SendCombinN);
//                       });

//    QTimer::singleShot(30,[=]()
//                       {
//                            send(GetSendAtCommand("AT+R_DCH=0,1"));
//                       });

    QTimer::singleShot(40,[=]()
                       {
                           com_BT.write(GetSendAtCommand("AT+AUTOCONN_ENABLE=1"));
                       });
    QTimer::singleShot(50,[=]()
                       {
                            QByteArray SendCombinN;

                            SendCombinN.append(QString("AT+AUTOCONN=").toLocal8Bit()).append(GetBluetoothMAC(index.row())).append(QString(",FFD0").toLocal8Bit()).append('\r').append('\n');

                            com_BT.write(SendCombinN);
                       });
    QTimer::singleShot(60,[=]()
                       {
                            QByteArray SendCombinN;

                            SendCombinN.append(QString("AT+AUTOCONN=").toLocal8Bit()).append(GetBluetoothMAC(index.row())).append(QString(",FFF0").toLocal8Bit()).append('\r').append('\n');

                            com_BT.write(SendCombinN);
                       });
}

QByteArray com_1::GetSendAtCommand(QString str)
{
    QByteArray returndata;
    returndata = str.toLocal8Bit().append('\r').append('\n');
    return returndata;
}

void com_1::on_port_refresh_VT_clicked()
{
    ui->port_list_VT->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->port_list_VT->addItem(info.portName());
    }
}

void com_1::on_port_open_VT_clicked()
{
    if(ui->port_list->currentText() == ui->port_list_VT->currentText())
    {
        QMessageBox::information(this,"错误！！！","蓝牙串口COM口与虚拟串口COM口相同，请重新选择",QMessageBox::Ok);
        return;
    }
    if(com_VT.isOpen())
    {
        com_VT.close();
        ui->port_open_VT->setText("打开串口");
        ui->port_state_VT->setText("串口未连接");
        ui->port_refresh_VT->setEnabled(true);
        ui->port_list_VT->setEnabled(true);
        return;
    }
    else
    {
        if(ui->port_list_VT->count() == 0)
        {
            QMessageBox::information(this,"错误！！！","请先点击刷新串口",QMessageBox::Ok);
            return;
        }
        ui->port_open_VT->setText("关闭串口");
        ui->port_state_VT->setText("串口已连接");
        ui->port_refresh_VT->setEnabled(false);
        ui->port_list_VT->setEnabled(false);
        VT_port_open_work();
    }
}

void com_1::VT_port_open_work()
{
    if(com_VT.isOpen())
    {
        ui->port_open->setEnabled(false);
        return;
    }

    SerOpen(9600);
}

void com_1::VT_port_read()
{
    if(!com_VT.isOpen())
    {
        return;
    }
    QByteArray VT_port_read_buffer = com_VT.readAll();
    QString BT_str = VT_port_read_buffer.toHex();
    ui->plainTextEdit->insertPlainText("【" + QDateTime::currentDateTime().toString("hh:mm:ss zzz(yyyy-MM-dd)") + "】" + " [已发送]: " + BT_str + "\n");
    fmt.setUnderlineColor("green");
    qDebug()<<"虚拟串口写入数据:"<<VT_port_read_buffer;
    com_BT.write(VT_port_read_buffer);
}

void com_1::on_pushButton_clicked()
{
    roll_time.stop();
}

void com_1::on_pushButton_2_clicked()
{
    roll_time.start(100);
}

void com_1::roll()
{
    ui->plainTextEdit->moveCursor(QTextCursor::End);
}
