#include "cserialportinterface.h"
#include <QApplication>
#include "readconfig.h"
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QDebug>
#include <QDateTime>
#include "languagemanager.h"

//#pragma execution_character_set("utf-8")

CSerialportInterface::CSerialportInterface():m_serialPort(NULL)
{
    receiveArray.clear();
    if(!m_serialPort)
    {
        m_serialPort = new QSerialPort();
        connect(m_serialPort,&QSerialPort::readyRead,this,&CSerialportInterface::receiveDataInterface);
        connect(m_serialPort,&QSerialPort::errorOccurred,this,&CSerialportInterface::displayError);
        setConfigParam();
    }
    m_blockTimer = new QTimer();

    m_blockTimer->setInterval(1000);
    //connect(m_blockTimer,SIGNAL(timeout()),this,SLOT(slotHandleTimeout()));
    connect(m_blockTimer,&QTimer::timeout,this,[=]
            {
                qDebug()<<"Hello";  //串口都没有哪来的jiekou
                if(!m_serialPort->isOpen())
                {
                    setConfigParamSerialError();
                    qDebug()<<"串口重新打开失败";
                }
                else
                {
                    qDebug()<<"串口重新打开成功";
                    m_blockTimer->stop();
                    displayError(QSerialPort::NoError);
                }
            });
}
CSerialportInterface::~CSerialportInterface()
{
    if(m_serialPort)
    {
        delete m_serialPort;
        m_serialPort = NULL;
    }
}
//配置参数
bool CSerialportInterface::setConfigParam()
{
    m_serialPort->close();
    ST_SerialPortConfig st_SerialConfig;
    if(!ReadConfig::getInstance()->getSerialPortConfig(st_SerialConfig))
    {
        QMessageBox::warning(NULL,tr("警告"),tr("获取串口配置失败"),QMessageBox::Retry);
        return false;
    }

    QSerialPortInfo m_SerialPortInfo;
    QStringList serialPortNames;
#if 0
    foreach(m_SerialPortInfo,QSerialPortInfo::availablePorts())
    {
        QSerialPort serialport;
        serialport.setPort(m_SerialPortInfo);

        if(serialport.open(QIODevice::ReadWrite))
        {
            serialPortNames.append(m_SerialPortInfo.portName());
            serialport.close();
        }
    }
    if(serialPortNames.isEmpty())
    {
        QMessageBox::warning(NULL,tr("警告"),tr("无可用串口"),QMessageBox::Retry);
        return false;
    }
#endif
    if(m_serialPort)
    {
        m_serialPort->setPortName(st_SerialConfig.portName);
        m_serialPort->setReadBufferSize(200);
        if(m_serialPort->open(QIODevice::ReadWrite))
        {
            m_serialPort->setBaudRate(st_SerialConfig.baud);
            m_serialPort->setDataBits(QSerialPort::Data8);
            m_serialPort->setParity(QSerialPort::NoParity);
            m_serialPort->setStopBits(QSerialPort::OneStop);
            m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
        }
        else
        {
            E_LANGUAGE language = LanguageManager::getInstance()->getCurrentLanguage();
            if(language == Chinese_E)
                QMessageBox::warning(NULL,tr("警告"),tr("串口打开失败"),QMessageBox::Retry);
            else //if(language == English_E)
                QMessageBox::warning(NULL,tr("Warning"),tr("Failed to open the serial port"),QMessageBox::Retry);
            qDebug() <<"current language index:"<< language;
            //QMessageBox::warning(NULL,tr("警告"),tr("串口打开失败"),QMessageBox::Retry);

            return false;
        }
    }

    return true;
}
//发送数据接口
void CSerialportInterface::sendDataInterface(QByteArray sendArray)
{
    if(m_serialPort)
    {
        if(m_serialPort->isOpen())
        {
            m_serialPort->write(sendArray);
            // qDebug()<<"send"<<sendArray.toHex();


            //qDebug() <<"发送时间:"<< QDateTime::currentDateTime();


        }
        else
        {
//            qDebug()<<tr("串口已关闭");
        }

    }
}
//接收数据接口
void CSerialportInterface::receiveDataInterface()
{
    QByteArray buf;
    buf = m_serialPort->readAll();
    receiveArray.append(buf);

    while(!receiveArray.isEmpty())
    {
        if(receiveArray[0] != (char)SLAVEPACKHEAD)
        {
            receiveArray.remove(0,1);
        }
        else
        {
            //获取有效数据长度
            uint8_t datalen = 0;
            memcpy(&datalen,receiveArray.constData()+1,sizeof(uint8_t));

            if(receiveArray.length() >= datalen + 4)
            {
                //校验成功
                if((uint8_t)receiveArray[datalen+3] ==  SLAVEPACKTAIL)
                {
                    emit  signalReadyRead(receiveArray.mid(0,datalen + 4));
                   // qDebug()<<receiveArray.toHex();
                    receiveArray.remove(0,datalen + 4);
                }
                else //校验失败
                {
                    //方式1 丢弃本包
                    receiveArray.remove(0,datalen + 4);
                }
            }
            else    //数据不够,直接退出继续接收
                break;
        }
    }
}

void CSerialportInterface::displayError(QSerialPort::SerialPortError error)
{
    QString lastError("");
    switch(error)
    {
    case QSerialPort::NoError:
        lastError = "";
        break;
    case QSerialPort::DeviceNotFoundError:
        lastError = "DeviceNotFoundError";
        break;
    case QSerialPort::PermissionError:
        lastError = "PermissionError";
        break;
    case QSerialPort::OpenError:
        lastError = "OpenError";
        break;
    case QSerialPort::NotOpenError:
        lastError = "NotOpenError";
        break;
    case QSerialPort::WriteError:
        //lastError = "WriteError";

        handleSerialError(); //串口被拔了,重新检测串口
        break;
    case QSerialPort::ReadError:
        lastError = "ReadError";
        break;
    case QSerialPort::UnknownError:
        lastError = "UnknownError";
        break;
    default:
        break;
    }
    emit signalDisplayError(lastError);
}

void CSerialportInterface::handleSerialError()
{

    m_blockTimer->start();

    qDebug() <<"定时器开始运行";
    setConfigParam();
}

//解析数据
void CSerialportInterface::analysisProtocal(QByteArray)
{

}



//配置参数
bool CSerialportInterface::setConfigParamSerialError()
{
    m_serialPort->close();
    ST_SerialPortConfig st_SerialConfig;
    if(!ReadConfig::getInstance()->getSerialPortConfig(st_SerialConfig))
    {
        QMessageBox::warning(NULL,tr("警告"),tr("获取串口配置失败"),QMessageBox::Retry);
        return false;
    }

    QSerialPortInfo m_SerialPortInfo;
    QStringList serialPortNames;
#if 0
    foreach(m_SerialPortInfo,QSerialPortInfo::availablePorts())
    {
        QSerialPort serialport;
        serialport.setPort(m_SerialPortInfo);

        if(serialport.open(QIODevice::ReadWrite))
        {
            serialPortNames.append(m_SerialPortInfo.portName());
            serialport.close();
        }
    }
    if(serialPortNames.isEmpty())
    {
        QMessageBox::warning(NULL,tr("警告"),tr("无可用串口"),QMessageBox::Retry);
        return false;
    }
#endif
    if(m_serialPort)
    {
        m_serialPort->setPortName(st_SerialConfig.portName);
        m_serialPort->setReadBufferSize(200);
        if(m_serialPort->open(QIODevice::ReadWrite))
        {
            m_serialPort->setBaudRate(st_SerialConfig.baud);
            m_serialPort->setDataBits(QSerialPort::Data8);
            m_serialPort->setParity(QSerialPort::NoParity);
            m_serialPort->setStopBits(QSerialPort::OneStop);
            m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
        }
        /*else
        {
            QMessageBox::warning(NULL,tr("警告"),tr("串口打开失败"),QMessageBox::Retry);
            return false;
        }*/
    }

    return true;
}