#include "cmwmanualkerf.h"
#include "ui_cmwmanualkerf.h"
#include "logic.h"
#include "cmwcamlight.h"
CMWManualKerf::CMWManualKerf(QWidget *parent) :
    CMWidget(parent),
    ui(new Ui::CMWManualKerf)
{
    ui->setupUi(this);
}

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

void CMWManualKerf::MInit()
{
    CMWidget::MInit();
}

void CMWManualKerf::MApply()
{
    Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
    CProductSide* pSide=GET_CHDIRECT(m_iCurSideID,CProductSide);

    QMutexLocker locker(&pSide->m_vCutParam.mutex);
	int iCurLayer = max(0, m_iCurLayer);
    SINGLECUTPARAM* pParam=pSide->m_vCutParam.mget(iCurLayer);
    Q_ASSERT(pParam);
    int iKerfIndex= pParam->iKerfIndex;
    locker.unlock();
    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);

    QMutexLocker locker1(&pKerf->m_vKerfParam.mutex);
    KERFPARAM * pKerfParam=pKerf->m_vKerfParam.mget(iKerfIndex);
    Q_ASSERT(pKerfParam);

    pKerfParam->iLineCount=ui->comboBox_LineCount->currentIndex()+1;
    pKerfParam->dRange=ui->lineEdit_RangeMax->text().toDouble();
    pKerfParam->dRangeMin=ui->lineEdit_RangeMin->text().toDouble();
    pKerfParam->dOffsetMax=ui->lineEdit_OffsetMax->text().toDouble();
    pKerfParam->dOffsetMin=ui->lineEdit_OffsetMin->text().toDouble();
    pKerfParam->dWidthMax=ui->lineEdit_WidthMax->text().toDouble();
    pKerfParam->dWidthMin=ui->lineEdit_WidthMin->text().toDouble();
    pKerfParam->dGAPMax=ui->lineEdit_GapMax->text().toDouble();
    pKerfParam->dGAPMin=ui->lineEdit_GapMin->text().toDouble();
    pKerfParam->ikerfPos=ui->comboBox_KerfPos->currentIndex();

    if(m_gSystem.m_pMWCamLight6X)
    {
        CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight6X;
        pCamLight->GetLightData(pKerfParam->iLight1,pKerfParam->iLight2);
        pCamLight->GetCamInfo(pKerfParam->iExposure, pKerfParam->iGain);
    }
    pKerfParam->iPixelThres=ui->label_Threshold->text().toDouble();
    pKerfParam->iBinaryThres=ui->label_Threshold_binary->text().toDouble();

    pKerf->SetKerfParam(m_iCurSideID,iCurLayer);

    pParam->dKerfOffset=ui->lineEdit_PosOffset->text().toDouble();

    /*pKerfParam->iExposure=ui->label_Exposure->text().toInt();
    pKerfParam->iGain=ui->label_Gain->text().toInt();*/
    pKerf->m_Variants.get_VData(Var_Process_Kerf_EnableAutoThres_ID)->setValue(ui->checkBox_AutoThres->isChecked());
    pKerfParam->dSpecKerfPos=ui->lineEdit_SpecPos->text().toDouble();
}

void CMWManualKerf::MFresh()
{
    if(m_gSystem.m_iCurChID!=CAM6X)
    {
        showShieldWindow(true,
                    QObject::trUtf8("Switch to cam.6X"));
        return;
    }
    if(m_gSystem.m_iCurSideID!=SIDE_A&&
            m_gSystem.m_iCurSideID!=SIDE_B)
    {
        showShieldWindow(true,
                     QObject::trUtf8("Switch to any side."));
        return;
    }
    CProductSide* pSide=GET_CHDIRECT(m_gSystem.m_iCurSideID,
                                     CProductSide);

    QMutexLocker locker(&pSide->m_vCutParam.mutex);
	//TODO:直接只采用第一次的参数即可
#ifdef __SIMULATOR__
	SINGLECUTPARAM* pParam=pSide->m_vCutParam.mget(0);
#else
	SINGLECUTPARAM* pParam=pSide->m_vCutParam.mget(m_gSystem.m_iCurLayer);
#endif // __SIMULATOR__
	if(!pParam)
	{
		showShieldWindow(true,
			QObject::trUtf8("Cut Cell channel before Kerf check."));
		return;
	}
    int iKerfIndex= pParam->iKerfIndex;
    locker.unlock();
    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);

    QMutexLocker locker1(&pKerf->m_vKerfParam.mutex);
    KERFPARAM * pKerfParam=pKerf->m_vKerfParam.mget(iKerfIndex);
    if(!pKerfParam)
    {
        showShieldWindow(true,
                         QObject::trUtf8("Cur channel do not have kerf param."));
        return;
    }
    showShieldWindow(false);
    ui->label_ChID->setNum(m_iCurLayer+1);
    ui->label_KerfID->setNum(iKerfIndex+1);
    ui->comboBox_LineCount->setCurrentIndex(pKerfParam->iLineCount-1);
    ui->lineEdit_RangeMax->
            setText(QString::number(pKerfParam->dRange,'f',3));
    ui->lineEdit_RangeMin->
            setText(QString::number(pKerfParam->dRangeMin,'f',3));

    ui->lineEdit_OffsetMax->
            setText(QString::number(pKerfParam->dOffsetMax,'f',4));
    ui->lineEdit_OffsetMin->
            setText(QString::number(pKerfParam->dOffsetMin,'f',4));

    ui->lineEdit_WidthMax->
            setText(QString::number(pKerfParam->dWidthMax,'f',3));
    ui->lineEdit_WidthMin->
            setText(QString::number(pKerfParam->dWidthMin,'f',3));

    ui->lineEdit_GapMax->
            setText(QString::number(pKerfParam->dGAPMax,'f',3));
    ui->lineEdit_GapMin->
            setText(QString::number(pKerfParam->dGAPMin,'f',3));
    ui->comboBox_KerfPos->setCurrentIndex(pKerfParam->ikerfPos);


    if(m_gSystem.m_pMWCamLight6X)
    {
        CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight6X;
        pCamLight->SetLight(pKerfParam->iLight1,pKerfParam->iLight2);
		pCamLight->SetCamInfo(pKerfParam->iExposure, pKerfParam->iGain);
    }

    ui->label_Threshold->setNum(pKerfParam->iPixelThres);

    ui->lineEdit_PosOffset->
            setText(QString::number(pParam->dKerfOffset,'f',3));

    ui->horizontalSlider_Exposure->setValue(pKerfParam->iExposure);

    ui->horizontalSlider_Gain->setValue(pKerfParam->iGain);

    on_horizontalSlider_Exposure_valueChanged(pKerfParam->iExposure);
    on_horizontalSlider_Gain_valueChanged(pKerfParam->iGain);

    ui->label_Threshold_binary->setNum(pKerfParam->iBinaryThres);
    ui->checkBox_AutoThres->setChecked(pKerf->m_Variants.get_VData(Var_Process_Kerf_EnableAutoThres_ID)
                                       ->toBool());
    ui->lineEdit_SpecPos->setText(QString::number(pKerfParam->dSpecKerfPos,'f',3));

	ui->label_13->setVisible(false);
	ui->lineEdit_GapMin->setVisible(false);
	ui->label_10->setVisible(false);
	ui->lineEdit_GapMax->setVisible(false);
	ui->label_8->setVisible(false);

	ui->label_21->setVisible(false);
	ui->horizontalSlider_Exposure->setVisible(false);
	ui->label_Exposure->setVisible(false);
	ui->label_22->setVisible(false);
	ui->horizontalSlider_Gain->setVisible(false);
	ui->label_Exposure->setVisible(false);
    ui->label_Gain->setVisible(false);
	ui->label_26->setVisible(false);
	//ui->label_6->setVisible(false);
	//ui->lineEdit_RangeMin->setVisible(false);
	//ui->label_5->setVisible(false);
	ui->label_23->setVisible(false);
	ui->comboBox_LineCount->setVisible(false);

	ui->label_25->setVisible(false);
	ui->label_24->setVisible(false);
	ui->lineEdit_SpecPos->setVisible(false);
	ui->pushButton_SetCurSpec->setVisible(false);

	ui->comboBox_KerfPos->setEnabled(false);
	ui->checkBox_AutoThres->setEnabled(false);
	CWorker* pWorker=GET_CHDIRECT(M_WORKER,CWorker);
	if(m_gSystem.IsSMAutoRun(SM_MAIN)
		&& pWorker->m_workLevel<LEVEL_ADMINISTRATOR)
	{
		setEnabled(false);
	}
	else
		setEnabled(true);
}

void CMWManualKerf::MTimeFresh()
{
    if( strCurFile!=m_gSystem.GetCurFile()||
            m_iCurSideID!=m_gSystem.m_iCurSideID||
            m_iCurLayer!=m_gSystem.m_iCurLayer||
            m_iCurCamID!=m_gSystem.m_iCurChID)
    {
        m_iCurCamID=m_gSystem.m_iCurChID;
        strCurFile=m_gSystem.GetCurFile();
        m_iCurSideID=m_gSystem.m_iCurSideID;
        m_iCurLayer=m_gSystem.m_iCurLayer;
        MFresh();
    }
}

/*void CMWManualKerf::FreshBinary()
{
    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);
    Q_ASSERT(pKerf);
    CCam* pCam=GET_CHDIRECT(pKerf->m_iKerfCamID,CCam);
    Q_ASSERT(pCam);
    CAKerfCheck_H* pAKerfCheck =
            (CAKerfCheck_H*)pCam->Find_Algorithm(M_KERFCHECK);
    Q_ASSERT(pAKerfCheck);
    CAMorphology* pMorphology=
            pAKerfCheck->GetMorphology(CAMorphology::IMG_BINARY);
    if(!pMorphology)
    {
        m_gSystem.m_SysMsg.SetMsg(tr("did not find binary Morphology"));
        return;
    }
    int ivalue=pMorphology->mparams[CAMorphology::THRES]->getDataDirect();
    ui->label_Threshold_binary->setNum(ivalue);
}

void CMWManualKerf::ApplyBinary()
{

    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);
    Q_ASSERT(pKerf);
    CCam* pCam=GET_CHDIRECT(pKerf->m_iKerfCamID,CCam);
    Q_ASSERT(pCam);
    CAKerfCheck_H* pAKerfCheck =
            (CAKerfCheck_H*)pCam->Find_Algorithm(M_KERFCHECK);
    Q_ASSERT(pAKerfCheck);
    CAMorphology* pMorphology=
            pAKerfCheck->GetMorphology(CAMorphology::IMG_BINARY);
    if(!pMorphology)
    {
        m_gSystem.m_SysMsg.SetMsg(tr("did not find binary Morphology"));
        return;
    }
    int ivalue=ui->label_Threshold_binary->text().toDouble();
    pMorphology->mparams[CAMorphology::THRES]->setDataDirect(ivalue);
}
*/
void CMWManualKerf::showEvent(QShowEvent *pEvent)
{
    CMWidget::showEvent( pEvent);

}

void CMWManualKerf::hideEvent(QHideEvent *event)
{
    CMWidget::hideEvent( event);
}

void CMWManualKerf::on_pushButton_CheckPos_clicked()
{

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Move Check Pos Sig"),
                          QVariantList()
                          <<PROCESS_KERFCHECK
                          <<CProcess_Kerf::MOVEKERFPOS ,0);
    m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualKerf::on_pushButton_AutoSet_clicked()
{
    Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
    MApply();

	int  iLayer = max(m_iCurLayer, 0);
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Move Check Pos Sig"),
                          QVariantList()
                          <<PROCESS_KERFCHECK
                          <<CProcess_Kerf::MOVEKERFPOS ,0);
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Search Kerf Line Sig"),
                          QVariantList()
                          <<PROCESS_KERFCHECK
                          <<CProcess_Kerf::KERF
                          <<m_iCurSideID<<iLayer<<true,0);

    m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualKerf::on_btnTestCur_clicked()
{
	Q_ASSERT(!(m_iCurSideID!=SIDE_A&&m_iCurSideID!=SIDE_B));
	
	int  iLayer = max(m_iCurLayer, 0);
	V_MsgQueue msgqueue;
	msgqueue.pushback_Msg(VarMsg_Process_ID,
		QObject::trUtf8("Search Kerf Line Sig"),
		QVariantList()
		<<PROCESS_KERFCHECK
		<<CProcess_Kerf::KERF
		<<m_iCurSideID<<iLayer<<true,0);

	m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualKerf::on_pushButton_ManualSet_clicked()
{

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Set Kerf Pos Manual Sig"),
                          QVariantList()
                          <<PROCESS_KERFCHECK
                          <<CProcess_Kerf::SETKERFPOSMANUAL <<m_iCurSideID
                          <<m_iCurLayer,0);

    if(true == m_gSystem.start_manual(SM_MAIN, msgqueue,true)){
		m_gSystem.abort_state(SM_MAIN,
			VarState_Kerf_Process_ID,
			QVariantList()<<m_gSystem.m_iCurSideID, true);
	}

}



void CMWManualKerf::on_pushButton_N5_clicked()
{
    TestKerf(-5);
}

void CMWManualKerf::on_pushButton_N1_clicked()
{
    TestKerf(-1);
}

void CMWManualKerf::on_pushButton_P1_clicked()
{
    TestKerf(1);
}

void CMWManualKerf::on_pushButton_P5_clicked()
{
    TestKerf(5);
}

void CMWManualKerf::on_pushButton_Test_clicked()
{
    TestKerf(0);
}

void CMWManualKerf::TestKerf(int offset)
{
    int ivalue= ui->label_Threshold->text().toInt()+offset;
    ivalue=min(255,ivalue);
    ivalue=max(0,ivalue);
    ui->label_Threshold->setNum(ivalue);
    MApply();

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("test Kerf Sig"),
                          QVariantList()
                          <<PROCESS_KERFCHECK
                          <<CProcess_Kerf::TESTKERF <<m_iCurSideID
                          <<m_iCurLayer,0);

    m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualKerf::TestBinary(int offset)
{
    int ivalue= ui->label_Threshold_binary->text().toInt()+offset;
    ivalue=min(255,ivalue);
    ivalue=max(0,ivalue);

    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);
    Q_ASSERT(pKerf);
    CCam* pCam=GET_CHDIRECT(pKerf->m_iKerfCamID,CCam);
    Q_ASSERT(pCam);
    CAKerfCheck_H* pAKerfCheck =
            (CAKerfCheck_H*)pCam->Find_Algorithm(M_KERFCHECK);
    Q_ASSERT(pAKerfCheck);
    CAMorphology* pMorphology=
            pAKerfCheck->GetMorphology(CAMorphology::IMG_BINARY);
    if(!pMorphology)
    {
        m_gSystem.m_SysMsg.SetMsg(tr("did not find binary Morphology"));
        return;
    }

    pMorphology->m_Variants.get_VData(Var_Morphology_Thres_ID)->setValue((double)ivalue);
    ui->label_Threshold_binary->setNum(ivalue);
    try
    {
        CCamDriver* pCamDriver=GET_CARD(CAM_DRIVER,CCamDriver);
        pCamDriver->image_to_container(pKerf->m_iKerfCamID);
        pAKerfCheck->exe_morphology(&pCam->m_imageContainer.m_Image);
    }
    catch(QString& s)
    {
        m_gSystem.m_SysMsg.SetMsg(s);
    }
}

void CMWManualKerf::on_pushButton_N5_binary_clicked()
{
    TestBinary(-5);
}

void CMWManualKerf::on_pushButton_N1_binary_clicked()
{
    TestBinary(-1);
}

void CMWManualKerf::on_pushButton_Test_binary_clicked()
{
    TestBinary(0);
}

void CMWManualKerf::on_pushButton_P1_binary_clicked()
{
    TestBinary(1);
}

void CMWManualKerf::on_pushButton_P5_binary_clicked()
{
    TestBinary(5);
}

void CMWManualKerf::on_horizontalSlider_Exposure_valueChanged(int value)
{
    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Set Kerf Exposure Sig"),
                          QVariantList()
                          <<CAM_DRIVER<<CCamDriver::SET_CAM_PROPERTY
                          <<pKerf->m_iKerfCamID<<Var_Cam_Exposure_ID
                          <<value<<false,0);
    m_gSystem.start_test(SM_MAIN, msgqueue,false);

}

void CMWManualKerf::on_checkBox_AutoThres_clicked(bool checked)
{
    UNUSED(checked);
}

void CMWManualKerf::on_horizontalSlider_Gain_valueChanged(int value)
{
    CProcess_Kerf* pKerf=GET_PROCESS(PROCESS_KERFCHECK,
                                     SM_MAIN,CProcess_Kerf);

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Set Kerf Gain Sig"),
                          QVariantList()
                          <<CAM_DRIVER<<CCamDriver::SET_CAM_PROPERTY
                          <<pKerf->m_iKerfCamID<<Var_Cam_Gain_ID
                          <<value<<false,0);
    m_gSystem.start_test(SM_MAIN, msgqueue,false);
}

void CMWManualKerf::on_pushButton_SetCurSpec_clicked()
{
    CMPointd wt;
    CMWorkTableDriver* pWorkTableDriver=GET_CARD(
                WORKTABLE_DRIVER,CMWorkTableDriver);
    pWorkTableDriver->CurAxisToWt(m_iCurCamID,wt,true);

    CProductSide* pSide=GET_CHDIRECT(m_gSystem.m_iCurSideID,
                                     CProductSide);

    ui->lineEdit_SpecPos->setText(QString::number(wt.tX-pSide->m_realCenter.tX,'f',3));
}
