#include "sensorinputwidget.h"
#include "ui_sensorinputwidget.h"

SensorInputWidget::SensorInputWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SensorInputWidget),
    m_itemPerPage(24),
    m_pGetSenserTimer(NULL)
{
    ui->setupUi(this);

    setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);

    m_mousePressX = 0;
    m_mousePressY = 0;
    m_mouseReleaseX = 0;
    m_mouseReleaseY = 0;
    m_sensorsTypeIdx = -1;

    m_pGetSenserTimer = new QTimer(this);
    connect(m_pGetSenserTimer, SIGNAL(timeout()),
            this, SLOT(slotOnRefTimer()));

    initData();
    initControl();
    initArabControlPos();
    refreshUi();
}

SensorInputWidget::~SensorInputWidget()
{
    delete m_pGetSenserTimer;
    delete ui;
}

void SensorInputWidget::initData()
{
    m_curPage = 0;                 // 当前页
    m_allSensorItemList.clear();
    m_sensorItemList.clear();
    m_itemList.clear();
    m_sensorsDat.clear();
}

//初始化窗体控件，包括位置、尺寸、样式
void SensorInputWidget::initControl()
{
    m_SensorBtnList.append(ui->button1);
    m_SensorBtnList.append(ui->button2);
    m_SensorBtnList.append(ui->button3);
    m_SensorBtnList.append(ui->button4);
    m_SensorBtnList.append(ui->button5);
    ui->button6->setVisible(false);
    ui->button7->setVisible(false);
    ui->button8->setVisible(false);
    ui->button9->setVisible(false);
    ui->button10->setVisible(false);
    ui->button11->setVisible(false);
    ui->button12->setVisible(false);

    if(g_emResolut == resolution1910)//1920x1080的分辨率每页显示12个条目
    {
        ui->button6->setVisible(true);
        ui->button7->setVisible(true);
        ui->button8->setVisible(true);
        ui->button9->setVisible(true);
        ui->button10->setVisible(true);
        ui->button11->setVisible(true);
        ui->button12->setVisible(true);
        m_SensorBtnList.append(ui->button6);
        m_SensorBtnList.append(ui->button7);
        m_SensorBtnList.append(ui->button8);
        m_SensorBtnList.append(ui->button9);
        m_SensorBtnList.append(ui->button10);
        m_SensorBtnList.append(ui->button11);
        m_SensorBtnList.append(ui->button12);
    }
    else if(g_emResolut == resolution1006)//1024x600的分辨率每页显示8个条目
    {
        ui->button6->setVisible(true);//显示
        ui->button7->setVisible(true);
        ui->button8->setVisible(true);
        m_SensorBtnList.append(ui->button6);
        m_SensorBtnList.append(ui->button7);
        m_SensorBtnList.append(ui->button8);
    }

    m_SensorBtnList.append(ui->button1_2);
    m_SensorBtnList.append(ui->button2_2);
    m_SensorBtnList.append(ui->button3_2);
    m_SensorBtnList.append(ui->button4_2);
    m_SensorBtnList.append(ui->button5_2);
    ui->button6_2->setVisible(false);
    ui->button7_2->setVisible(false);
    ui->button8_2->setVisible(false);
    ui->button9_2->setVisible(false);
    ui->button10_2->setVisible(false);
    ui->button11_2->setVisible(false);
    ui->button12_2->setVisible(false);

    if(g_emResolut == resolution1910)//1920x1080的分辨率每页显示12个条目
    {
        ui->button6_2->setVisible(true);
        ui->button7_2->setVisible(true);
        ui->button8_2->setVisible(true);
        ui->button9_2->setVisible(true);
        ui->button10_2->setVisible(true);
        ui->button11_2->setVisible(true);
        ui->button12_2->setVisible(true);
        m_SensorBtnList.append(ui->button6_2);
        m_SensorBtnList.append(ui->button7_2);
        m_SensorBtnList.append(ui->button8_2);
        m_SensorBtnList.append(ui->button9_2);
        m_SensorBtnList.append(ui->button10_2);
        m_SensorBtnList.append(ui->button11_2);
        m_SensorBtnList.append(ui->button12_2);
    }
    else if(g_emResolut == resolution1006)//1024x600的分辨率每页显示8个条目
    {
        ui->button6_2->setVisible(true);
        ui->button7_2->setVisible(true);
        ui->button8_2->setVisible(true);
        m_SensorBtnList.append(ui->button6_2);
        m_SensorBtnList.append(ui->button7_2);
        m_SensorBtnList.append(ui->button8_2);
    }

    //根据不同分辨率设置控件的位置和尺寸
    switch (g_emResolut)
    {
    case resolution1910:
        initResolution1910();
        break;
    case resolution1006:
        initResolution1006();
        break;
    default:
        this->resize(1920,1080);
        break;
    }

    initControlStyle();//初始化窗体控件样式
}

//初始化窗体控件为1920x1080分辨率
void SensorInputWidget::initResolution1910()
{
    this->resize(1920,1080);
    ui->frameBack->setGeometry(0,0,1920,1080);
    ui->buttonTypeLogo->setGeometry(128,66,78,78);
    ui->labelMainTitle->setGeometry(226,60,1000,48);
    ui->labelSubTitle->setGeometry(302,112,1000,36);

    QRect rectName(34,2,58,58);
    QRect rectValue(74,0,660,58);//传感器信号的名称
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < m_itemPerPage/2; j++)
        {
            m_SensorBtnList[i*(m_itemPerPage/2) + j]->setGeometry(295+i*630,180+j*64,660,58);
            m_SensorBtnList[i*(m_itemPerPage/2) + j]->initLeftNameRightValue(rectName,rectValue);
        }
    }

    ui->framePageBtn->setGeometry(1120,990,800,70);
    ui->labelPage->setGeometry(32,1008,400,40);
    ui->buttonPgUp->setGeometry(200,0,168,70);
    ui->buttonPgDn->setGeometry(400,0,168,70);
    ui->buttonBack->setGeometry(600,0,168,70);
}
//初始化窗体控件为1024x600分辨率
void SensorInputWidget::initResolution1006()
{
    m_itemPerPage = m_itemPerPage - 8;
    this->resize(1024,600);
    ui->frameBack->setGeometry(0,0,1024,600);
    ui->buttonTypeLogo->setGeometry(25,30,60,60);
    ui->labelMainTitle->setGeometry(100,30,200,24);
    ui->labelSubTitle->setGeometry(130,64,300,21);

    QRect rectName(35,0,53,53);
    QRect rectValue(50,0,380,53);
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < m_itemPerPage/2; j++)
        {
            m_SensorBtnList[i*(m_itemPerPage/2) + j]->setGeometry(140+i*340,94+j*53,380,53);
            m_SensorBtnList[i*(m_itemPerPage/2) + j]->initLeftNameRightValue(rectName,rectValue);
        }
    }

    ui->framePageBtn->setGeometry(700,545,600,45);
    ui->labelPage->setGeometry(20,550,102,45);
    ui->buttonPgUp->setGeometry(0,0,96,40);
    ui->buttonPgDn->setGeometry(106,0,96,40);
    ui->buttonBack->setGeometry(212,0,96,40);
}

//初始化窗体控件样式
void SensorInputWidget::initControlStyle()
{
    SetControlStyle setControlStyle;
    setControlStyle.setUiName(this->objectName());

    //背景图
    QString frameBackImgPath = setControlStyle.getSharedStyleSheet();
    ui->frameBack->setStyleSheet(frameBackImgPath);
    ui->labelMainTitle->setFont(fontBold_1);
    ui->labelMainTitle->setStyleSheet(LABELWHITESTYLE);
    ui->labelSubTitle->setFont(fontNormal_1);
    ui->labelSubTitle->setStyleSheet(LABELWHITESTYLE);
    ui->labelPage->setFont(fontNormal_1);
    ui->labelPage->setStyleSheet(LABELWHITESTYLE);

    for(int i = 0; i < m_SensorBtnList.size(); i++)
    {
        m_SensorBtnList[i]->setEnabled(false);
        m_SensorBtnList[i]->setLabelValueFont(fontNormal_1);
        m_SensorBtnList[i]->setLabelNameFont(fontBold_1);
    }

    //四个按钮样式表一样
    ui->buttonPgUp->setOrangeGradientBottomStyle(BORDER_RADIUS2);
    ui->buttonPgUp->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgUp->objectName()),12);

    ui->buttonPgDn->setOrangeGradientBottomStyle(BORDER_RADIUS2);
    ui->buttonPgDn->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgDn->objectName()),12);

    ui->buttonBack->setOrangeGradientBottomStyle(BORDER_RADIUS2);
    ui->buttonBack->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonBack->objectName()),12);
}

void SensorInputWidget::initArabControlPos()
{
    int language = g_pSettings->readFromInHMIiFile("HMI/language").toInt();
    if(language != arabic)
    {
        return;
    }

    ui->labelMainTitle->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    ui->labelSubTitle->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    for(int i = 0; i < m_SensorBtnList.size(); i++)
    {
        m_SensorBtnList[i]->setLabelValuePos(1);
    }
}

//设置类型图标
void SensorInputWidget::setTypeLogo(QString tStyle)
{
    ui->buttonTypeLogo->setUnPreBtnLogo(tStyle);
}

void SensorInputWidget::setMainTitle(QString title)
{
    ui->labelMainTitle->setText(title);
}

//设置副title
void SensorInputWidget::setSubTitle(QString title)
{
    ui->labelSubTitle->setText(title);
}

int SensorInputWidget::addSensorItems(QList<SensorItem> itemList)
{
    m_allSensorItemList.append(itemList);
    return (m_allSensorItemList.size() - itemList.size());
}

void SensorInputWidget::setButtonIdx(int idx)
{
    m_itemList.clear();
    int val = STYPE1;
    idx -= 1;
    if(idx >= 0)
    {
        m_sensorsTypeIdx = val << idx;
    }
    refreshUi();
}

void SensorInputWidget::setMachine(Machine *pMc)
{
    g_pMachine = pMc;
}

void SensorInputWidget::refreshUi()
{
//    QList<SensorItem> itemList;
//    itemList.clear();

#if(0)//测试用
    m_SensorBtnList[0]->setLabelValue("11111");
    m_SensorBtnList[0]->setLabelName("■");
#endif

    if(m_itemPerPage <= 0)
    {
        return;
    }

    if(m_sensorsTypeIdx == -1)//传感器信号不分类
    {
        m_itemList.clear();
        m_itemList.append(m_sensorItemList);//根据下位机位图过滤的传感器信号列表放在itemList里
    }
    else
    {
        getItemList(m_itemList); //根据不同主板加载的分类传感器信号
    }

    //-----------
    int itemNum, pageNums;
    itemNum = m_itemList.size();

    //qDebug()<< "RefreshUi m_sensorItemList = "<<itemNum;
    pageNums = (itemNum+m_itemPerPage-1) / m_itemPerPage;

    if (m_curPage > pageNums)                 // 当前页
    {
        m_curPage = pageNums;
    }
    if (m_curPage <= 1)
    {
        m_curPage = 1;
    }

    // 刷新文本
    int i, itemidx;
    itemidx = (m_curPage-1) * m_itemPerPage;
    for (i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < itemNum)
        {
            if(m_itemList[itemidx].m_name.length() <= 0)//字符长度为空
            {
               //QString str = "byte:" + QString::number(itemList[itemidx].m_byte_offset) + "  bit:" + QString::number(m_sensorItemList[itemidx].m_bit_offset);
                QString str = "byte:" + QString::number(m_itemList[itemidx].m_byte_offset) + "  bit:" + QString::number(m_itemList[itemidx].m_bit_offset);
                m_SensorBtnList.at(i)->setLabelValue(str);
            }
            else
            {
                m_SensorBtnList.at(i)->setLabelValue(m_itemList.at(itemidx).m_name);
            }
            m_SensorBtnList.at(i)->show();
        }
        else
        {
            m_SensorBtnList.at(i)->hide();
        }
        itemidx++;
    }

    // 刷新信号
    refreshSensors();

    // 刷新按钮
    if (m_curPage <= 1)
    {
        ui->buttonPgUp->setEnabled(false);
    }
    else
    {
        ui->buttonPgUp->setEnabled(true);
    }
    if (m_curPage >= pageNums)
    {
        ui->buttonPgDn->setEnabled(false);
    }
    else
    {
        ui->buttonPgDn->setEnabled(true);
    }

    if(pageNums == 0)
    {
        m_curPage = 0;
    }

    // 页信息
    QString str = tr("pageNum: ") + QString("%1/%2").arg(m_curPage).arg(pageNums);//页数:
    ui->labelPage->setText(str);
}

void SensorInputWidget::refreshSensors()
{
    QTextCodec *cod = QTextCodec::codecForLocale();
    if(m_sensorsDat.size() <= 0)
    {
        return;
    }

    //--------------------------
    int itemNum, pageNums;
//    itemNum = m_sensorItemList.size();//m_sensorItemList
    itemNum = m_itemList.size();
    pageNums = (itemNum+m_itemPerPage-1) / m_itemPerPage;

    if (m_curPage > pageNums)                 // 当前页
    {
        m_curPage = pageNums;
    }
    if (m_curPage <= 1)
    {
        m_curPage = 1;
    }

    // 刷新文本
    int i, itemidx;
    itemidx = (m_curPage-1) * m_itemPerPage;
    for (i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < itemNum)
        {
            //const SensorItem & item = m_sensorItemList.at(itemidx);//m_sensorItemList
            const SensorItem & item = m_itemList.at(itemidx);

            int bytepos = item.m_byte_offset;
            int bitinbyte = item.m_bit_offset;

            if (    bytepos >= 0 &&
                    bitinbyte >= 0 &&
                    bytepos < m_sensorsDat.size())
            {
                u8 curbyte = m_sensorsDat.at(bytepos);
                u8 mod = 0x01 << bitinbyte;

                if ((curbyte & mod) != 0)
                {
                    m_SensorBtnList.at(i)->setLabelName(cod->toUnicode("■"));
                }
                else
                {
                    m_SensorBtnList.at(i)->setLabelName(cod->toUnicode("□"));
                }
            }
            else
            {
                m_SensorBtnList.at(i)->setText("");
            }
        }
        else
        {
            break;
        }
        itemidx++;
    }
}

void SensorInputWidget::getItemList(QList<SensorItem> &ItemList)
{
    ItemList.clear();

    for(int i = 0; i < m_sensorItemList.size(); i++)
    {
        int type = m_sensorItemList[i].m_type;

        if((type & m_sensorsTypeIdx) != 0 && (type != -1))
        {
            ItemList.append(m_sensorItemList[i]);//筛选好的传感器信号，分类传感器信号
        }
    }
}

void SensorInputWidget::show()
{
    m_sensorsDat.clear();

    if (g_pMachine != NULL)
    { //如果没有传感器信号位图
        if (g_pMachine->isSensorBmpEn() == 0)
        {
            m_sensorItemList.clear();
            g_pMachine->getSensorEnBmpFromMachine();//读取传感器有效位图
            refreshUi();

            qDebug("send GetSensorEnBmpFromMachine");
        }
    }

    //emit(siEntrySensorScan());
    if (m_pGetSenserTimer != NULL)
    {
        m_pGetSenserTimer->start(500);//读取传感器信号
    }

    if (g_pMachine != NULL)
    {
        g_pMachine->entrySensorScan();
    }

    qDebug("SensorInputWidget::show");

    QWidget::show();
}

void SensorInputWidget::hide()
{
    if (m_pGetSenserTimer != NULL)
    {
        m_pGetSenserTimer->stop();
    }

    //emit(siExitSensorScan());

    if (g_pMachine != NULL)
    {
        g_pMachine->exitSensorScan();
    }

    qDebug("SensorInputWidget::hide");

    QWidget::hide();
}

void SensorInputWidget::slotRefSensorBitmap(SensorsBitmap map)
{
    qDebug("SlotRefSensorBitmap");
    m_sensorItemList.clear();

    if (g_pMachine != NULL)
    {
        if (g_pMachine->isSensorBmpEn() != 0)
        {
            QByteArray sensorsbmp;
            sensorsbmp.resize(sizeof(SensorsBitmap));
            memcpy(sensorsbmp.data(), &map, sizeof(SensorsBitmap));

            int ssize = m_allSensorItemList.size() ;//m_allSensorItemList 8192个  机型里的所有主板的传感器信号
            int fsize = sensorsbmp.size();
            int size = (ssize < fsize) ? ssize:fsize;
            for (int i = 0; i < size; i++)
            {
                unsigned char fdat = sensorsbmp.at(i);
                for (int j = 0; j < 8; j++)
                {
                    const SensorItem & item = m_allSensorItemList.at( i*8 + j);
                    if ((fdat & 0x01) != 0)
                    {
                        m_sensorItemList.append(item);//根据下位机过滤好的传感器列表
                    }
                    fdat >>= 1 ;
                }
            }

            qDebug("m_sensorItemList.size=%d", m_sensorItemList.size());
            refreshUi();
        }
    }
}
//接收传感器状态改变的槽函数
void SensorInputWidget::slotRefSensorsDat(SensorsBitmap dat)
{
    // 读取信号
    m_sensorsDat.clear();
    m_sensorsDat.resize(sizeof(SensorsBitmap));
    memcpy(m_sensorsDat.data(),&dat,sizeof(SensorsBitmap));

    // 更新视图
    refreshSensors();
}

void SensorInputWidget::slotOnRefTimer()
{
    if (g_pMachine != NULL)
    {
        g_pMachine->getSensorsFromMachine();        // 读取一次信号
    }
}

void SensorInputWidget::on_buttonPgUp_clicked()
{
    m_curPage--;
    refreshUi();
}

void SensorInputWidget::on_buttonPgDn_clicked()
{
    m_curPage++;
    refreshUi();
}

void SensorInputWidget::on_buttonBack_clicked()
{
    this->hide();
}

void SensorInputWidget::mousePressEvent(QMouseEvent *e)
{
    if ( e->button() == Qt::LeftButton)
    {
        m_mousePressX = e->x();
        m_mousePressY = e->y();
        m_mouseReleaseX = 0;
        m_mouseReleaseY = 0;
    }
}

void SensorInputWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if ( e->button() == Qt::LeftButton)
    {
        m_mouseReleaseX = e->x();
        m_mouseReleaseY = e->y();
    }

    int width = this->width();
    int height = this->height();
    if ((m_mousePressX >= 0 && m_mousePressX <= 100)  &&
            ((m_mousePressY >= (height - 100)) && m_mousePressY <= height) &&
            ((m_mouseReleaseX >= (width - 100)) && m_mouseReleaseX <= width) &&
            ((m_mouseReleaseY >= (height - 100)) && m_mouseReleaseY <= height))
    {
        MainWidgetFunction mainFunction;
        QString usbPath;//优盘路径
        usbPath = mainFunction.detectUsb();//优盘检测
        if(usbPath.length() <= 0)
        {
            //优盘不存在
            return;
        }
        else
        {
            QPixmap pixmap=QPixmap::grabWindow(this->winId(),0,0,this->width(),this->height());//截屏存放在pixmap
            QString name_pc = usbPath +  "EMB" + //
                    QDateTime::currentDateTime().toString("yyyyMMdd") +//获取时期时间
                    +"_"+
                    QDateTime::currentDateTime().toString("hhmmss")    + ".png";

            pixmap.save(name_pc,"png"); // 路径
        }
    }

    m_mousePressX = 0;
    m_mousePressY = 0;
    m_mouseReleaseX = 0;
    m_mouseReleaseY = 0;
}
