#include "datafiledsr.h"


DataFileDsr::DataFileDsr()
{
    m_colorNum = 0;//颜色数
    m_pColor = NULL;//颜色rgb值
}

DataFileDsr::~DataFileDsr()
{

}

void DataFileDsr::initColor(int cnum, QRgb *pColor)
{
    m_colorNum = cnum;//颜色数
    m_pColor = pColor;//颜色rgb值
}

void DataFileDsr::initFile(const QString &fullPathName)
{
    clear();
    QFileInfo file(fullPathName);
    if (file.exists() && file.isFile())
    {
        m_fileFullPathName = fullPathName;
        m_fileName = fullPathName;
    }
    else
    {
        qDebug() << "Init file failed path =" << m_fileFullPathName;
    }
}

//检查dsr文件版本，非5.2以上版本和错误格式返回-1
int DataFileDsr::checkDsrVersion()
{
    loadFile();     // 如果数据未读取，重新读取

    int size = m_fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dsr size less then headsize");
        return -1;
    }
    DsrHead * dsrHead = (DsrHead *)(m_fileData.data());
    float ver = *((float*)(&dsrHead->verCode))+0.1;
    if(ver < DSR_VERSION_5)// 5.x 以下版本
    {
        return -1;
    }

    if(ver >= DSR_VERSION_6_3)//6.3版本
    {
        if (size <= (int)(sizeof(DsrHead63)))
        {
            qDebug("dsr size less then headsize");
            return -1;
        }
    }
    if(dsrHead->dataBegin > (u32)size)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    size -= dsrHead->dataBegin;
    if (size <= 0)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    int stepsize = size/sizeof(DsrStep);
    if (stepsize <= 0)
    {
        qDebug("dsr data size err");
        return -1;
    }
    if (stepsize > PATTERN_LARGE_NEEDLES)//128万针
    {
        qDebug("dsr data size big");
        return -2;
    }

    return stepsize;
}

// 转换为绝对数据
void DataFileDsr::convertDataToEmbAbs()
{
    m_embAbsData.clear();

    getDsrMinMax();//读取dsr源文件

    int size = m_fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dsr size less then headsize");
        return;
    }
    DsrHead * dsrHead = (DsrHead *)(m_fileData.data());//读取dsr源文件的头文件的结构体
    if(dsrHead->dataBegin > (u32)size)
    {
        qDebug("dsr dataBegin err");
        return;
    }
    size -= dsrHead->dataBegin;

    if (size <= 0)
    {
        qDebug("dsr dataBegin err");
        return;
    }
    int stepsize = size/sizeof(DsrStep);
    if (stepsize <= 0)
    {
        qDebug("dsr data size err");
        return;
    }
    DsrStep * dsrDataBeg = (DsrStep *)((m_fileData.data() + dsrHead->dataBegin));

    // 绝对坐标数据
    DataDs16FileHead dhead;
    memset(&dhead, 0, sizeof(DataDs16FileHead));

    QByteArray absData;//绝对坐标
    absData.clear();
    DsAbsItem absItem;
    memset(&absItem,0,sizeof(DsAbsItem));

    DsrStep * dsrDataPtr = dsrDataBeg;
    DsrStep * dsrDataPtrTemp = dsrDataBeg;

    int stepidx = 0;
    BYTE ctrl,attr,beforeCtrl;
    int runflag = 0;
    beforeCtrl = 0;
    int colorNum = 1;
    s16 towelHighNum = 1;
    int dataEMB = 0;
    int dataLASER = 0;
    int dataCHEN = 0;
    int dataCOIL = 0;
    double xfactor ;
    double yfactor ;
    double rfactor ;
    if (dsrHead->xyUnit == 0) //  0：单位0.1mm; 1: 0.01mm; 2: mm
    {
        xfactor = DSR_EMB_DATADIRX*10;
        yfactor = DSR_EMB_DATADIRY*10;
    }
    else if (dsrHead->xyUnit == 2)
    {
        xfactor = DSR_EMB_DATADIRX*100;
        yfactor = DSR_EMB_DATADIRY*100;
    }
    else
    {
        xfactor = DSR_EMB_DATADIRX;
        yfactor = DSR_EMB_DATADIRY;
    }
    if (dsrHead->rUnit == 0)    // 0：单位0.36度; 1: 0.036度; 2: 度; 3, 1/10000弧度;
    {
        rfactor = 2*PI*10 * DSR_EMB_DATADIRR;
    }
    else if (dsrHead->rUnit == 1)
    {
        rfactor = 2*PI * DSR_EMB_DATADIRR;
    }
    else
    {
        rfactor = DSR_EMB_DATADIRR;
    }

    int ax,ay,ar;
    ax = ay = ar = 0;
    for (int i = 0; i < stepsize; i++)
    {
        ctrl = dsrDataPtr->ctrl;
        attr = dsrDataPtr->attr;
        ax = dsrDataPtr->dx;
        ay = dsrDataPtr->dy;
        ar = dsrDataPtr->dr;

        if  (ctrl == DATA_PAUSE_OLD)	// 暂停
        {
            ctrl = DATA_PAUSE;
        }
        if  (ctrl == DATA_ANGLE_OLD)	// 拐点
        {
            ctrl =  DATA_ANGLE;
        }
        if  (ctrl == DATA_CUT_OLD)	// 剪线
        {
            ctrl =  DATA_CUTTRD;
        }
        if  (ctrl == DATA_END_OLD)	// 结束码
        {
            ctrl =  DATA_END;
        }
        if  (ctrl == DATA_CHGND_OLD)	// 换色功能码
        {
            ctrl =  DATA_CHGND;
        }

        //判断冲缝绣三种针步间的转换是否有换色码，若没有需要插入换色码
        if(beforeCtrl != ctrl)
        {
            //等于冲缝绣任意一种针步
            if(ctrl == DSR_SEWING || ctrl == DSR_PUNCH || ctrl == DSR_EMB)
            {
                if(beforeCtrl != 0)
                {
                    //判断前一针步是否为换色
                    dsrDataPtr--;
                    if(dsrDataPtr->ctrl == DSR_CHGND)
                    {
                        dsrDataPtr++;
                    }
                    else
                    {
                        //插入换色码
                        absItem.ctrl = DATA_CHGND;
                        absItem.attr = 0;
                        absItem.action = 0;
                        absItem.ax = ax * xfactor;
                        absItem.ay = ay* yfactor;
                        absItem.ar = ar  * rfactor;
                        absData.append((char*)(&absItem), sizeof(DsAbsItem));
                        dsrDataPtr++;
                        colorNum++;
                    }
                }
                beforeCtrl = ctrl;
            }
        }

        if (dsrDataPtr->ctrl == DSR_CHGND)    // 换色
        {
            ctrl = DATA_CHGND;
            colorNum++;
        }

        if (dsrDataPtr->ctrl == DSR_TOWELHIGH)    // 毛巾高度
        {
            ctrl = DATA_TOWELHIGH;
            towelHighNum++;
        }

        //判断dsr花版里是不是有以下数据
        if(dsrDataPtr->ctrl == DSR_EMB)// bit2,平绣数据有无	0,无	1,有
        {
            dataEMB = 1;
        }
        if(dsrDataPtr->ctrl == DSR_LASER)// bit3,激光数据有无	0,无	1,有
        {
            dataLASER = 1;
        }
        if(dsrDataPtr->ctrl == DSR_CHENILLE ||
                dsrDataPtr->ctrl == DSR_CHAIN)// bit4,毛巾链式数据有无	0,无	1,有
        {
            dataCHEN = 1;
        }
        if(dsrDataPtr->ctrl == DSR_COIL ||
                dsrDataPtr->ctrl == DSR_SAWTOOTH ||
                dsrDataPtr->ctrl == DSR_RIBBON)// bit5,缠绕,锯齿,盘带,数据有无	0,无	1,有
        {
            dataCOIL = 1;
        }

#if(1)
        //判断是否要改变第一针的属性
        if(ctrl == DSR_JUMP)
        {
            if (runflag == 0)
            {
                runflag = 1;
            }
            runflag++;
        }
        else if(ctrl == DSR_EMB)//是否转换为跳针
        {
            if ((runflag == 0 || runflag >= 3) && (i >= 0))   // 第一个运针是入针
            {
                dsrDataPtr++;
                u8 ctl = dsrDataPtr->ctrl;
                if(ctl == DSR_EMB)//下一针还为绣花针步时才转换为跳针
                {
                    ctrl = DATA_JUMP;
                }
                dsrDataPtr--;
                runflag = 1;
            }
            //else if (i == 0 && ddx == 0 && ddy == 0)   // 第一针，入针，向后扫描，如果有连续的三个跳针，则将第一针入针转换为跳针 ljs
            else if (i == 0)   // 20230511 第一针，入针，向后扫描，如果有连续的三个跳针，则将第一针入针转换为跳针 ljs
            {
                int count = 0;
                do
                {
                    dsrDataPtrTemp++;
                    if  (dsrDataPtr->ctrl == DSR_JUMP)
                    {
                        count++;
                        if (dsrDataPtrTemp->dx == 0 && dsrDataPtrTemp->dy == 0)   // 空跳，直接变成跳针
                        {
                            count += 2;
                        }
                    }
                    else
                    {
                        break;
                    }
                }while(1);
                if  (count >= 3)
                {
                    ctrl = DATA_JUMP;
                    runflag = 2;
                }
                else
                {
                    runflag = 1;
                }
            }
            else
            {
                runflag = 1;
            }

            //第一针位移都为0时下一针也转换为跳针
//            if(i == 0 && ddx == 0 && ddy == 0)
//            {
//                runflag = 3;
//            }
        }
        else if (ctrl == DATA_CHGND)    // 换色
        {
            runflag = 10;
        }
        else
        {
            runflag = 0;
        }
#endif

        absItem.ctrl = ctrl;
        absItem.attr = attr;
        absItem.action = dsrDataPtr->action;
        absItem.ax = ax * xfactor;
        absItem.ay = ay * yfactor;
        absItem.ar = ar * rfactor;

        absData.append((char*)(&absItem), sizeof(DsAbsItem));

        stepidx++;
        dsrDataPtr++;
    }

    int newstepnum = stepidx;    // 转换后的数据长度

    // 文件头转换
    QString name = getFileFullName();
    int namelen = name.size();
    if (namelen > HEAD_NAME_STR_LEN)
    {
        namelen = HEAD_NAME_STR_LEN;
    }
    memcpy(dhead.fileName, name.data(), namelen);   // 文件名称
    dhead.dataSize = newstepnum*sizeof(DsAbsItem);    // 数据字节数
    dhead.itemNums = newstepnum;                    // 数据项个数
    dhead.bytesPerItem = sizeof(DsAbsItem);           // 每项占的字节数
    dhead.bytesPerBlk = MAX_EXDP_LEN;               // 数据内容划分块大小
    dhead.dataChecksum = calcCheckSum32((u8 *)(absData.data()) , absData.length());		// 数据累加校验和
    dhead.checkCrc = calcCrc16((u8 *)(&dhead), HEAD_FIX_INFO_LEN);	// 前面6个字段的CRC校验，（6个字段分别为：文件名称，字节数，项个数，每项字节数，每块字节数，数据累加和的CRC校验值）
    u32 fileID = 0;
    fileID = calcCheckSum32((u8 *)(absData.data()) , absData.length());		// 原始数据累加校验和
    dhead.fileid = fileID;  //中间数据的 fileid  =

    dhead.anchorX = 0;                  // 定位点坐标X
    dhead.anchorY = 0;                  // 定位点坐标Y
    dhead.beginX = dsrHead->startX;// 数据起点坐标X
    dhead.beginY = dsrHead->startY;// 数据起点坐标Y
    dhead.beginR = 0;
    dhead.minX = m_minX;
    dhead.maxX = m_maxX;
    dhead.minY = m_minY;
    dhead.maxY = m_maxY;                // 轮廓范围，使用重新计算之后的值
    dhead.colorNum = colorNum;
    dhead.towelHighNum = towelHighNum;
    dhead.offsetEn = dsrHead->offsetEn;//中间数据的偏移点XY  =   dsr头文件的偏移点XY允许

    if(dataEMB == 1)// bit2,平绣数据有无	0,无	1,有
    {
        dhead.offsetEn = dhead.offsetEn | 0x04;
    }
    if(dataLASER == 1)// bit3,激光数据有无	0,无	1,有
    {
        dhead.offsetEn = dhead.offsetEn | 0x08;
    }
    if(dataCHEN == 1)// bit4,毛巾链式数据有无	0,无	1,有
    {
        dhead.offsetEn = dhead.offsetEn | 0x10;
    }
    if(dataCOIL == 1 )// bit5,缠绕,锯齿,盘带,数据有无	0,无	1,有
    {
        dhead.offsetEn = dhead.offsetEn | 0x20;
    }
    else
    {
        dhead.offsetEn = dhead.offsetEn | 0x00;
    }
    dhead.offsetX = dsrHead->offsetX;
    dhead.offsetY = dsrHead->offsetY;

    //dsr头文件中的以何种工作机头定点
    dhead.begHead = dsrHead->begWorkHead;//中间数据的机头   等于    dsr头文件的机头
    memcpy(dhead.switchTable,dsrHead->switchTable,sizeof(dhead.switchTable));//如果文件有色序会自动设置为文件中的色序

    // 保存文件头到数组中
    m_embAbsData.append((char *)(&dhead), sizeof(DataDs16FileHead));

    // 保存数据到数组中
    m_embAbsData.append(absData);
}

int DataFileDsr::createPreviewImage(QImage *pImg, int saveflag, int penwidth, int gradientFlag, int reDraw)
{
#if(1)
    if(reDraw == 0)//图片存在则不重画
    {
        // 图片是否存在，存在则返回
        QString previewPath = getFileFullPathName() + ".preview.png";
        QFile imageFile(previewPath);
        if (imageFile.exists())
        {
            return 0;
        }
    }
#endif

    int newimgflag = 0;
    QImage * pImage;
    int width, height;
    if (pImg == NULL)
    {
        width = DSR_PREVIEW_WIDTH;
        height = DSR_PREVIEW_HEIGHT;
        pImage = new QImage(width, height, IMAGE_TYPE);
        newimgflag = 1;
    }
    else
    {
        pImage = pImg;
    }

    width = pImage->width();
    height = pImage->height();

    if (width <= DSR_PREVIEW_SIDE*2 || height <= DSR_PREVIEW_SIDE*2)
    {
        if (pImage != NULL && newimgflag == 1)
        {
            delete pImage;
        }
        qDebug("preview img too small");
        return -1;
    }

    memset(pImage->bits(), 0x00, pImage->byteCount());

    QPainter painter(pImage);
    QColor backcolor(255, 255, 255, 0);         // 透明背景

    // 背景
    QPen pen;
    pen.setWidth(penwidth);
    pen.setColor(backcolor);
    painter.setPen(pen);
    painter.setBrush(backcolor);
    painter.drawRect(0, 0, width, height);

    QColor backColor1;
    QColor backColor2;

    getDsrMinMax();
    // 图形
    int size = m_fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dsr size less then headsize");
        return -1;
    }
    DsrHead * dsrHead = (DsrHead *)(m_fileData.data());
    if(dsrHead->dataBegin > (u32)size)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    size -= dsrHead->dataBegin;
    if (size <= 0)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    int stepsize = size/sizeof(DsrStep);
    if (stepsize <= 0)
    {
        qDebug("dsr data size err");
        return -1;
    }

    DsrStep * dsrDataBeg = (DsrStep *)((m_fileData.data() + dsrHead->dataBegin));

    // 图形显示区域
    int dpminx = DSR_PREVIEW_SIDE;
    int dpmaxx = width - DSR_PREVIEW_SIDE;
    int dpminy = DSR_PREVIEW_SIDE + DSR_PREVIEW_SIDE;
    int dpmaxy = height - DSR_PREVIEW_SIDE;

    // 计算缩放系数
    double factor, temp;
    factor = (double)(abs(m_maxX - m_minX)) / (dpmaxx - dpminx);      // 按x计算的缩放系数
    temp =   (double)(abs(m_maxY - m_minY)) / (dpmaxy - dpminy);      // 按轮廓计算，最小能够放下重复次数个图形
    if (temp >= factor)     // 使用较大的缩放系数
    {
        factor = temp;
    }

    // 计算显示参数，按照图形的实际位置显示（数据坐标零点对应图形中心）
    int dpx = (int)((dpminx+dpmaxx)/2 - ((m_maxX+m_minX)/factor)/2);
    int dpy = (int)((dpminy+dpmaxy)/2 - ((m_maxY+m_minY)/factor)/2);

    // 显示花样图形
    BYTE ctrlByte;
    //BYTE attrByte;
    int colorIdx;
    int oldcolor;

    colorIdx = 0;
    oldcolor = -1;

    WORD actionWord;	//附加动作
    double datposx, datposy;
    int curx, cury, prex, prey;
    curx = cury = prex = prey = 0;

    DsrStep * dsrDataPtr = dsrDataBeg;
    QColor beadColor;

    for (int i = 0; i < stepsize; i++)
    {
        // 读入一个针步数据
        ctrlByte = dsrDataPtr->ctrl;
        //attrByte = dsrDataPtr->attr;
        actionWord = dsrDataPtr->action;

        prex = curx;
        prey = cury;

        datposx = dsrDataPtr->dx;
        datposy = dsrDataPtr->dy;

        curx = (datposx) / factor + dpx;
        cury = (datposy) / factor + dpy;

        if (DSR_SHOWDIRX == -1)
        {
            curx = (width)-curx;
        }
        if (DSR_SHOWDIRY == -1)
        {
            cury = (height)-cury;
        }

        if(i == 0)
        {
            dsrDataPtr++;
            continue;
        }

        if ( ctrlByte == DSR_SEWING  ||
             ctrlByte == DSR_CUTTING ||
             ctrlByte == DSR_LASER   ||
             ctrlByte == DSR_JUMP    ||
             ctrlByte == DSR_PUNCH   ||
             ctrlByte == DSR_CHENILLE   ||
             ctrlByte == DSR_CHAIN   ||
             ctrlByte == DSR_COIL   ||
             ctrlByte == DSR_SAWTOOTH   ||
             ctrlByte == DSR_RIBBON   ||
             ctrlByte == DSR_EMB )
        {
            if (oldcolor != colorIdx)
            {
                int cidx = dsrHead->switchTable[colorIdx % EMB_BF_SW_ND];
                int cnum = m_colorNum;
                cnum /= sizeof(QRgb);
                if (cnum > EMB_BF_SW_ND)
                {
                    cnum = EMB_BF_SW_ND;
                }
                QColor sewcolor;
                if (cnum != 0)
                {
                    cidx %= cnum;
                    QRgb * pColor = m_pColor;
                    if(pColor != NULL)
                    {
                        sewcolor.setRgb(pColor[cidx]);
                    }
                    else
                    {
                        sewcolor = QColor(Qt::green);
                    }
                }
                else
                {
                    sewcolor = QColor(Qt::green);
                }

                pen.setColor(sewcolor);
                painter.setPen(pen);
                oldcolor = colorIdx;

                if(gradientFlag == 1)//渐变色绘制
                {
                    backColor2 = getBrightDec(sewcolor);
                    backColor1 = getBrightAdd(sewcolor);
                }
                beadColor = sewcolor;
            }

            //亮片或散珠动作
            //action1是0x20代表散珠或亮片动作,绘制散珠或亮片效果图
            if((actionWord & 0x20) == 0x20)
            {
                int cr = BEADRADIUS / factor;

                if(((actionWord >> 8) >= 0x01) && ((actionWord >> 8) <= 0x0F))//亮片
                {
                    QPen npen;
                    npen.setWidth(2);
                    npen.setColor(beadColor);
                    painter.setPen(npen);
                    painter.drawEllipse(curx-cr,cury-cr,cr*2,cr*2);
                    painter.drawEllipse((curx-cr)+cr/2+cr*0.3,(cury-cr)+cr/2+cr*0.3,cr*0.7,cr*0.7);
                }
                if(((actionWord >> 8) >= 0x11) && ((actionWord >> 8) <= 0x1F))//散珠
                {
                    QBrush brush;
                    brush.setColor(beadColor);//设置颜色
                    brush.setStyle(Qt::SolidPattern);//设置填充的风格，可以使用帮助文档查看有哪些风格
                    painter.setBrush(brush);
                    QPen npen(brush , 2);
                    painter.setPen(npen);
                    painter.drawEllipse(curx-cr,cury-cr,cr*2,cr*2);
                }
            }

            if(gradientFlag == 1)//渐变色绘制
            {
                QLinearGradient gradient(prex, prey, curx, cury);
                gradient.setColorAt(0.1,backColor2);
                gradient.setColorAt(0.5,backColor1);
                gradient.setColorAt(1.0,backColor2);

                painter.setRenderHint(QPainter::Antialiasing,true);
                QBrush brush(gradient);
                QPen npen(brush , penwidth);
                painter.setPen(npen);
            }
            painter.drawLine(prex, prey, curx, cury);
        }
        else if (ctrlByte == DSR_CHGND)    // 换色
        {
            colorIdx++;
        }
        else
        {
            //qDebug("other type=0x%x", ctrlByte);
        }

        dsrDataPtr++;
    }

    // 保存成文件
    QString preview = getFileFullPathName();
    if (saveflag != 0 && preview.isEmpty() == false)
    {
#if (1)
        preview += ".preview.png";
        pImage->save(preview, "png");
#endif
    }

    if (pImage != NULL && newimgflag == 1)
    {
        delete pImage;
    }

    return 0;
}

void DataFileDsr::clear()
{
    m_fileFullPathName.clear(); // 文件路径
    m_fileData.clear();         // 文件数据内容
    m_embAbsData.clear();       // 转换后的数据
}

void DataFileDsr::loadFile()
{    
    QFile rdfile(m_fileFullPathName);
    if(!rdfile.open(QIODevice::ReadOnly))
    {
        qDebug() << "open file fail when read, path =" << m_fileFullPathName;
        return;
    }

    m_fileData = rdfile.readAll();
    rdfile.close();

    int ret = checkFileCryption();
    if(ret > 0)//已加密
    {
        //解密
        int size = m_fileData.size();
        if (size <= (int)(sizeof(DsrHead)))
        {
            qDebug("dsr size less then headsize");
            return;
        }

        DsrHead * dsrHead = (DsrHead *)(m_fileData.data());
        if(dsrHead->dataBegin > (u32)size)
        {
            qDebug("dsr dataBegin err");
            return ;
        }
        size -= dsrHead->dataBegin;

        BYTE* pCryFactors = (BYTE*)(&dsrHead->dataBegin);
        BYTE* pData = (BYTE*)((m_fileData.data() + dsrHead->dataBegin));

        DsrCryption cry;
        cry.InitDsrCryptionCtrl(-1, dsrHead->cryWord, pCryFactors);

        int rslt = cry.DeCryption(pData, size);

        if (rslt == 0)
        {
            dsrHead->cryWord = 0;
        }
    }

    return;
}

void DataFileDsr::saveFile()
{
    QFile wrfile(m_fileFullPathName);
    if(!wrfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qDebug() << "open file fail when wirte, path =" << m_fileFullPathName;
        return;
    }
    else
    {
        wrfile.write(m_fileData);
#ifdef Q_OS_LINUX
        system("sync");
#endif
        wrfile.close();
    }
}

//偏移点XY写回dsr头文件
void DataFileDsr:: writeOffsetXYMoveToFile(s32 EnFlag,s32 offsetX,s32 offsetY)
{
    if(m_fileData.size() <= 0)
    {
        return;
    }

    DsrHead * pDsrHead = (DsrHead *)(m_fileData.data());

    pDsrHead->offsetEn = EnFlag;
    pDsrHead->offsetX = offsetX;
    pDsrHead->offsetY = offsetY;

    QFile wfile(m_fileFullPathName);
    if(!wfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qDebug() << "open file fail when read, path =" << m_fileFullPathName;
        return;
    }

    wfile.write(m_fileData);
#ifdef Q_OS_LINUX
        system("sync");
#endif
    wfile.close();

}

QByteArray DataFileDsr::getTowelHighTable(QString path)
{
    QByteArray towelHighTable;//dsr6.3毛巾高度
    towelHighTable.resize(TOWELHIGHBUF);
    memset(towelHighTable.data(),0,TOWELHIGHBUF);

    QFile rdfile(path);
    if(!rdfile.open(QIODevice::ReadOnly))
    {
        return towelHighTable;
    }

    QByteArray fileData = rdfile.readAll();
    rdfile.close();

    int size = fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dsr size less then headsize");
        return towelHighTable;
    }
    DsrHead * dsrHead = (DsrHead *)(fileData.data());//读取dsr源文件的头文件的结构体

    float ver = *((float*)(&dsrHead->verCode))+0.1;
    if(ver >= DSR_VERSION_6_3)//6.3版本-带毛巾高度
    {
        DsrHead63 * dsrHead63 = (DsrHead63 *)(fileData.data()+sizeof(DsrHead));
        memcpy(towelHighTable.data(),dsrHead63->towelHighTable,towelHighTable.length());
    }

    return towelHighTable;
}

//写入起绣点到文件中
void DataFileDsr::writePointToFile(u8 type, int x, int y, int st ,u8 workHead)
{
    if(st == 0){}
    if(m_fileData.size() <= 0)
    {
        return;
    }

    DsrHead * pDsrHead = (DsrHead *)(m_fileData.data());
    if(type == START_POINT)
    {
        pDsrHead->begWorkHead = workHead;//dsr头文件 == 主控中的机头
        pDsrHead->startX = x;
        pDsrHead->startY = y;
    }

    QFile wfile(m_fileFullPathName);
    if(!wfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qDebug() << "open file fail when read, path =" << m_fileFullPathName;
        return;
    }

    wfile.write(m_fileData);
#ifdef Q_OS_LINUX
        system("sync");
#endif
    wfile.close();

#ifdef Q_OS_LINUX
    system("sync");
#endif
}

QString DataFileDsr::getFileFullPath()
{
    QFileInfo file(m_fileFullPathName);
    return file.absoluteFilePath();
}

QString DataFileDsr::getFileFullName()
{
    QFileInfo file(m_fileFullPathName);
    return file.fileName();
}

QString DataFileDsr::getFileName()
{
    QFileInfo file(m_fileFullPathName);
    return file.completeBaseName();
}

QString DataFileDsr::getFileSuffix()
{
    QFileInfo file(m_fileFullPathName);
    return file.suffix();
}

int DataFileDsr::getStitchNums()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->itemNums;
}

int DataFileDsr::getColorNums()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->colorNum;
}

int DataFileDsr::getTowelHighNums()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->towelHighNum;
}

//测试fileid用，目前这个函数没用到
int DataFileDsr::getFileid()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->fileid;
}


int DataFileDsr::getDatWidth()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return (pDsrHead->maxX - pDsrHead->minX);
}

int DataFileDsr::getDatHeight()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return (pDsrHead->maxY - pDsrHead->minY);
}

int DataFileDsr::getMaxX()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->maxX;
}

int DataFileDsr::getMinX()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->minX;
}

int DataFileDsr::getMaxY()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->maxY;
}

int DataFileDsr::getMinY()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->minY;
}

int DataFileDsr::getJumpNeedleNum()
{
    if(m_embAbsData.size() <= 0)
    {
        return 0;
    }

    DataDs16FileHead * pDsrHead = (DataDs16FileHead *)((m_embAbsData.data()));
    return pDsrHead->jumpNeedleNum;
}

int DataFileDsr::checkFileCryption()
{
    int encryption = 0;

    int size = m_fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dsr size less then headsize");
        return -1;
    }
    DsrHead * dsrHead = (DsrHead *)(m_fileData.data());
    if(dsrHead->dataBegin > (u32)size)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    size -= dsrHead->dataBegin;
    if (size <= 0)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    int stepsize = size/sizeof(DsrStep);
    if (stepsize <= 0)
    {
        qDebug("dsr data size err");
        return -1;
    }

    if (dsrHead->cryWord != 0)
    {
        encryption = 1;
    }

    return encryption;
}

void DataFileDsr::getDsrMinMax()
{
    loadFile();     // 如果数据未读取，重新读取

    int size = m_fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dsr size less then headsize");
        return;
    }

    DsrHead * dsrHead = (DsrHead *)(m_fileData.data());
    if(dsrHead->dataBegin > (u32)size)
    {
        qDebug("dsr dataBegin err");
        return;
    }
    size -= dsrHead->dataBegin;
    if (size <= 0)
    {
        qDebug("dsr dataBegin err");
        return;
    }

    int stepsize = size/sizeof(DsrStep);
    if (stepsize <= 0)
    {
        qDebug("dsr data size err");
        return;
    }

    DsrStep * dsrDataBeg = (DsrStep *)((m_fileData.data() + dsrHead->dataBegin));
    DsrStep * dsrDataPtr = dsrDataBeg;
    m_maxX = S32_MIN;
    m_maxY = S32_MIN;
    m_minY = S32_MAX;
    m_minX = S32_MAX;

    BYTE ctrlByte;

    long curPitX = 0;
    long curPitY = 0;

    int i = 0;
    do
    {
        if (i < stepsize)
        {
            ctrlByte = dsrDataPtr->ctrl;

            if ( ctrlByte == DATA_EMB  ||
                 ctrlByte == DSR_SEWING ||
                 ctrlByte == DATA_JUMP ||
                 ctrlByte == DATA_OFFSET ||
                 ctrlByte == DATA_PUNCH ||
                 ctrlByte == DATA_CHENILLE ||
                 ctrlByte == DATA_CHAIN ||
                 ctrlByte == DATA_COIL ||
                 ctrlByte == DATA_SAWTOOTH ||
                 ctrlByte == DATA_RIBBON ||
                 ctrlByte == DATA_LASER ||
                 0 )
            {
                curPitX = dsrDataPtr->dx;
                curPitY = dsrDataPtr->dy;
            }
            dsrDataPtr++;
            i++;
        }
        else
        {
            break;
        }

        if (curPitX > m_maxX)
        {
            m_maxX = curPitX;
        }
        if (curPitX < m_minX)
        {
            m_minX = curPitX;
        }
        if (curPitY > m_maxY)
        {
            m_maxY = curPitY;
        }
        if (curPitY < m_minY)
        {
            m_minY = curPitY;
        }

    }while(1);

    return;
}

int DataFileDsr::checkDefaultSwitchTable(int colornum)
{
    //loadFile();     // 如果数据未读取，重新读取

    int size = m_fileData.size();
    if (size <= (int)(sizeof(DsrHead)))
    {
        qDebug("dst size less then headsize");
        return -1;
    }
    DsrHead * dsrHead = (DsrHead *)(m_fileData.data());
    if(dsrHead->dataBegin > (u32)size)
    {
        qDebug("dsr dataBegin err");
        return -1;
    }
    size -= dsrHead->dataBegin;
    int stepsize = size/sizeof(DsrStep);
    if (stepsize <= 0)
    {
        qDebug("dst data size err");
        return -1;
    }

    DsrHead * pDsrHead = (DsrHead *)((m_fileData.data()));

    int i;
    if (colornum < 1)
    {
        colornum = 1;
    }
    if (colornum > EMB_BF_SW_ND)
    {
        colornum = EMB_BF_SW_ND;
    }
    for (i = 0; i < colornum; i++)
    {
        if (pDsrHead->switchTable[i] != 0x20)
        {
            break;
        }
    }
    if (i < colornum)  // 不全部是0x20, 可能设置过色序
    {
        for (i = 0; i < colornum; i++)
        {
            if (pDsrHead->switchTable[i] != 0x00)
            {
                break;
            }
        }
    }

    if (i >= colornum && colornum > 1)  // 全部是0x20 或 全部是0, 未设置过色序
    {
        for (i = 0; i < colornum; i++)
        {
            pDsrHead->switchTable[i] = i;     // 默认色序
        }
        saveFile();        // 保存文件
    }

    return 0;
}

QColor DataFileDsr::getBrightAdd(QColor embcolor)
{
    QColor backColor;

    float rgbR = embcolor.red();//R值
    float rgbG = embcolor.green();//G值
    float rgbB = embcolor.blue();//B值

    float Y = 0.257 * rgbR + 0.504 * rgbG + 0.098 * rgbB + 16;
    float U = (-0.148) * rgbR - 0.291 * rgbG + 0.439 * rgbB +128;
    float V = 0.439 * rgbR - 0.368 * rgbG + 0.071 * rgbB + 128;

    Y = Y + 100;

    int R = 1.164*Y + 1.596 * V - 222.9;
    int G = 1.164*Y - 0.392 * U - 0.823 * V+ 135.6;
    int B = 1.164*Y + 2.017 * U- 276.8 ;

    if(R > 255)
    {
        R = 255;
    }
    else if (R < 0)
    {
        R = 0;
    }

    if(G > 255)
    {
        G = 255;
    }
    else if (G < 0)
    {
        G = 0;
    }

    if(B > 255)
    {
        B = 255;
    }
    else if (B < 0)
    {
        B = 0;
    }

    backColor.setRgb(R , G , B);

    return backColor;
}

QColor DataFileDsr::getBrightDec(QColor embcolor)
{
    QColor backColor;

    float rgbR = embcolor.red();//R值
    float rgbG = embcolor.green();//G值
    float rgbB = embcolor.blue();//B值

    float Y = 0.257 * rgbR + 0.504 * rgbG + 0.098 * rgbB + 16;
    float U = (-0.148) * rgbR - 0.291 * rgbG + 0.439 * rgbB +128;
    float V = 0.439 * rgbR - 0.368 * rgbG + 0.071 * rgbB + 128;

    if( Y > 100.0)
    {
        Y = Y - 100.0;
    }
    else
    {
        Y = 16;
    }

    int R = 1.164*Y + 1.596 * V - 222.9;
    int G = 1.164*Y - 0.392 * U - 0.823 * V+ 135.6;
    int B = 1.164*Y + 2.017 * U- 276.8 ;

    if(R > 255)
    {
        R = 255;
    }
    else if (R < 0)
    {
        R = 0;
    }

    if(G > 255)
    {
        G = 255;
    }
    else if (G < 0)
    {
        G = 0;
    }

    if(B > 255)
    {
        B = 255;
    }
    else if (B < 0)
    {
        B = 0;
    }

    backColor.setRgb(R , G , B);

    return backColor;
}
