#include "fescontroldialog.h"
#include "ui_fescontroldialog.h"
#include <QMessageBox>
#include <QDebug>
#include <QSerialPortInfo>
#include "bleitem.h"
#include <QDir>
#include <QSettings>
#include "dbforrmate.h"
#include "cdatabaseinterface.h"
#include <QMessageBox>
#include "readconfig.h"
#include <QTimer>
#include <QPainter>
#include "languagemanager.h"

FesControlDialog* FesControlDialog::instance = nullptr;

FesControlDialog::FesControlDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FesControlDialog),
    m_serialPort(NULL),
    deviceConCount(0),
    connectTimer(NULL),
    E_fromFesType(ONLY_FES_E)
{
    ui->setupUi(this);

    //跟随主窗体关闭
    ui->queryDevice_Btn->setVisible(false);
    //ui->scanDevice_Btn->setVisible(false);

    setAttribute(Qt::WA_QuitOnClose,false);

    for(int i = 0;i< 4;i++)
    {
        deviceDtateArray[i] = 0;
        //m_batteryValue[i] = 0;
    }

    for(int i = 0;i< 4;i++)
        checkedMuscle_DeviceArray[i] = 0;

    connectTimer = new QTimer();
    connect(connectTimer,&QTimer::timeout,this,&FesControlDialog::slotConnectFes);

    addedDeviceList.clear();

    this->setWindowFlags(Qt::FramelessWindowHint);      //设置无边框
    setAttribute(Qt::WA_TranslucentBackground,true);    //设置透明

    initSerialPort();

    //ui->flushSerial_Btn->setVisible(false);
}

FesControlDialog::~FesControlDialog()
{
    qDebug()<<"~FesControlDialog()";
    delete ui;
}

FesControlDialog *FesControlDialog::getInstance()
{
    if(!instance)
        instance = new FesControlDialog();
    return instance;
}

bool FesControlDialog::initSerialPort()
{
    if(!m_serialPort)
    {
        m_serialPort = new QSerialPort();
        connect(m_serialPort,&QSerialPort::readyRead,this,&FesControlDialog::receiveDataInterface);
        connect(m_serialPort,&QSerialPort::errorOccurred,this,&FesControlDialog::displayError);
    }

    m_serialPort->close();
    QSerialPortInfo m_SerialPortInfo;
    QStringList serialPortNames;

    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())
    {
        ui->serial_ComboBox->clear();
        ui->serial_ComboBox->addItems(serialPortNames);
    }
    else
    {
        QMessageBox::warning(NULL,tr("警告"),tr("FES无可用串口"),QMessageBox::Retry);
        return false;
    }

    return true;
}

char FesControlDialog::getSum(QByteArray srcArray, int startIndex, int endIndex)
{
    if(srcArray==nullptr||srcArray.length()==0||startIndex>srcArray.length()||endIndex>srcArray.length()||startIndex>endIndex)
    {
        return static_cast<char>(0);
    }
    int iSum=0;
    for(int i=startIndex;i<=endIndex;i++)
    {
        iSum+=srcArray[i];
    }
    return static_cast<char>(iSum%256);
}

QByteArray FesControlDialog::createFrame(QByteArray dataBuffer)
{
    //创建数据包
    QByteArray buffer;
    buffer.append(static_cast<char>(FRAME_HEAD));
    buffer.append(static_cast<char>(dataBuffer.length()));
    for(int i=0;i<dataBuffer.length();i++)
    {
        buffer.append(dataBuffer.data()[i]);
    }
    buffer.append(getSum(buffer,2,buffer.length()-1));
    buffer.append(0x55);
    return  buffer;
}

void FesControlDialog::openSerialPort()
{
    if(m_serialPort)
    {
        m_serialPort->setPortName(ui->serial_ComboBox->currentText());
        m_serialPort->setReadBufferSize(200);
        if(m_serialPort->open(QIODevice::ReadWrite))
        {
            m_serialPort->setBaudRate(QSerialPort::Baud115200);
            m_serialPort->setDataBits(QSerialPort::Data8);
            m_serialPort->setParity(QSerialPort::NoParity);
            m_serialPort->setStopBits(QSerialPort::OneStop);
            m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
            ui->openSerial_Btn->setText("关闭");
        }
        else
        {
            QMessageBox::warning(NULL,tr("警告"),tr("串口打开失败"),QMessageBox::Retry);
        }
    }
}

bool FesControlDialog::openSeriaport(ST_SerialPortConfig st_serialParam)
{
    if(m_serialPort)
    {
        m_serialPort->setPortName(st_serialParam.portName);
        m_serialPort->setReadBufferSize(200);
        if(m_serialPort->open(QIODevice::ReadWrite))
        {
            m_serialPort->setBaudRate(QSerialPort::Baud115200);
            m_serialPort->setDataBits(QSerialPort::Data8);
            m_serialPort->setParity(QSerialPort::NoParity);
            m_serialPort->setStopBits(QSerialPort::OneStop);
            m_serialPort->setFlowControl(QSerialPort::NoFlowControl);
            ui->openSerial_Btn->setText("关闭");
            return true;
        }
        else
        {
            QMessageBox::warning(NULL,tr("警告"),tr("FES串口打开失败"),QMessageBox::Retry);

        }
    }
    return false;
}

void FesControlDialog::searchDevice()
{
    QByteArray array(4,0);
    array[0] = CMD_SEARCH_DEVICE_E; //功能码
    array[1] = 0;                   //设备编号0,搜索所有设备
    array[2] = 0;                   //通道号0,默认值
    array[3] = 1;                   //数据(1-开始搜索,0-停止搜索)
    QByteArray sendArray = createFrame(array);

    sendData(sendArray);
}

bool FesControlDialog::connectDevice(QByteArray mac,uint8_t deviceNum)
{
    QByteArray array(3,0);
    array[0] = CMD_DEVICE_CONNECT_E;  //功能码
    array[1] = deviceNum;            //设备编号0,搜索所有设备
    array[2] = 0;                    //通道号0,默认值
    array.append(mac);
    QByteArray sendArray = createFrame(array);

    sendData(sendArray);

    return true;
}

void FesControlDialog::setPreCurrentState(int device, int channel, bool state)
{
    QByteArray dataArray(4,0);
    dataArray[0] = PreCurrentSwitch;       //功能码
    dataArray[1] = device;                //设备编号0,搜索所有设备
    dataArray[2] = channel;               //通道号0,默认值
    dataArray[3] = state ? 1: 0;          //1-开 0-关
    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);

}

//预设电流大小
void FesControlDialog::setPreCurrent(int device,int channel,uint8_t current)
{
    QByteArray dataArray(4,0);
    dataArray[0] = PreCurrentSet_E;       //功能码
    dataArray[1] = device;                //设备编号0,搜索所有设备
    dataArray[2] = channel;               //通道号0,默认值
    dataArray[3] = current;               //1-开 0-关
    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);
}

void FesControlDialog::setPreFrequency(int device, int channel, int16_t current)
{
        QByteArray dataArray(3,0);
        dataArray[0] = FES_PRE_FREQUENCY;       //功能码
        dataArray[1] = device;                //设备编号0,搜索所有设备
        dataArray[2] = channel;               //通道号0,默认值
       // memcpy(dataArray.data()+3,&current,sizeof(current));

        QByteArray tempArray(2,0);
        memcpy(tempArray.data(),&current,sizeof(current));
        dataArray.append(tempArray.at(1)).append(tempArray.at(0));

        QByteArray sendArray = createFrame(dataArray);
        sendData(sendArray);
        qDebug() <<"发送频率:"<< sendArray.toHex();
        /*
        switch(E_fromFesType) //FES参数来的页面
        {
        case ONLY_FES_E:
            m_st_OnlyFESParam.frequency = current;
            //FesControlDialog::getInstance()->setOnlyFesParam(device,channel,m_st_OnlyFESParam);

            Sleep(100);
            // FesControlDialog::getInstance()->setPreCurrentState(device,channel,true);
            //qDebug()<<"单独电刺激,修改预设频率:"<<current<<m_st_OnlyFESParam.frequency << m_st_OnlyFESParam.keepTime << m_st_OnlyFESParam.mode;
            break;
        case BICYCLE_FES_E:
            m_st_fesParam.frequency = current;
            //qDebug()<<"脚踏车电刺激,修改预设频率:"<<current;
            //FesControlDialog::getInstance()->setFesParam(device,channel,m_st_fesParam);
            Sleep(100);

            //FesControlDialog::getInstance()->setPreCurrentState(device,channel,true);
            break;
        }
        */

}

void FesControlDialog::setPrePulseWidth(int device, int channel, int16_t current)
{
    //qDebug() << E_fromFesType;
    /*
    switch(E_fromFesType) //FES参数来的页面
    {
    case ONLY_FES_E:
        m_st_OnlyFESParam.pulseWidth = current;
        FesControlDialog::getInstance()->setOnlyFesParam(device,channel,m_st_OnlyFESParam);
        Sleep(100);
        // FesControlDialog::getInstance()->setPreCurrentState(device,channel,true);
        //qDebug()<<"单独电刺激,修改预设频率:"<<current<<m_st_OnlyFESParam.frequency<<m_st_OnlyFESParam.pulseWidth << m_st_OnlyFESParam.keepTime << m_st_OnlyFESParam.mode;
        break;
    case BICYCLE_FES_E:
        m_st_fesParam.pulseWidth = current;
        qDebug()<<"脚踏车电刺激,修改预设频率:"<<current<<m_st_fesParam.frequency << m_st_fesParam.pulseWidth << m_st_fesParam.mode;
        FesControlDialog::getInstance()->setFesParam(device,channel,m_st_fesParam);
        Sleep(100);
        //FesControlDialog::getInstance()->setPreCurrentState(device,channel,true);
        break;
    }*/
    QByteArray dataArray(3,0);
    dataArray[0] = FES_PRE_BINDWIDTH;       //功能码
    dataArray[1] = device;                //设备编号0,搜索所有设备
    dataArray[2] = channel;               //通道号0,默认值

    QByteArray tempArray(2,0);
    memcpy(tempArray.data(),&current,sizeof(current));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);
    qDebug() <<"发送带宽:"<< sendArray.toHex();
}

void FesControlDialog::setFesParam(int device,int channel,ST_FESSetParam st_fesParam)
{
    //来自页面,保存参数
    m_st_fesParam = st_fesParam;

    E_fromFesType = BICYCLE_FES_E;

    QByteArray dataArray(6,0);
    dataArray[0] = FESParamSet_E;       //功能码
    dataArray[1] = device;              //设备编号0,搜索所有设备
    dataArray[2] = channel;             //通道号0,默认值
    dataArray[3] = 2;                   //刺激
    dataArray[4] = 1;                   //采样率4k
    dataArray[5] = 1;                   //双向对称方波
    QByteArray tempArray(2,0);
    //频率
    memcpy(tempArray.data(),&st_fesParam.frequency,sizeof(st_fesParam.frequency));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));
    //脉宽
    memcpy(tempArray.data(),&st_fesParam.pulseWidth,sizeof(st_fesParam.pulseWidth));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));
    //起始角度
    memcpy(tempArray.data(),&st_fesParam.startAngle,sizeof(st_fesParam.startAngle));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));
    //结束角度
    memcpy(tempArray.data(),&st_fesParam.stopAgnle,sizeof(st_fesParam.stopAgnle));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    //起始角度-逆向
    memcpy(tempArray.data(),&st_fesParam.startAngleReverse,sizeof(st_fesParam.startAngle));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));
    //结束角度-逆向

    memcpy(tempArray.data(),&st_fesParam.stopAgnleReverse,sizeof(st_fesParam.stopAgnle));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    //最小电流
    dataArray.append(st_fesParam.minCurrent);
    //最大电流sendRealTimeFesParam
    dataArray.append(st_fesParam.maxCurrent);
    //上下肢区分
    dataArray.append(st_fesParam.upDownLimp);
    //左右肢区分
    dataArray.append(st_fesParam.leftRightLimp);

    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);
    qDebug() <<"发送数据:"<<sendArray.toHex();

}

void FesControlDialog::setRealTimeParam(int device,ST_FESRealTimeParam st_fesRealTimeParam)
{
    QByteArray dataArray(5,0);
    dataArray[0] = RealTimeParam_E;       //功能码
    dataArray[1] = device;                //设备编号0,搜索所有设备
    dataArray[2] = 0;                     //通道号0,默认值
    dataArray[3] = st_fesRealTimeParam.upSpeed;//实时速度
    dataArray[4] = st_fesRealTimeParam.downSpeed;//实时速度
    QByteArray tempArray(2,0);
    //上肢实时角度
    memcpy(tempArray.data(),&st_fesRealTimeParam.currentUpAngle,sizeof(st_fesRealTimeParam.currentUpAngle));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));
    //下肢实时角度
    memcpy(tempArray.data(),&st_fesRealTimeParam.currentDownAngle,sizeof(st_fesRealTimeParam.currentDownAngle));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    dataArray.append(st_fesRealTimeParam.direction);
    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);
    qDebug() <<"电刺激实时数据:"<<sendArray.toHex();

}

void FesControlDialog::switchDeviceChannel(int device, int channel, bool on)
{
    QByteArray dataArray(4,0);
    dataArray[0] = CMD_CHANNEL_CONTROL;       //功能码
    dataArray[1] = device;                    //设备编号0,搜索所有设备
    dataArray[2] = channel;                   //通道号0,默认值
    dataArray[3] = on ? 1:0;                  //1-开 0-关
    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);
    qDebug() <<"发送FES输出开关指令:"<<sendArray.toHex();
}


void FesControlDialog::setOnlyFesParam(int device,int channel,ST_OnlyFESParam st_fesParm)
{
    m_st_OnlyFESParam = st_fesParm;
    E_fromFesType = ONLY_FES_E;

    st_fesParm.mode = 0x02;//刺激
    st_fesParm.sampleRate = 0;//采样率4K
    st_fesParm.waveStyle = 1;//波形 双向方波
    QByteArray dataArray;

    dataArray.append(st_fesParm.mode);
    dataArray.append(st_fesParm.sampleRate);
    dataArray.append(st_fesParm.waveStyle);

    QByteArray tempArray(2,0);
    memcpy(tempArray.data(),&st_fesParm.frequency,sizeof(st_fesParm.frequency));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    memcpy(tempArray.data(),&st_fesParm.pulseWidth,sizeof(st_fesParm.pulseWidth));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    memcpy(tempArray.data(),&st_fesParm.waveRise,sizeof(st_fesParm.waveRise));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    memcpy(tempArray.data(),&st_fesParm.keepTime,sizeof(st_fesParm.keepTime));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    memcpy(tempArray.data(),&st_fesParm.waveFall,sizeof(st_fesParm.waveFall));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    memcpy(tempArray.data(),&st_fesParm.sleepTime,sizeof(st_fesParm.sleepTime));
    dataArray.append(tempArray.at(1)).append(tempArray.at(0));

    QByteArray array(3,0);
    array[0] = CMD_PARAM_SET_E;
    array[1] =  device;
    array[2] = channel;
    array.append(dataArray);

    QByteArray sendArray = createFrame(array);

    sendData(sendArray);
    qDebug() <<"发送实时参数:"<<sendArray.toHex();
}

/*
void FesControlDialog::saveOnlyFesParam(ST_OnlyFESParam st_OnlyFESParam)
{
    m_st_OnlyFESParam = st_OnlyFESParam;
    E_fromFesType = ONLY_FES_E;  //从单电刺激页面来的参数

}

void FesControlDialog::saveBicycleFesParam(ST_FESSetParam st_FESSetParam)
{
    m_st_fesParam = st_FESSetParam;
    E_fromFesType = BICYCLE_FES_E; //从FES页面来的参数

}
*/


bool FesControlDialog::getDeviceStateByNo(uint8_t deviceNo)
{
    if(deviceNo <= 4 )
    {
        if(deviceDtateArray[deviceNo-1])
            return true;
    }
    return false;
}

bool FesControlDialog::getMuscleDeviceStateByNo(uint8_t deviceNo)
{
    if(deviceNo >=1 && deviceNo <= 4 )
    {
        if(checkedMuscle_DeviceArray[deviceNo-1])
            return true;
    }
    return false;
}

void FesControlDialog::setMuscleDeviceStateByNo(uint8_t deviceNo, bool flag)
{
    if(flag)
    {
        qDebug() <<"打开设备的肌肉:"<<deviceNo; //从0~3
        checkedMuscle_DeviceArray[deviceNo-1] = 1;
    }

    else
    {
        qDebug() <<"关闭设备的肌肉:"<<deviceNo;
        checkedMuscle_DeviceArray[deviceNo-1] = 0;
    }
}

//启用电刺激设备
bool FesControlDialog::openFESDevice()
{
    //将按钮设置为不可用
    //通过配置文件打开串口
    ST_SerialPortConfig st_serialPortParam;
    if(ReadConfig::getInstance()->getFesASerialPortConfig(st_serialPortParam))
    {
        //初始化串口
        if(initSerialPort())
        {
            //打开串口
            if(openSeriaport(st_serialPortParam))
            {
                //搜索电刺激设备
                searchDevice();
                //连接电刺激设备
                connectTimer->start(1000);
                this->show();
                return true;
            }
        }
    }



    return false;
}

void FesControlDialog::queryDeviceState(uint8_t deviceNo)
{
    QByteArray dataArray(4,0);
    dataArray[0] = CMD_QUERY_STATE_E;       //功能码
    dataArray[1] = deviceNo;                       //设备编号0,搜索所有设备
    dataArray[2] = 0;                       //通道号0,默认值
    dataArray[3] = 0;
    QByteArray sendArray = createFrame(dataArray);
    sendData(sendArray);
}

void FesControlDialog::turnoffDevice(uint8_t deviceNo, uint8_t type)
{
    QByteArray array(4,0);
    array[0] = CMD_TURNOFF_E;        //功能码
    array[1] = deviceNo;             //设备编号
    array[2] = 0;                    //通道号0,默认值
    array[3] = type;                 //数据(0-关闭单个设备,1-所有设备)
    QByteArray sendArray = createFrame(array);
    sendData(sendArray);
    if(1 == deviceNo && 1 == type)
    {
        qDebug()<<"关闭所有设备";
    }
}

void FesControlDialog::on_openSerial_Btn_clicked()
{
    if(ui->openSerial_Btn->text() == "打开")
    {
        openSerialPort();
    }
    else if(ui->openSerial_Btn->text() == "关闭")
    {
        m_serialPort->close();
        ui->openSerial_Btn->setText("打开");
        //刷新串口
        initSerialPort();
    }
}

void FesControlDialog::on_scanDevice_Btn_clicked()
{
    searchDevice();
}

void FesControlDialog::receiveDataInterface()
{
    QByteArray buf;
    buf = m_serialPort->readAll();
    receiveArray.append(buf);
    while(!receiveArray.isEmpty())
    {
        if(receiveArray[0] != (char)(0xAA))
        {
            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] ==  0x55)
                {
                    analysisData(receiveArray);
                    receiveArray.remove(0,datalen + 4);
                }
                else //校验失败
                {
                    //方式1 丢弃本包
                    receiveArray.remove(0,datalen + 4);
                }
            }
            else    //数据不够,直接退出继续接收
                break;
        }
    }
}

void FesControlDialog::analysisData(QByteArray array)
{
    uint8_t deviceNo = uint8_t(array[3]);
    qDebug()<<"FES所有数据:"<<array.toHex();

    switch(array[2])
    {
    case CMD_QUERY_STATE_E:
    {
        //qDebug()<<"轮询:"<<array.toHex();
        int temp_batteryValue = array[7];//电量
        //temp_batteryValue = 50;
        int temp_deviceNo = array[3];
        if(temp_deviceNo <= 4)
          //  m_batteryValue[temp_deviceNo] = temp_batteryValue;
        emit signalGetBattery(temp_deviceNo,temp_batteryValue);
        //如果轮训,发现设备不在列表中,则删除
    }
        break;
    case CMD_TURNOFF_E:
        if(deviceNo <= 4)
            deviceDtateArray[deviceNo-1] = 0;
        qDebug()<<deviceNo<<"关机断开";
        deviceObjectMap.value(deviceNo)->setDeviceState(false);
        break;
    case CMD_SEARCH_DEVICE_E:
    {
        qDebug()<<"搜索设备";
        //qDebug()<<array.toHex();
    }
        break;
    case CMD_DEVICE_REPORT_E:
    {
        //qDebug()<<"设备上报:"<<array.toHex();
        QByteArray macArray = array.mid(5,6);
        //更新连接界面列表
        if(connectDevieMap.contains(macArray) && (!deviceList.contains(macArray)))
        {
            //填充自动连接设备列表
            AutoFESDeviceMap.insert(connectDevieMap.value(macArray),macArray);
            AutoFESDeviceControlStateMap.insert(connectDevieMap.value(macArray),false);
            deviceList.append(macArray);
            updateDeviceList();
        }
    }
        break;
    case CMD_DEVICE_CONNECT_E:
        if(deviceObjectMap.contains(deviceNo))
        {
            if(deviceNo <= 4)
                deviceDtateArray[deviceNo-1] = 1;
            //for(int i=0; 1<4; i++)
            //    qDebug()<<"点击连接状态:"<<i<<deviceDtateArray[i];
            AutoFESDeviceControlStateMap[deviceNo] = true;
            deviceObjectMap.value(deviceNo)->setDeviceState(true);
        }
        break;
    case CMD_DEVICE_DISCONNECT_E:
        qDebug()<<deviceNo<<"断开";

        if(deviceObjectMap.contains(deviceNo))
        {
            if(deviceNo <= 4)
                deviceDtateArray[deviceNo-1] = 0;

            AutoFESDeviceControlStateMap[deviceNo] = false;
            deviceObjectMap.value(deviceNo)->setDeviceState(false);

            /*
            BLEItem *bleItem = new BLEItem(deviceNo-1);
            bleItem->setBLEName(connectDevieMap.value(deviceList.at(deviceNo-1)));

            QListWidgetItem *item =ui->listWidget->item(deviceNo-1);
            //item->setSizeHint(QSize(100,65));
            //ui->listWidget->addItem(item);

            ui->listWidget->removeItemWidget(item);
            ui->listWidget->takeItem(deviceNo-1);
            delete item;
            */
            /*
            qDebug()<<"ui->listWidget->count()"<<ui->listWidget->count();
            BLEItem *bleItem = new BLEItem(deviceNo-1);
            bleItem->setBLEName(deviceNo); //BLeItem和命名

            qDebug()<<"ui->listWidget->count()2"<<ui->listWidget->count();
            for(int i = 0; i < ui->listWidget->count(); ++i)  //编号
            {
                //QListWidgetItem *item =ui->listWidget->item(i);
                QListWidgetItem *item =ui->listWidget->item(i);

                // 获取与item关联的QWidget
                QWidget *widget = ui->listWidget->itemWidget(item);
                // 尝试将QWidget转换为BLEItem
                BLEItem *tempBleItem = dynamic_cast<BLEItem*>(widget);

                if(bleItem->getBLEName() == tempBleItem->getBLEName())
                {

                    qDebug() <<"清除:"<< bleItem->getBLEName();

                    ui->listWidget->removeItemWidget(item);
                    delete tempBleItem;
                    delete item;        // 从QListWidget中移除item*

                    //ui->listWidget->takeItem(i);
                    --i;

                    break;
                }

            }
        */


        }
        break;
    }
}

//更新蓝牙设备列表
void FesControlDialog::updateDeviceList()
{
    QStringList labelList;
    for(int i = 0;i < deviceList.count();++i)
    {
        if(addedDeviceList.contains(deviceList.at(i)))
            continue;
        //在连接界面显示
        //qDebug() <<"设备列表:"<<i<< deviceList[i];
        BLEItem *bleItem = new BLEItem(i);
        bleItem->setBLEName(connectDevieMap.value(deviceList.at(i)));
        deviceObjectMap.insert(bleItem->getBLEName(),bleItem);

        connect(bleItem,&BLEItem::signalConnectDevice,this,&FesControlDialog::slotConnectDevice);
        connect(bleItem,&BLEItem::signalBtnStateChanged,this,&FesControlDialog::deviceStateChanged);

        QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
        item->setSizeHint(QSize(100,65));
        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item,bleItem);

        addedDeviceList.append(deviceList.at(i));
    }
    //qDebug() <<"deviceList.count():"<<deviceList.at(0).toInt()<<addedDeviceList.at(0).toInt();
}



QByteArray FesControlDialog::str2QByteArray(QString str)
{
    QByteArray currentMac(6,0);
    bool ok;
    for(int i = 0;i < currentMac.size();++i)
    {
        currentMac[i] = str.mid(2*i,2).toInt(&ok,16);
    }
    return currentMac;
}


void FesControlDialog::sendData(QByteArray array)
{
    if(m_serialPort && m_serialPort->isOpen())
        m_serialPort->write(array);
    //qDebug() <<"输出FES数据"<<array.toHex();
}

//查看界面列表
void FesControlDialog::on_listWidgetClicked(QListWidgetItem *item)
{
    QString str = item->text();
    QByteArray currentMac(6,0);
    bool ok;
    for(int i = 0;i < currentMac.size();++i)
    {
        currentMac[i] = str.mid(2*i,2).toInt(&ok,16);
    }
    currentMacDevice = currentMac;
}

void FesControlDialog::displayError(QSerialPort::SerialPortError error)
{

}

void FesControlDialog::slotConnectDevice(bool connect,uint8_t device)
{
    QMapIterator<QByteArray, int> iter(connectDevieMap);
    QByteArray devcieMac;
    while (iter.hasNext()) {
        iter.next();
        if(iter.value() == device)
        {
            devcieMac = iter.key();
            break;
        }
    }

    QByteArray sendArray;
    if(connect)
    {
        QByteArray array(3,0);
        array[0] = CMD_DEVICE_CONNECT_E;  //功能码
        array[1] = device;               //设备编号0,搜索所有设备
        array[2] = 0;                    //通道号0,默认值
        array.append(devcieMac);
        sendArray = createFrame(array);
    }
    else
    {
        QByteArray array(4,0);
        array[0] = CMD_TURNOFF_E;        //功能码
        array[1] = device;               //设备编号
        array[2] = 0;                    //通道号0,默认值
        array[3] = 0;                    //数据(0-关闭)
        sendArray = createFrame(array);
        setMuscleDeviceStateByNo(device,false); //已连接的肌肉设备更新
    }
    sendData(sendArray);
}



void FesControlDialog::showEvent(QShowEvent *event)
{
    Q_UNUSED(event)
    //查询数据库
    connectDevieMap.clear();
    QString query("select * from  BLEDeviceMsg");
    if(CDatabaseInterface::getInstance()->exec(query))
    {
        int tempNum = CDatabaseInterface::getInstance()->getValuesSize();
        QList<QVariantMap> valueMapList;
        valueMapList = CDatabaseInterface::getInstance()->getValues(0,tempNum);
        for(int i = 0;i < valueMapList.count();++i)
        {
            ST_BLEDevice st_BLEDevice = variantMapToBLEDevice(valueMapList.at(i));
            //填充设备Map
            connectDevieMap.insert(str2QByteArray(st_BLEDevice.deviceMac),st_BLEDevice.deviceNo);
        }
    }
}



void FesControlDialog::on_queryDevice_Btn_clicked()
{
    queryDeviceState(1);
}


void FesControlDialog::on_flushSerial_Btn_clicked()
{
    initSerialPort();
}

void FesControlDialog::slotConnectFes()
{
    QMapIterator<int,bool> iter(AutoFESDeviceControlStateMap);
    int times = 1;
    while (iter.hasNext()) {
        iter.next();
        if(!iter.value())
        {
            ++times;
            int deviceNo = iter.key();
            QTimer::singleShot(100*times,this,[=](){
                connectDevice(AutoFESDeviceMap.value(deviceNo),deviceNo);
            });

            break;
        }
    }

}

void FesControlDialog::deviceStateChanged(uint8_t deviceNo, bool state)
{
    qDebug()<<"设备状态发生变化"<<deviceNo<<state;
    QList<uint8_t> deviceStateList;
    for(int i = 0;i < 4;++i)
    {
        qDebug()<<i<<deviceDtateArray[i];
        deviceStateList.append(deviceDtateArray[i]);
        //如果不存在item,就移除item
    }

    emit signalDeviceStateChanged(deviceStateList);

}


void FesControlDialog::on_close_Btn_clicked()
{
    this->close();
}

void FesControlDialog::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.fillRect(rect(),QColor(0,0,0,100));
}

void FesControlDialog::changeEvent(QEvent *event)
{
    switch (event->type())
    {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        QWidget::changeEvent(event);
        break;
    }
}