#include "patternselectwidget.h"
#include "ui_patternselectwidget.h"

PatternSelectWidget::PatternSelectWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PatternSelectWidget),
    m_itemPerPage(10)
{
    ui->setupUi(this);
    setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);

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

    this->move(g_mainWidgetPos.x(),g_mainWidgetPos.y());
    initControl();
    initArabControlPos();
    initialize();
}

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

//初始化窗体控件，包括位置、尺寸、样式
void PatternSelectWidget::initControl()
{
    m_imageButtonList.clear();
    m_imageButtonList.append(ui->buttonImage1);
    m_imageButtonList.append(ui->buttonImage2);
    m_imageButtonList.append(ui->buttonImage3);
    m_imageButtonList.append(ui->buttonImage4);
    m_imageButtonList.append(ui->buttonImage5);
    m_imageButtonList.append(ui->buttonImage6);
    m_imageButtonList.append(ui->buttonImage7);
    m_imageButtonList.append(ui->buttonImage8);
    m_imageButtonList.append(ui->buttonImage9);
    m_imageButtonList.append(ui->buttonImage10);

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

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

//初始化窗体控件为1920x1080分辨率
void PatternSelectWidget::initResolution1910()
{
    int language = g_pSettings->readFromInHMIiFile("HMI/language").toInt();

    this->resize(1920,1080);
    ui->frameBack->setGeometry(0,0,1920,1080);
    ui->buttonTypeLogo->setGeometry(128,66,78,78);
    ui->labelMainTitle->setGeometry(226,60,1000,44);
    ui->labelSubTitle->setGeometry(302,112,1000,36);
    ui->frameImage->setGeometry(48,194,1422,748);

    //预览图片
    QRect rectImage(14,12,230,230);
    QRect rectName(36,262,210,82);
    for(int i = 0; i < 2; i++)
    {
        s16 num = m_imageButtonList.size()/2;
        for(int j = 0; j < num; j++)
        {
            m_imageButtonList.at(i*num + j)->setGeometry(0+j*288 ,0+i*390,256,356);
            m_imageButtonList.at(i*num + j)->initUpImageDownName(rectImage,rectName);
        }
    }

    ui->frameRightUp->setGeometry(1716,92,172,72);
    ui->buttonBackUpDir->setGeometry(102,0,66,66);

    //label样式
    ui->labelMainTitle->setFont(fontBold_1);
    ui->labelMainTitle->setStyleSheet(LABELWHITESTYLE);
    ui->labelSubTitle->setFont(fontNormal_1);
    ui->labelSubTitle->setStyleSheet(LABELWHITESTYLE);
    ui->labelPageNum->setFont(fontNormal_1);
    ui->labelPageNum->setStyleSheet(LABELWHITESTYLE);

    ui->frameInfo1->setGeometry(1528,210,328,284);

    QList<QLabel*> labelList1;
    labelList1.append(ui->labelPatternName);
    labelList1.append(ui->labelTotalNeedle);
    labelList1.append(ui->labelColorNum);
    labelList1.append(ui->labelPatternWidth);
    labelList1.append(ui->labelPatternHeight);
    labelList1.append(ui->labelX);
    labelList1.append(ui->labelY);
    for(int i = 0; i < labelList1.size(); i++)
    {
        if(language == arabic)
        {
            labelList1[i]->setGeometry(176,i*40,138,32);
        }
        else
        {
            labelList1[i]->setGeometry(0,i*40,138,32);
        }
        labelList1[i]->setFont(fontNormal_6);
        labelList1[i]->setStyleSheet(LABELWHITESTYLE);
    }

    QList<QLabel*> labelList2;
    labelList2.append(ui->labelPatternNameValue);
    labelList2.append(ui->labelTotalNeedleValue);
    labelList2.append(ui->labelColorNumValue);
    labelList2.append(ui->labelPatternWidthValue);
    labelList2.append(ui->labelPatternHeightValue);
    labelList2.append(ui->labelXValue);
    labelList2.append(ui->labelYValue);
    for(int i = 0; i < labelList2.size(); i++)
    {
        if(language == arabic)
        {
            labelList2[i]->setGeometry(0,i*40,176,32);
        }
        else
        {
            labelList2[i]->setGeometry(138,i*40,176,32);
        }
        labelList2[i]->setFont(fontNormal_6);
        labelList2[i]->setStyleSheet(LABELWHITESTYLE);
    }

    ui->frameInfo2->setGeometry(1528,526,328,398);

    QList<QLabel*> labelList3;
    labelList3.append(ui->labelScale);
    labelList3.append(ui->labelRotate);
    labelList3.append(ui->labelDirection);
    labelList3.append(ui->labelPriority);
    labelList3.append(ui->labelReverseWay);
    labelList3.append(ui->labelReverseNum);
    labelList3.append(ui->labelReverSpace);
    for(int i = 0; i < labelList3.size(); i++)
    {
        if(language == arabic)
        {
            labelList3[i]->setGeometry(120,30+i*40,200,32);
        }
        else
        {
            labelList3[i]->setGeometry(0,30+i*40,200,32);
        }
        labelList3[i]->setFont(fontNormal_6);
        labelList3[i]->setStyleSheet(LABELWHITESTYLE);
    }

    QList<QLabel*> labelList4;
    labelList4.append(ui->labelScaleValue);
    labelList4.append(ui->labelRotateValue);
    labelList4.append(ui->labelDirectionValue);
    labelList4.append(ui->labelPriorityValue);
    labelList4.append(ui->labelReverseWayValue);
    labelList4.append(ui->labelReverseNumValue);
    labelList4.append(ui->labelReverSpaceValue);
    for(int i = 0; i < labelList4.size(); i++)
    {
        if(language == arabic)
        {
            labelList4[i]->setGeometry(0,30+i*40,130,32);
        }
        else
        {
            labelList4[i]->setGeometry(192,30+i*40,130,32);
        }
        labelList4[i]->setFont(fontNormal_6);
        labelList4[i]->setStyleSheet(LABELWHITESTYLE);
    }

    ui->framePageBtn->setGeometry(1120,990,800,70);
    ui->labelPageNum->setGeometry(32,1008,260,40);//显示不全 加长
    ui->buttonPgUp->setGeometry(0,0,168,70);
    ui->buttonPgDn->setGeometry(200,0,168,70);
    ui->buttonOk->setGeometry(400,0,168,70);
    ui->buttonCancel->setGeometry(600,0,168,70);
}
//初始化窗体控件为1024x600分辨率
void PatternSelectWidget::initResolution1006()
{
    int language = g_pSettings->readFromInHMIiFile("HMI/language").toInt();

    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,240,21);
    ui->frameImage->setGeometry(27,108,791,431);

    //预览图片
    QRect rectImage(7,9,120,120);
    QRect rectName(18,144,112,42);
    for(int i = 0; i < 2; i++)
    {
        s16 num = m_imageButtonList.size()/2;
        for(int j = 0; j < num; j++)
        {
            m_imageButtonList.at(i*num + j)->setGeometry(0+j*155,0+i*220,134,197);
            m_imageButtonList.at(i*num + j)->initUpImageDownName(rectImage,rectName);
        }
    }

    ui->frameRightUp->setGeometry(800,40,300,61);
    ui->buttonBackUpDir->setGeometry(150,0,50,50);

    //label样式
    ui->labelMainTitle->setFont(fontBold_1);
    ui->labelMainTitle->setStyleSheet(LABELWHITESTYLE);
    ui->labelSubTitle->setFont(fontNormal_1);
    ui->labelSubTitle->setStyleSheet(LABELWHITESTYLE);
    ui->labelPageNum->setFont(fontNormal_1);
    ui->labelPageNum->setStyleSheet(LABELWHITESTYLE);

    ui->frameInfo1->setGeometry(804,110,222,191);

    QList<QLabel*> labelList1;
    labelList1.append(ui->labelPatternName);
    labelList1.append(ui->labelTotalNeedle);
    labelList1.append(ui->labelColorNum);
    labelList1.append(ui->labelPatternWidth);
    labelList1.append(ui->labelPatternHeight);
    labelList1.append(ui->labelX);
    labelList1.append(ui->labelY);
    for(int i = 0; i < labelList1.size(); i++)
    {
        if(language == arabic)
        {
            labelList1[i]->setGeometry(92,i*26,90,32);
        }
        else
        {
            labelList1[i]->setGeometry(5,i*26,90,32);
        }
        labelList1[i]->setFont(fontNormal_6);
        labelList1[i]->setStyleSheet(LABELWHITESTYLE);
    }

    QList<QLabel*> labelList2;
    labelList2.append(ui->labelPatternNameValue);
    labelList2.append(ui->labelTotalNeedleValue);
    labelList2.append(ui->labelColorNumValue);
    labelList2.append(ui->labelPatternWidthValue);
    labelList2.append(ui->labelPatternHeightValue);
    labelList2.append(ui->labelXValue);
    labelList2.append(ui->labelYValue);
    for(int i = 0; i < labelList2.size(); i++)
    {
        if(language == arabic)
        {
            labelList2[i]->setGeometry(0,i*26,140,32);
        }
        else
        {
            labelList2[i]->setGeometry(42,i*26,140,32);
        }
        labelList2[i]->setFont(fontNormal_6);
        labelList2[i]->setStyleSheet(LABELWHITESTYLE);
    }

    ui->frameInfo2->setGeometry(804,310,222,232);

    QList<QLabel*> labelList3;
    labelList3.append(ui->labelScale);
    labelList3.append(ui->labelRotate);
    labelList3.append(ui->labelDirection);
    labelList3.append(ui->labelPriority);
    labelList3.append(ui->labelReverseWay);
    labelList3.append(ui->labelReverseNum);
    labelList3.append(ui->labelReverSpace);
    for(int i = 0; i < labelList3.size(); i++)
    {
        if(language == arabic)
        {
            labelList3[i]->setGeometry(72,i*26,110,32);
        }
        else
        {
            labelList3[i]->setGeometry(5,i*26,110,32);
        }
        labelList3[i]->setFont(fontNormal_6);
        labelList3[i]->setStyleSheet(LABELWHITESTYLE);
    }

    QList<QLabel*> labelList4;
    labelList4.append(ui->labelScaleValue);
    labelList4.append(ui->labelRotateValue);
    labelList4.append(ui->labelDirectionValue);
    labelList4.append(ui->labelPriorityValue);
    labelList4.append(ui->labelReverseWayValue);
    labelList4.append(ui->labelReverseNumValue);
    labelList4.append(ui->labelReverSpaceValue);
    for(int i = 0; i < labelList4.size(); i++)
    {
        if(language == arabic)
        {
            labelList4[i]->setGeometry(-24,i*26,110,32);
        }
        else
        {
            labelList4[i]->setGeometry(72,i*26,110,32);
        }
        labelList4[i]->setFont(fontNormal_6);
        labelList4[i]->setStyleSheet(LABELWHITESTYLE);
    }

    ui->framePageBtn->setGeometry(595,545,600,45);
    ui->labelPageNum->setGeometry(20,550,102,45);
    ui->buttonPgUp->setGeometry(0,0,96,40);
    ui->buttonPgDn->setGeometry(106,0,96,40);
    ui->buttonOk->setGeometry(212,0,96,40);
    ui->buttonCancel->setGeometry(318,0,96,40);
}

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

    //背景图
    QString frameBackImgPath = setControlStyle.getStyleSheet(this->objectName());
    ui->frameBack->setStyleSheet(frameBackImgPath);

    //frame样式
    ui->framePageBtn->setStyleSheet(TRANSPARENTSTYLE);
    ui->frameImage->setStyleSheet(TRANSPARENTSTYLE);
    ui->frameInfo1->setStyleSheet(TRANSPARENTSTYLE);
    ui->frameInfo2->setStyleSheet(TRANSPARENTSTYLE);
    ui->frameRightUp->setStyleSheet(TRANSPARENTSTYLE);

    //条目
    for(int i = 0; i < m_itemPerPage; i++)
    {
        m_imageButtonList[i]->setCheckedBottomImage(setControlStyle.getBottomStyleSheet(m_imageButtonList[i]->parent()->objectName()));
        m_imageButtonList[i]->setLabelFont(fontNormal_12);
    }

    ui->buttonBackUpDir->setGreenGradientBottomStyle(BORDER_RADIUS1);
    ui->buttonBackUpDir->setTopImage(setControlStyle.getTopStyleSheet(ui->buttonBackUpDir->objectName()));

    //四个按钮样式表一样
    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->buttonOk->setOrangeGradientBottomStyle(BORDER_RADIUS2);
    ui->buttonOk->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonOk->objectName()),12);

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

void PatternSelectWidget::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_imageButtonList.size(); i++)
    {
        m_imageButtonList.at(i)->setLabelNamePos(1);
    }

    ui->labelPageNum->setAlignment(Qt::AlignLeft| Qt::AlignVCenter);
    ui->labelX->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    ui->labelPriorityValue->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    ui->labelReverseWayValue->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
}

//初始化
void PatternSelectWidget::initialize()
{
    m_firstFilePath.clear();
    m_curFilePath.clear();
    m_fileItemList.clear();

    m_curPages = 1;//花样选择界面当前页数
    m_backUpDirPages = 1;//上一级当前页数
    m_pageNums = 1;//总页数
    m_selectedPattenIdx = -1;//被选中的花版号

    initPattern();
}

//初始化花样
void PatternSelectWidget::initPattern()
{
    //花样文件目录
    QDir apppath(qApp->applicationDirPath());
    QString filePath = apppath.path() + apppath.separator() + PATTERNPATH;
    m_firstFilePath = QDir(filePath).absolutePath();//为了将"\"变为"/"
    getDirPatternFiles(m_firstFilePath);
}

//获取花样文件下的路径或者花样
void PatternSelectWidget::getDirPatternFiles(QString dirPath)
{
    m_curFilePath = dirPath;//记录当前目录
    if(m_curFilePath == m_firstFilePath)//如果当前目录为一级目录
    {
        ui->buttonBackUpDir->setEnabled(false);//设置按钮不可按(返回上级目录按钮)
    }
    else
    {
        ui->buttonBackUpDir->setEnabled(true);//设置按钮可按(返回上级目录按钮)
    }

    createCurDirPatterns();
}

//刷新界面显示
void PatternSelectWidget::refreshPageUi()
{
    int itemNum;
    if (m_fileItemList.size() <= 0)
    {
        itemNum = 0;

        for (int i = 0; i < m_itemPerPage; i++)
        {
            m_imageButtonList.at(i)->hide();
        }
        ui->labelPageNum->setText(tr("PageNum: 0/0"));//页数: 0/0
        ui->buttonPgUp->setEnabled(false);
        ui->buttonPgDn->setEnabled(false);
        ui->buttonOk->setEnabled(false);

        clearFileInfo();
        return;
    }
    else
    {
        itemNum = m_fileItemList.size();
    }

    m_pageNums = (itemNum + m_itemPerPage - 1)/m_itemPerPage;// 计算页数
    if (m_curPages > m_pageNums)// 当前页
    {
        m_curPages = m_pageNums;
    }
    if (m_curPages <= 1)
    {
        m_curPages = 1;
    }

    int itemidx = (m_curPages - 1) * m_itemPerPage;

    for (int i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < itemNum)
        {
            QImage image = m_fileItemList.at(itemidx).getPreviewImage();
            m_imageButtonList[i]->setPreviewImage(image);
            m_imageButtonList[i]->setLabelName(m_fileItemList.at(itemidx).getShowInfo());
            m_imageButtonList.at(i)->show();

            itemidx++;
        }
        else
        {
            m_imageButtonList.at(i)->hide();
        }
    }

    // 翻页按钮
    if (m_curPages <= 1)
    {
        ui->buttonPgUp->setEnabled(false);
    }
    else
    {
        ui->buttonPgUp->setEnabled(true);
    }
    if (m_curPages >= m_pageNums)
    {
        ui->buttonPgDn->setEnabled(false);
    }
    else
    {
        ui->buttonPgDn->setEnabled(true);
    }

    // 页信息
    if(m_pageNums == 0)
    {
        m_curPages = 0;
    }

    // 页信息
    QString str = tr("pageNum: ") + QString("%1/%2").arg(m_curPages).arg(m_pageNums);//页数:
    ui->labelPageNum->setText(str);

    //refreshCheckedPage();
    refreshChecked();
}

//刷新条目选中状态
void PatternSelectWidget::refreshCheckedPage()
{
    int num =m_fileItemList.size();
    if (num <= m_selectedPattenIdx)//没有花版 num = 0
    {
        m_selectedPattenIdx = -1;
    }

    if(m_selectedPattenIdx == -1)//被选中的花版号初始化的时候就是-1
    {
        clearFileInfo();//清空花样信息
        ui->buttonOk->setEnabled(false);
    }
    else
    {
        ui->buttonOk->setEnabled(true);
    }

    // 刷新页面中被选择的条目
    for(int var = 0; var < m_itemPerPage; var++)//var < 花样选择界面每页图片数
    {
        int idx = (m_curPages - 1) * (m_itemPerPage) + var;
        if(m_selectedPattenIdx == idx)//选中的花版号等于 idx
        {
            QString filePath = m_fileItemList.at(m_selectedPattenIdx).getFilePath();//m_fileItemList 花样列表，从0开始
            QFileInfo file(filePath);
            if(file.isDir())//为文件夹
            {
                m_selectedPattenIdx = -1;
                m_backUpDirPages = m_curPages;//获取当前页数，从文件夹返回上一级时，返回到这页
                m_curPages = 1;//如果位文件夹，打开默认显示第一页
                getDirPatternFiles(filePath);
                return;
            }

            //所选文件
            QString ext = file.suffix().toUpper();
            getFileInfo(filePath,ext);//获取花样信息

            // 条目被选中
            m_imageButtonList.at(var)->setCheckable(true);
            m_imageButtonList.at(var)->setChecked(true);
        }
        else
        {
            // 不被选中
            m_imageButtonList.at(var)->setChecked(false);
            m_imageButtonList.at(var)->setCheckable(false);
        }
    }
}

void PatternSelectWidget::refreshChecked()
{
    int num =m_fileItemList.size();
    if (num <= m_selectedPattenIdx)//没有花版 num = 0
    {
        m_selectedPattenIdx = -1;
    }

    if(m_selectedPattenIdx == -1)//被选中的花版号初始化的时候就是-1
    {
        clearFileInfo();//清空花样信息
        ui->buttonOk->setEnabled(false);
    }
    else
    {
        ui->buttonOk->setEnabled(true);
    }

    // 刷新页面中被选择的条目
    for(int var = 0; var < m_itemPerPage; var++)//var < 花样选择界面每页图片数
    {
        int idx = (m_curPages - 1) * (m_itemPerPage) + var;
        if(m_selectedPattenIdx == idx)//选中的花版号等于 idx
        {
            if(m_selectedPattenIdx == -1 ||
                    m_selectedPattenIdx >= m_fileItemList.size())
            {
                break;
            }
            QString filePath = m_fileItemList.at(m_selectedPattenIdx).getFilePath();//m_fileItemList 花样列表，从0开始
            QFileInfo file(filePath);
            if(file.isDir())//为文件夹
            {
                m_selectedPattenIdx = -1;
                getDirPatternFiles(filePath);
                return;
            }

            // 条目被选中
            m_imageButtonList.at(var)->setCheckable(true);
            m_imageButtonList.at(var)->setChecked(true);
        }
        else
        {
            // 不被选中
            m_imageButtonList.at(var)->setChecked(false);
            m_imageButtonList.at(var)->setCheckable(false);
        }
    }
}

//点击花样图片
void PatternSelectWidget::clickItem(int idx)
{
    if(m_fileItemList.size() <= 0)
    {
        return;
    }
    m_selectedPattenIdx = (m_curPages - 1) * m_itemPerPage + idx - 1;
    refreshCheckedPage();
}

//清空花样信息
void PatternSelectWidget::clearFileInfo()
{
    ui->labelColorNumValue->clear();
    ui->labelDirectionValue->clear();
    ui->labelPatternHeightValue->clear();
    ui->labelPatternNameValue->clear();
    ui->labelPatternWidthValue->clear();
    ui->labelPriorityValue->clear();
    ui->labelReverseNumValue->clear();
    ui->labelReverseWayValue->clear();
    ui->labelReverSpaceValue->clear();
    ui->labelRotateValue->clear();
    ui->labelScaleValue->clear();
    ui->labelTotalNeedleValue->clear();
    ui->labelXValue->clear();
    ui->labelYValue->clear();
}

//获取花样信息
void PatternSelectWidget::getFileInfo(QString filePath, QString suffix)
{
    QFileInfo file(filePath);
    QString fileName = file.fileName();
    int size = fileName.length();
    if(size > NAMEMAXLENGTH)//花样名称过长时截取
    {
        fileName = fileName.mid(0,NAMEMAXLENGTH) + "~";
    }

    if(suffix == "DST")//dst文件
    {
        //qDebug()<<"dst click begin";

        DataFileDst dst;
        dst.initFile(filePath);

        //qDebug()<<"dst.convertDataToAbs() begin";
        dst.convertDataToAbs();
        //qDebug()<<"dst.convertDataToAbs() end";

        ui->labelPatternNameValue->setText(fileName);
        ui->labelTotalNeedleValue->setText(QString::number(dst.getStitchNums()));
        ui->labelColorNumValue->setText(QString::number(dst.getColorNums()));

        double width = dst.getDatWidth()*0.01;
        ui->labelPatternWidthValue->setText(QString("%1").arg(width));

        double height = dst.getDatHeight()*0.01;
        ui->labelPatternHeightValue->setText(QString("%1").arg(height));

        double maxX = dst.getMaxX()*0.01;
        double minX = dst.getMinX()*0.01;
        ui->labelXValue->setText(QString("(%1,%2)").arg(maxX).arg(minX));

        double maxY = dst.getMaxY()*0.01;
        double minY = dst.getMinY()*0.01;
        ui->labelYValue->setText(QString("(%1,%2)").arg(maxY).arg(minY));

        QByteArray bsMap;
        bsMap.clear();
        memset(m_beadSequinTable,0,sizeof(m_beadSequinTable));
        dst.getBeadSequinMap(bsMap);       // 得到有效珠片码的位图
        memcpy(m_beadSequinTable,bsMap.data(),bsMap.size());
    }
    else if(suffix == "DSR")//dsr文件
    {
        DataFileDsr dsr;
        dsr.initFile(filePath);
        dsr.convertDataToEmbAbs();

        ui->labelPatternNameValue->setText(fileName);
        ui->labelTotalNeedleValue->setText(QString::number(dsr.getStitchNums()));
        ui->labelColorNumValue->setText(QString::number(dsr.getColorNums()));

        double width = dsr.getDatWidth()*0.01;
        ui->labelPatternWidthValue->setText(QString("%1").arg(width));

        double height = dsr.getDatHeight()*0.01;
        ui->labelPatternHeightValue->setText(QString("%1").arg(height));

        double maxX = dsr.getMaxX()*0.01;
        double minX = dsr.getMinX()*0.01;
        ui->labelXValue->setText(QString("(%1,%2)").arg(maxX).arg(minX));

        double maxY = dsr.getMaxY()*0.01;
        double minY = dsr.getMinY()*0.01;
        ui->labelYValue->setText(QString("(%1,%2)").arg(maxY).arg(minY));
    }

    //qDebug()<<"get patternpara begin";

    //得到花样参数
    DataFileHead filehead;
    memset(&filehead,0,sizeof(DataFileHead));
    QString fPath = filePath + ".fcg";
    QFile sfile(fPath);
    if(sfile.exists())//存在fcg文件
    {
        if(sfile.open(QIODevice::ReadOnly))
        {
            QByteArray ary = sfile.readAll();

            if((u32)ary.size() >= sizeof(DataFileHead))
            {
                memcpy(&filehead,ary.data(),sizeof(DataFileHead));
            }
        }
        sfile.close();
    }

    //存在fcg的文件时fcg的数据
    s16 para1 = filehead.rotateStyle;    //旋转式样
    QString str1;
    switch (para1)
    {
    case 0:
        str1 = "p";
        break;
    case 1:
        str1 = "q";
        break;
    case 2:
        str1 = "b";
        break;
    case 3:
        str1 = "d";
        break;
    default:
        str1 = "p";
        break;
    }
    ui->labelDirectionValue->setText(str1);

    s16 para2 = filehead.rotateAngle;    //旋转角度
    ui->labelRotateValue->setText(QString::number(para2));

    s16 para3 = filehead.xZoom;          //X向倍率
    s16 para4 = filehead.yZoom;          //Y向倍率
    if(para3 < 50 || para3 > 200){para3 = 100;}
    if(para4 < 50 || para4 > 200){para4 = 100;}
    ui->labelScaleValue->setText("("+QString::number(para3)+","+QString::number(para4)+")");

    s16 para5 = filehead.repeatStyle;    //反复方式
    QString str5;
    switch (para5)
    {
    case 0:
        str5 = tr("UsualRepeat");//通常反复
        break;
    case 1:
        str5 = tr("XSymmetry");//X轴对称
        break;
    case 2:
        str5 = tr("YSymmetry");//Y轴对称
        break;
    case 3:
        str5 = tr("XYSymmetry");//XY对称
        break;
    case 4:
        str5 = tr("UsualByColor");//按色通常
        break;
    case 5:
        str5 = tr("BasisColorX");//按色X轴
        break;
    case 6:
        str5 = tr("BasisColorY");//按色Y轴
        break;
    case 7:
        str5 = tr("BasisColorXY");//按色XY
        break;
    default:
        str5 = tr("UsualRepeat");//通常反复
        break;
    }
    ui->labelReverseWayValue->setText(str5);

    s16 para6 = filehead.priority;       //优先次序
    QString str6;
    switch (para6)
    {
    case 0:
        str6 = tr("HorFirst");//先绣横向
        break;
    case 1:
        str6 = tr("VerFirst");//先绣纵向
        break;
    default:
        str6 = tr("HorFirst");//先绣横向
        break;
    }
    ui->labelPriorityValue->setText(str6);

    s16 para7 = filehead.xRepeatNum;     //X向反复次数
    s16 para8 = filehead.yRepeatNum;     //Y向反复次数
    if(para7 < 1 || para7 > 200){para7 = 1;}
    if(para8 < 1 || para8 > 200){para8 = 1;}
    ui->labelReverseNumValue->setText("("+QString::number(para7)+","+QString::number(para8)+")");
    s16 para9 ;
    s16 para10;
    if(!sfile.exists())//存在不fcg文件
    {
        para9 = 2;   //X向反复间距
        para10 =2;  //Y向反复间距
    }
    else
    {
        para9 = filehead.xRepeatSpace;   //X向反复间距
        para10 = filehead.yRepeatSpace;  //Y向反复间距
    }

    //    if(para9 < -30000 || para9 > 30000){para9 = 300;}
    //    if(para10 < -30000|| para10 > 30000){para10 = 300;}
    ui->labelReverSpaceValue->setText("("+QString::number(para9)+","+QString::number(para10)+")");

    //qDebug()<<"get patternpara end";
}

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

//设置主title
void PatternSelectWidget::setMainTitle(QString str)
{
    ui->labelMainTitle->setText(str);
}

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

//生成当前路径花样
void PatternSelectWidget::createCurDirPatterns()
{
    m_fileItemList.clear();
    QDir dir(m_curFilePath);

    // 打开文件所在的路径
    if(!dir.exists())
    {
        m_curPages = 0;
        m_pageNums = 0;
        qDebug() << "dirpath not exist, name=" << m_curFilePath;

        dir.mkdir(m_curFilePath);//创建花样文件夹
    }

    FileItem item;
    QString fileName;
    QString filePath;
    DataFileDst dst;
    DataFileDsr dsr;

    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);  // 设置类型过滤器，只为文件夹和dst文件格式
    dir.setSorting(QDir::DirsFirst | QDir::Time | QDir::IgnoreCase);  // 设置排序方式

    QFileInfoList fileList = dir.entryInfoList();
    int count = fileList.count();
    for(int i = 0; i < count; i++)
    {
        QImage image(QSize(ui->buttonImage1->labelImage->width(), ui->buttonImage1->labelImage->height()), IMAGE_TYPE);
        QFileInfo fileInfo = fileList[i];

        if(fileInfo.isDir())//为文件夹
        {
            //QString imageName = ":/images/folder.png";
            filePath = fileInfo.absoluteFilePath();
            fileName = fileInfo.baseName();
            if(g_emResolut == resolution1910)
            {
                image.load(":/images/folderBig.png");
            }
            else
            {
                image.load(":/images/folder.png");
            }
            item.setFileInfo(filePath,fileName,image);
            m_fileItemList.append(item);
        }
        else//为文件
        {
            filePath = fileInfo.absoluteFilePath();
            fileName = fileInfo.fileName();
            QString imageName = filePath + ".preview.png";
            QFile imageFile(imageName);

            if(fileInfo.suffix().toUpper() == "DST")//为dst文件
            {
                if(!imageFile.exists())//图片不存在时生成图片
                {
                    //重新改变图片大小，因为文件夹的图标大小与图片大小不同
                    dst.initColor(g_pSettings->getColorRgbArray().size(),(QRgb*)g_pSettings->getColorRgbArray().data());
                    dst.initFile(filePath);
                    dst.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
            else if(fileInfo.suffix().toUpper() == "DSR")//dsr文件
            {
                if(!imageFile.exists())//图片不存在时生成图片
                {
                    dsr.initColor(g_pSettings->getColorRgbArray().size(),(QRgb*)g_pSettings->getColorRgbArray().data());
                    dsr.initFile(filePath);
                    dsr.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
        }
    }

    refreshPageUi();
    refreshChecked();
}

//获取绘图区域大小
QSize PatternSelectWidget::getImageSize()
{
    QSize size = ui->buttonImage1->labelImage->size();
    return size;
}

void PatternSelectWidget::on_buttonImage1_clicked()
{
    clickItem(1);
}

void PatternSelectWidget::on_buttonImage2_clicked()
{
    clickItem(2);
}

void PatternSelectWidget::on_buttonImage3_clicked()
{
    clickItem(3);
}

void PatternSelectWidget::on_buttonImage4_clicked()
{
    clickItem(4);
}

void PatternSelectWidget::on_buttonImage5_clicked()
{
    clickItem(5);
}

void PatternSelectWidget::on_buttonImage6_clicked()
{
    clickItem(6);
}

void PatternSelectWidget::on_buttonImage7_clicked()
{
    clickItem(7);
}

void PatternSelectWidget::on_buttonImage8_clicked()
{
    clickItem(8);
}

void PatternSelectWidget::on_buttonImage9_clicked()
{
    clickItem(9);
}

void PatternSelectWidget::on_buttonImage10_clicked()
{
    clickItem(10);
}

void PatternSelectWidget::on_buttonBackUpDir_clicked()
{
    if(m_curFilePath.size() <= 0)
    {
        return;
    }

    QDir dir(m_curFilePath);
    dir.cdUp();//返回上级目录
    QString path = dir.absolutePath();//得到上级目录
    m_fileItemList.clear();
    m_curPages = m_backUpDirPages;
    m_selectedPattenIdx = -1;
    getDirPatternFiles(path);//打开上级目录
}

void PatternSelectWidget::on_buttonPgUp_clicked()
{
    m_curPages--;
    refreshPageUi();
}

void PatternSelectWidget::on_buttonPgDn_clicked()
{
    m_curPages++;
    refreshPageUi();
}

void PatternSelectWidget::on_buttonOk_clicked()
{
    if(m_selectedPattenIdx < 0)
    {
        return;
    }

    int patternNeedles = ui->labelTotalNeedleValue->text().toInt();
    if(patternNeedles > EMBALLOWNEEDLELIMIT)//大于200万针
    {
        PromptDialog promptDlg(this);
        promptDlg.initDialog(PromptDialog::BTN_OK);
        promptDlg.setTitleStr(tr("Prompt"));

        QString str;
        //所选花样针数已达上限(200万针)，不可绣作！
        str = tr("The number of stitches of the selected pattern has reached the upper limit (2 million stitches), and it cannot be embroidered!");
        promptDlg.setContentStr(str);

        promptDlg.exec();
        return;
    }

    emit siSelectPattern(m_fileItemList.at(m_selectedPattenIdx).getFilePath());

    //this->hide();
}

void PatternSelectWidget::on_buttonCancel_clicked()
{
    this->hide();
}

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

void PatternSelectWidget::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;
}
