#include "cmwmanuallocate.h"
#include "ui_cmwmanuallocate.h"
#include "logic.h"
#include "cmwcamlight.h"
CMWManualLocate::CMWManualLocate(QWidget *parent) :
    CMWidget(parent),
    ui(new Ui::CMWManualLocate)
{
    ui->setupUi(this);
    icon_off.addFile(CMakePath::make_bin_path("../theme/led_off.png"));
    icon_blue.addFile(CMakePath::make_bin_path("../theme/led_blue.png"));
    ui->tableWidget->setRowCount(4);
    ui->widget->m_bContainerInside=true;
    ui->widget->MInit();
}

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

void CMWManualLocate::MFresh()
{
    if(m_gSystem.m_iCurChID!=CAM2X)
    {
        showShieldWindow(true,
                         QObject::trUtf8("Switch to  cam. 2X"));
        return;
    }
    if(!(m_gSystem.m_iCurSideID!=SIDE_A&&m_gSystem.m_iCurSideID!=SIDE_B))
    {
        showShieldWindow(true,
                         QObject::trUtf8("Switch to load side."));
        return;
    }
    showShieldWindow(false);

    CProcess_Locate* pLocate=GET_PROCESS( PROCESS_LOCATE,
                                          SM_MAIN, CProcess_Locate);
    Q_ASSERT(pLocate);


	//TODO:设置定位的Exposure Gain
    if(m_gSystem.m_pMWCamLight2X)
    {
		int ilight1;
		int ilight2;
		ilight1=pLocate->m_Variants.get_VData(Var_Process_Locate_LightDirect)
			->toInt();
		ilight2=pLocate->m_Variants.get_VData(Var_Process_Locate_LightSide)
			->toInt();
		int iExposure = pLocate->m_Variants.get_VData(Var_Location_Exposure)->toInt();
		int iGain = pLocate->m_Variants.get_VData(Var_Location_Gain)->toInt();
        CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight2X;
        pCamLight->SetLight(ilight1,ilight2);
		pCamLight->SetCamInfo(iExposure, iGain);
    }

    MFreshPosVector();
    ui->tableWidget->setCurrentCell(pLocate->m_iCurLocateIndex,0);
    MFreshImage(ui->tableWidget->currentRow());

    CCam* pcam=GET_CHDIRECT(pLocate->m_iLocateCamID,
                            CCam);
    Q_ASSERT(pcam);
    CAFindEage* pAFindEage=(CAFindEage*)pcam->Find_Algorithm(M_FINDEAGE);
    Q_ASSERT(pAFindEage);
    int isizemorphology= pAFindEage->m_lMorphology.size();
    if(isizemorphology)
    {
        CAMorphology* pMorphology=pAFindEage->GetMorphology(CAMorphology::IMG_BINARY);
        if(!pMorphology)
        {
            m_gSystem.m_SysMsg.SetMsg(tr("did not find binary Morphology"));
            return;
        }
        int ithres= pMorphology->m_Variants.get_VData(Var_Morphology_Thres_ID)->toInt();
        ui->label_Threshold->setNum(ithres);
    }

	 CWorker* pWorker=GET_CHDIRECT(M_WORKER,CWorker);

	 if(pWorker->m_workLevel>=LEVEL_FACTORAY){
		 ui->btnMoveACenter->setVisible(true);
		 ui->btnMoveBCenter->setVisible(true);
		 ui->btnMoveCenter->setVisible(true);
	 }else{
		 ui->btnMoveACenter->setVisible(false);
		 ui->btnMoveBCenter->setVisible(false);
		 ui->btnMoveCenter->setVisible(false);
	 }
}

void CMWManualLocate::MApply()
{
    CProcess_Locate* pLocate=GET_PROCESS(
                PROCESS_LOCATE,
                SM_MAIN,
                CProcess_Locate);
    Q_ASSERT(pLocate);


    if(m_gSystem.m_pMWCamLight2X)
    {
        int ilight1;
        int ilight2;
        int exposureUs;
        int iGain;

        CMWCamLight* pCamLight=(CMWCamLight*)m_gSystem.m_pMWCamLight2X;
        pCamLight->GetLightData(ilight1,ilight2);
        pCamLight->GetCamInfo(exposureUs, iGain);

        pLocate->m_Variants.get_VData(Var_Process_Locate_LightDirect)->setValue(ilight1);
        pLocate->m_Variants.get_VData(Var_Process_Locate_LightSide)->setValue(ilight2);
		pLocate->m_Variants.get_VData(Var_Location_Exposure)->setValue(exposureUs);
		pLocate->m_Variants.get_VData(Var_Location_Gain)->setValue(iGain);
		

        //TODO:定位的参数
//        pLocate->m_Variants.set_VData(Var_Process_Locate_LightDirect,
//                                      ilight1);
//        pLocate->m_Variants.set_VData(Var_Process_Locate_LightSide,
//                                      ilight2);
    }

    CCam* pcam=GET_CHDIRECT(pLocate->m_iLocateCamID,
                            CCam);
    Q_ASSERT(pcam);
    CAFindEage* pAFindEage=(CAFindEage*)pcam->Find_Algorithm(M_FINDEAGE);
    Q_ASSERT(pAFindEage);
    int isizemorphology= pAFindEage->m_lMorphology.size();
    if(isizemorphology)
    {
        CAMorphology* pMorphology=pAFindEage->GetMorphology(CAMorphology::IMG_BINARY);
        if(!pMorphology)
        {
            m_gSystem.m_SysMsg.SetMsg(tr("did not find binary Morphology"));
            return;
        }
        int ithres=ui->label_Threshold->text().toInt();
        pMorphology->m_Variants.get_VData(Var_Morphology_Thres_ID)->setValue((double)ithres);
    }
}

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


void CMWManualLocate::MFreshPosVector()
{
    CProcess_Locate* pLocate=GET_PROCESS(
                PROCESS_LOCATE,
                SM_MAIN,
                CProcess_Locate);
    int isize=pLocate->m_LocateVector.size();
    for(int i=0;i<isize;i++)
    {
        LOCATEPOS &pos=pLocate->m_LocateVector[i];
        QIcon& icon=pos.bHasLocated?icon_blue:icon_off;
        QTableWidgetItem* pItem=new QTableWidgetItem(icon,QString(" "));
        ui->tableWidget->setItem(i,0,pItem);
        pItem=new QTableWidgetItem(QString::number(pos.dAngle));
        ui->tableWidget->setItem(i,1,pItem);
        pItem=new QTableWidgetItem(QString::number(pos.WPDP.tX));
        ui->tableWidget->setItem(i,2,pItem);
        pItem=new QTableWidgetItem(QString::number(pos.WPDP.tY));
        ui->tableWidget->setItem(i,3,pItem);
    }
}

void CMWManualLocate::MFreshImage(int iIndex)
{

    int iRowSel=iIndex;

    ui->widget->m_pContainer->m_Image.resetImage();
    CProcess_Locate* pLocate=GET_PROCESS(
                PROCESS_LOCATE,
                SM_MAIN,
                CProcess_Locate);
    if(!OUTOFRANGE(iRowSel,0,pLocate->m_LocateVector.size()))
    {
        LOCATEPOS& pos=pLocate->m_LocateVector[iRowSel];
        ui->widget->m_pContainer->SetImage( pos.img,false);
        ui->widget->m_pContainer->clearShape(-1);
        ui->widget->m_pContainer->clearString(-1);
        ui->widget->m_pContainer->addShape(new CCross(200,200, pos.PixelResultPos),
                             CImageContainer::STATIC_SHAPE);
    }
    ui->widget->ZoomFit();
}

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

void CMWManualLocate::showEvent(QShowEvent *event)
{
    ui->pushButton_Auto->setEnabled(false);
    ui->pushButton_Manual->setEnabled(false);
CMWidget::showEvent( event);
}


void CMWManualLocate::on_pushButton_Initial_clicked()
{
    try
    {
        CProcess_Locate* pLocate=GET_PROCESS(
                    PROCESS_LOCATE, SM_MAIN,
                    CProcess_Locate);
        pLocate->CalcuLocateVector();
        MFreshPosVector();
    }
    catch(QString &s)
    {
        m_gSystem.m_SysMsg.SetMsg(s,NOTIFY_MSG_TYPE);
    }
}

void CMWManualLocate::on_pushButton_MoveTo_clicked()
{

    CProcess_Locate* pLocate=GET_PROCESS( PROCESS_LOCATE,
                                          SM_MAIN, CProcess_Locate);

    CCam* pcam=GET_CHDIRECT(pLocate->m_iLocateCamID,
                            CCam);
    Q_ASSERT(pcam);
    pcam->m_imageContainer.clearShape(-1);

    ui->pushButton_Auto->setEnabled(true);
    ui->pushButton_Manual->setEnabled(true);
    int iRowSel=ui->tableWidget->currentRow();
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Move To Edge Pos Sig"),
                          QVariantList()
                          <<PROCESS_LOCATE<<CProcess_Locate::MOVEPOS
                          <<iRowSel<<0,0);
    m_gSystem.start_manual(SM_MAIN, msgqueue);
}

void CMWManualLocate::on_pushButton_Auto_clicked()
{
    int iRowSel=ui->tableWidget->currentRow();
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Search Edge Pos Sig"),
                          QVariantList()
                          <<PROCESS_LOCATE<<CProcess_Locate::SEARCHPOS
                          <<iRowSel<<true,0);
    m_gSystem.start_manual(SM_MAIN, msgqueue);
}

void CMWManualLocate::on_pushButton_Manual_clicked()
{
    int iRowSel=ui->tableWidget->currentRow();
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Set Edge Pos Sig"),
                          QVariantList()
                          <<PROCESS_LOCATE<<CProcess_Locate::SETPOSMANUAL
                          <<iRowSel<<0,0);
    m_gSystem.start_manual(SM_MAIN, msgqueue);
    m_gSystem.abort_state(SM_MAIN,
                          VarState_Locate_Single_ID,
                          QVariantList()<<iRowSel, true);
}

void CMWManualLocate::on_pushButton_CellSet_clicked()
{
    int iRowSel=ui->tableWidget->currentRow();
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Fit Circle Manual Sig"),
                          QVariantList()
                          <<PROCESS_LOCATE<<CProcess_Locate::FITCELL,0);
    m_gSystem.start_manual(SM_MAIN, msgqueue);
    m_gSystem.abort_state(SM_MAIN,
                          VarState_Locate_Process_ID,
                          QVariantList()<<iRowSel, true);
}

void CMWManualLocate::ThresChange(int iChange)
{
    int iThres=ui->label_Threshold->text().toDouble();
    iThres+=iChange;
    iThres=max(0,iThres);
    iThres=min(255,iThres);
    ui->label_Threshold->setNum(iThres);
    MApply();
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Exe Morphology Sig"),
                          QVariantList()
                          <<CAM_DRIVER<<CCamDriver::EXE_MORPHOLOGY
                          <<CAM2X<<M_FINDEAGE,0);
    m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualLocate::MTimeFresh()
{
	/*if(m_gSystem.IsSMAutoRun(SM_MAIN))
	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 CMWManualLocate::on_pushButton_N5_clicked()
{
    ThresChange(-5);
}

void CMWManualLocate::on_pushButton_N0_clicked()
{
	 ThresChange(0);
}

void CMWManualLocate::on_pushButton_N1_clicked()
{
    ThresChange(-1);
}

void CMWManualLocate::on_pushButton_P1_clicked()
{
    ThresChange(1);
}

void CMWManualLocate::on_pushButton_P5_clicked()
{
    ThresChange(5);
}

void CMWManualLocate::on_tableWidget_clicked(const QModelIndex &index)
{
    UNUSED(index);
    int iCurRow=ui->tableWidget->currentRow();
    if(iCurRow>=0)
    {


        CProcess_Locate* pLocate=GET_PROCESS( PROCESS_LOCATE,
                                              SM_MAIN, CProcess_Locate);

        CCam* pcam=GET_CHDIRECT(pLocate->m_iLocateCamID,
                                CCam);
        Q_ASSERT(pcam);
        pcam->m_imageContainer.clearShape(-1);
        pLocate->m_iCurLocateIndex=iCurRow;
        MFresh();

        ui->pushButton_Auto->setEnabled(false);
        ui->pushButton_Manual->setEnabled(false);
    }
}

void CMWManualLocate::on_btnMoveCenter_clicked()
{
    CMProduct* pProduct=GET_CHDIRECT(PRODUCT,CMProduct);
    Q_ASSERT(pProduct);


    CMPointd Axis;
    CMWorkTableDriver* pWorkTableDriver=GET_CARD(
                WORKTABLE_DRIVER,CMWorkTableDriver);
    pWorkTableDriver->WtToAxis(m_gSystem.m_iCurChID,pProduct->m_RealCenter,Axis);
    V_MsgQueue msgqueue;
    m_gSystem.absmove_xy_msg(Axis.tX,Axis.tY,msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualLocate::on_btnMoveACenter_clicked()
{
    CProductSide* pSideA=GET_CHDIRECT(SIDE_A,CProductSide);
    Q_ASSERT(pSideA);
    CMPointd Axis;
    CMWorkTableDriver* pWorkTableDriver=GET_CARD(
                WORKTABLE_DRIVER,CMWorkTableDriver);
    pWorkTableDriver->WtToAxis(m_gSystem.m_iCurChID,pSideA->m_realCenter,Axis);
    V_MsgQueue msgqueue;
    m_gSystem.absmove_xy_msg(Axis.tX,Axis.tY,msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue,true);
}

void CMWManualLocate::on_btnMoveBCenter_clicked()
{

}
