#include "cmwfactoryoffsetadjust.h"
#include "ui_cmwfactoryoffsetadjust.h"
#include "logic.h"
#include "cctrlbuttonid.h"
CMWFactoryOffsetAdjust::CMWFactoryOffsetAdjust(QWidget *parent) :
    CMWidget(parent),
    ui(new Ui::CMWFactoryOffsetAdjust)
{
    ui->setupUi(this);
    m_iCurSideID=-1;
    m_iCurLineCount=-1;

	ui->tableWidget_Offset->setEditTriggers(QAbstractItemView::DoubleClicked);
	ui->tableWidget_Offset_Cur->setEditTriggers(QAbstractItemView::DoubleClicked);
}

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

void CMWFactoryOffsetAdjust::MFresh()
{
    MFresh_Offset_List();
    MFresh_OffsetCur_List();
    MFresh_Button();
    MFresh_Lines();
    MFresh_ComboBox();
}

void CMWFactoryOffsetAdjust::MApply()
{
    MApply_Offset_List();
    MApply_OffsetCur_List();
    MApply_ComboBox();
}

void CMWFactoryOffsetAdjust::MTimeFresh()
{
    if( m_iCurSideID!=m_gSystem.m_iCurSideID)
    {
        m_iCurSideID=m_gSystem.m_iCurSideID;
    }
    MFresh_Lines();
}

void CMWFactoryOffsetAdjust::MFresh_Offset_List()
{

    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    OFFSETLIST &list=pOffset->m_offsetList;
    int iSize=list.size();

    ui->tableWidget_Offset->clearContents();
    ui->tableWidget_Offset->setRowCount(iSize);
    for ( int i=0;i<iSize;i++)
    {
        QTableWidgetItem *pItem=0;
        pItem=new QTableWidgetItem(
                    QString::number(list.at(i).first, 'f',4));
        ui->tableWidget_Offset->setItem(i,0,pItem);

        pItem=new QTableWidgetItem(
                    QString::number(list.at(i).second,
                                    'f',4));
        ui->tableWidget_Offset->setItem(i,1,pItem);

    }
    CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
    ui->tableWidget_Offset_Cur->setCurrentCell(pOffsetDriver->m_iListIndex,0);
}

void CMWFactoryOffsetAdjust::MFresh_OffsetCur_List()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    OFFSETLIST &list=pOffset->m_offsetListCur;
    int iSize=list.size();

    ui->tableWidget_Offset_Cur->clearContents();
    ui->tableWidget_Offset_Cur->setRowCount(iSize);
    for ( int i=0;i<iSize;i++)
    {
        QTableWidgetItem *pItem=0;
        pItem=new QTableWidgetItem(
                    QString::number(list.at(i).first, 'f',4));
        ui->tableWidget_Offset_Cur->setItem(i,0,pItem);

        pItem=new QTableWidgetItem(
                    QString::number(list.at(i).second,
                                    'f',4));
        ui->tableWidget_Offset_Cur->setItem(i,1,pItem);
    }

    CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
    ui->tableWidget_Offset_Cur->setCurrentCell(pOffsetDriver->m_iListCurIndex,0);

}

void CMWFactoryOffsetAdjust::MApply_Offset_List()
{

    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    OFFSETLIST &list=pOffset->m_offsetList;
    list.clear();
    int iSize=ui->tableWidget_Offset->rowCount();
    for(int i=0;i<iSize;i++)
    {
        QPair<double,double> pair;
        QTableWidgetItem *pItem=ui->tableWidget_Offset->item(i,0);Q_ASSERT(pItem);
        pair.first=pItem->text().toDouble();
        pItem=ui->tableWidget_Offset->item(i,1);Q_ASSERT(pItem);
        pair.second=pItem->text().toDouble();
        list.push_back(pair);
    }
}

void CMWFactoryOffsetAdjust::MApply_OffsetCur_List()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    OFFSETLIST &list=pOffset->m_offsetListCur;
    list.clear();
    int iSize=ui->tableWidget_Offset_Cur->rowCount();
    for(int i=0;i<iSize;i++)
    {
        QPair<double,double> pair;
        QTableWidgetItem *pItem=ui->tableWidget_Offset_Cur->item(i,0);Q_ASSERT(pItem);
        pair.first=pItem->text().toDouble();
        pItem=ui->tableWidget_Offset_Cur->item(i,1);Q_ASSERT(pItem);
        pair.second=pItem->text().toDouble();
        list.push_back(pair);
    }
}

void CMWFactoryOffsetAdjust::MFresh_Button()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    int iChecked= pOffset->m_Variants.get_VData(Var_WorkTable_Offset_EnableOffset)
            ->toBool();
    ui->checkBox_EnableOffset->setChecked(iChecked);
    ui->pushButton_POSConfirm->setEnabled(iChecked);
    ui->pushButton_OffsetConfirm->setEnabled(iChecked);
}

void CMWFactoryOffsetAdjust::MFresh_Lines()
{
    if((m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B))return;
    CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
    int isize=pSide->m_CutLineVector.size();
    if(isize!=m_iCurLineCount)
    {
        m_iCurLineCount=isize;
        ui->tableWidget_Line->clearContents();
        ui->tableWidget_Line->setRowCount(isize);
        for(int i=0;i<isize;i++)
        {
            CUTLINE* pLine= pSide->m_CutLineVector.mget(i);
            QString strLineId;
            if(pLine->m_bSUB)
            {
                strLineId=QString::fromUtf8("(%1)").arg(pLine->m_index+1);
            }
            else
            {
                strLineId=QString::fromUtf8("%1").arg(pLine->m_index+1);
            }
            QTableWidgetItem* pItem=new QTableWidgetItem(strLineId);
            pItem->setForeground(Qt::white);
            pItem->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget_Line->setItem(i,0,pItem);
            pItem=new QTableWidgetItem(QString());
            ui->tableWidget_Line->setItem(i,1,pItem);
            pItem=new QTableWidgetItem(QString());
            ui->tableWidget_Line->setItem(i,2,pItem);
            pItem=new QTableWidgetItem(QString());
            ui->tableWidget_Line->setItem(i,3,pItem);
        }

    }
    int iSizeParam= pSide->m_vCutParam.size();
    for(int i=0;i<isize;i++)
    {
        QTableWidgetItem* pItem=ui->tableWidget_Line->item(i,0);
        QColor color=QColor(0,0,255);
        QMutexLocker locker(&pSide->m_CutLineVector.mutex);
        CUTLINE* pLine= pSide->m_CutLineVector.mget(i);
        int iLayer=-1;
        if(pLine)
        {
            iLayer=pLine->m_bHasCut-1;
        }
        locker.unlock();
        if(iLayer>=0&&iSizeParam)
        {
            int iStepColor=255/iSizeParam*(iLayer+1);
            color=QColor(iStepColor,0,255-iStepColor);
        }
        if(m_gSystem.m_iCurLine==i)
        {
            color=QColor(255,255,0);
        }
        pItem->setBackgroundColor(color);
    }

}

void CMWFactoryOffsetAdjust::MFresh_ComboBox()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    double dThres= pOffset->m_Variants.get_VData(Var_WorkTable_Offset_Threshold)
            ->toDouble();
    int iThres=dThres*1000;
    if(iThres==10){ui->comboBox_threshold->setCurrentIndex(0);}
    else if(iThres==100){ui->comboBox_threshold->setCurrentIndex(1);}
    else if(iThres==1000){ui->comboBox_threshold->setCurrentIndex(2);}
}

void CMWFactoryOffsetAdjust::MApply_ComboBox()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    double dthres= ui->comboBox_threshold->currentText().toDouble();
    pOffset->m_Variants.get_VData(Var_WorkTable_Offset_Threshold)->setValue(dthres);
}

void CMWFactoryOffsetAdjust::on_checkBox_EnableOffset_clicked(bool checked)
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    pOffset->m_Variants.get_VData(Var_WorkTable_Offset_EnableOffset)->setValue(checked);
    MFresh_Button();
}

void CMWFactoryOffsetAdjust::on_pushButton_Delete_clicked()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    int icurRow= ui->tableWidget_Offset->currentRow();
    if(!OUTOFRANGE(icurRow,0,pOffset->m_offsetList.size()))
    {
        pOffset->m_offsetList.removeAt(icurRow);
        CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
        pOffsetDriver->m_iListIndex=icurRow;
        MFresh_Offset_List();
    }
}

void CMWFactoryOffsetAdjust::on_pushButton_Clear_clicked()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    pOffset->m_offsetList.clear();
    CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
    pOffsetDriver->m_iListIndex=0;
    MFresh_Offset_List();
}

void CMWFactoryOffsetAdjust::on_pushButton_Delete_Cur_clicked()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    int icurRow= ui->tableWidget_Offset_Cur->currentRow();
    if(!OUTOFRANGE(icurRow,0,pOffset->m_offsetListCur.size()))
    {
        pOffset->m_offsetListCur.removeAt(icurRow);

        CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
        pOffsetDriver->m_iListCurIndex=icurRow;
        MFresh_OffsetCur_List();
    }
}

void CMWFactoryOffsetAdjust::on_pushButton_Clear_Cur_clicked()
{
    CWorktableOffset* pOffset=GET_CHDIRECT(WTOFFSET,CWorktableOffset);
    pOffset->m_offsetListCur.clear();
    CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
    pOffsetDriver->m_iListCurIndex=0;
    MFresh_OffsetCur_List();
}

void CMWFactoryOffsetAdjust::on_pushButton_Merge_clicked()
{
    CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);
    pOffsetDriver->MargeOffset(WTOFFSET);
    MFresh_OffsetCur_List();
    MFresh_Offset_List();

}
//计算左中右基准点
static void CalcuBasePos(int isideID, int iLine,V_MsgQueue& msgqueue)
{
    CProductSide* pSide=GET_CHDIRECT(isideID,CProductSide);
    QMutexLocker locker1(&pSide->m_CutLineVector.mutex);
    const CUTLINE& line= pSide->m_CutLineVector[iLine];
	locker1.unlock();

    if(line.m_bSUB==false)
    {
        msgqueue.pushback_Msg(VarMsg_Process_ID,
                              QObject::trUtf8("Calcu pt by Line Sig"),
                              QVariantList()
                              <<PROCESS_LEVELING
                              <<CProcess_Level::CALCU_PT_BY_LINE
                              <<isideID<<iLine ,0);

    }

}
void CMWFactoryOffsetAdjust::mon_MovePos(int32_t iID)
{
    int iMovePos=iID>>28;
    int iLineID=iID&0x0FFFFFFF;

    Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
    CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);
    Q_ASSERT(pSide);
    QMutexLocker locker(&pSide->m_CutLineVector.mutex);
    CUTLINE* pLine=pSide->m_CutLineVector.mget(iLineID);
    if(pLine)
    {
        CMPointd Wt;
        switch(iMovePos)
        {
        case CENTER_POS:Wt=pLine->m_BasePt;break;
        case START_POS: Wt=pLine->m_WPPair.ptPostive;break;
        case END_POS: Wt=pLine->m_WPPair.ptNegative;break;
        }
        locker.unlock();
        CMPointd Axis;

        CMWorkTableDriver* pWorkTableDriver=GET_CARD(
                    WORKTABLE_DRIVER,CMWorkTableDriver);
        pWorkTableDriver->WtToAxis(m_gSystem.m_iCurChID,Wt,Axis);
        V_MsgQueue msgqueue;
        m_gSystem.absmove_xy_msg(Axis.tX,Axis.tY,msgqueue);

        CalcuBasePos(  m_iCurSideID,   iLineID,msgqueue);
        m_gSystem.start_test(SM_MAIN, msgqueue);
    }
}

void CMWFactoryOffsetAdjust::on_tableWidget_Line_currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous)
{
    if(current)
    {
        if(current->column())
        {

            CCtrlButtonID* pButton=new CCtrlButtonID(this,
                                                     current->row()|current->column()<<28);
            pButton->setText(tr("Move To"));
            ui->tableWidget_Line->
                    setCellWidget(current->row(),
                                  current->column(),
                                  pButton);
            connect(pButton,SIGNAL(MClick_Signal(int32_t)),
                    this,SLOT(mon_MovePos(int32_t)));
            V_MsgQueue msgqueue;
            CalcuBasePos(m_iCurSideID, current->row(),msgqueue);
            m_gSystem.start_test(SM_MAIN, msgqueue,false);
        }
    }
    if(previous)
    {
        if(previous->column())
        {
            ui->tableWidget_Line->
                    removeCellWidget(previous->row(),
                                     previous->column());
        }
    }
}

void CMWFactoryOffsetAdjust::on_comboBox_threshold_currentIndexChanged(int index)
{
    UNUSED(index);
}

void CMWFactoryOffsetAdjust::on_pushButton_POSConfirm_clicked()
{
	//记录当前位置，用作后面计算
    CMWorkTableDriver* pWorkTableDriver=GET_CARD(
                WORKTABLE_DRIVER,CMWorkTableDriver);
    CMPointd Wt;
    pWorkTableDriver->CurAxisToWt(m_gSystem.m_iCurChID,Wt,true);

	
    m_dRefPosWTY=Wt.tY;
}

void CMWFactoryOffsetAdjust::on_pushButton_OffsetConfirm_clicked()
{
    CMWorkTableDriver* pWorkTableDriver=GET_CARD(
                WORKTABLE_DRIVER,CMWorkTableDriver);
    CMPointd Wt;
    pWorkTableDriver->CurAxisToWt(m_gSystem.m_iCurChID,Wt,true);
    double dPosCur=Wt.tY;
    CWorktableOffsetDriver* pOffsetDriver=GET_CARD(WTOFFSET_DRIVER,CWorktableOffsetDriver);

    double dOffset=pOffsetDriver-> CalcuOffsetCur(  dPosCur,  m_dRefPosWTY);

    try
    {
        pOffsetDriver->SetOffsetCur(WTOFFSET,m_dRefPosWTY,dOffset);

        MFresh_OffsetCur_List();
    }
    catch(QString& s)
    {
        m_gSystem.m_SysMsg.SetMsg(s);
    }

}
