#include "vst_wait_main.h"
#include "vsm_thread.h"
#include "logic.h"
#include "vst_work_main.h"
#include "msg_def.h"
#include "cmallsystem.h"
#include "cprocess_laserpowercali.h"
VST_Wait_Main::VST_Wait_Main(int iID, const QString &sName,
                             VSM_Thread *pParent)
    :VST_Wait_Base(  iID,  sName, pParent)
{

}

//仅处理切割事件
void VST_Wait_Main::do_Msg(const V_Msg &msg)
{
    switch(msg.m_iID)
    {
	//开始切片,由Trans触发
    case VarMsg_Auto_StartCut:
    {
        if(!m_pNextState)
        {
            CMProduct* pProduct=GET_CHDIRECT(PRODUCT,CMProduct);
            bool bfirstCutB= pProduct->m_Variants.get_VData(Var_MProduct_FirstCutb_ID)->toBool();
            int iFirstSide=bfirstCutB?SIDE_B:SIDE_A;
            int iSecondSide=!bfirstCutB?SIDE_B:SIDE_A;

            m_pNextState= new VST_Work_Main(VarState_Work_Main,
                                            QObject::trUtf8("Auto Cell Cut"),
                                            m_pParent,this,0);

			((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
					pushback_Msg(VarMsg_Resume_Process_Main_ID,
					QObject::trUtf8("Cut_Process"), QVariantList());

			//功率校正
			//定位
			// 每片都进行初始化卡抓操作
            ((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
            pushback_Msg(VarMsg_Driver_ID,
                         QObject::trUtf8("Check lens protect flow volume "), QVariantList() << LASERPATH_DRIVER
                         << CLaserPathDriver::CHECKLESNPROTECT << LASERPATH_D_WIDE);

			//初始化卡抓
			((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
				pushback_Msg(VarMsg_Driver_ID,
					QObject::trUtf8("Move Path init angle"), QVariantList() << LASERPATH_DRIVER 
					<< CLaserPathDriver::CHECKLESNPROTECT << LASERPATH_D_WIDE);

			//功率复检
			if (NeedPowerCheck()) {
				((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
					pushback_Msg(VarMsg_PowerCheck_ALL_ID,
						QObject::trUtf8("Power Check All"), QVariantList() << false << 2 << SIDE_A
						<< SIDE_B);
			}

			//定位
            ((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
                    pushback_Msg(VarMsg_Locate_Process_ID,
                                 QObject::trUtf8("Locate_Process"));

			if(m_gSystem.m_bPausedAfterLocation)
			{
				((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
					pushback_Msg(VarMsg_Locate_Process_PauseAfter_ID,
					QObject::trUtf8("Cut_Process"), QVariantList());

				//恢复工作
				((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
					pushback_Msg(VarMsg_Resume_Process_Main_ID,
					QObject::trUtf8("Cut_Process"), QVariantList());
			}

			//仅定位
			if(!m_gSystem.m_bOnlyLocation){
				if(true == m_gSystem.m_bSimulatorLeveling)
				{
					//模拟时，直接生成切割线
					((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
						pushback_Msg(VarMsg_Debug_Align_Process_ID,
						QObject::trUtf8("Align_Process"),
						QVariantList()<<iFirstSide);
					
					((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
						pushback_Msg(VarMsg_Debug_Align_Process_ID,
						QObject::trUtf8("Align_Process"),
						QVariantList()<<iSecondSide);
				}else{
				//调平第一面
				((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
						pushback_Msg(VarMsg_Align_Process_ID,
									 QObject::trUtf8("Align_Process"),
									 QVariantList()<<iFirstSide);

				//调平第二面
				((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
						pushback_Msg(VarMsg_Align_Process_ID,
									 QObject::trUtf8("Align_Process"),
									 QVariantList()<<iSecondSide);
				}
				//仅调平，不切割
				if(!m_gSystem.m_bOnlyLeveling)
				{
					//切割前暂停
					if(m_gSystem.m_bPausedAfterLeveling)
					{
						((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
							pushback_Msg(VarMsg_Align_Process_PauseAfter_ID,
							QObject::trUtf8("Cut_Process"), QVariantList());

						//恢复工作
						((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
							pushback_Msg(VarMsg_Resume_Process_Main_ID,
							QObject::trUtf8("Cut_Process"), QVariantList());
					}

					((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
						pushback_Msg(VarMsg_Cut_Process_Before_ID, QObject::trUtf8("Before cut record data"), QVariantList()<<iFirstSide);

					((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
						pushback_Msg(VarMsg_Cut_Process_Before_ID, QObject::trUtf8("Before cut record data"), QVariantList()<<iSecondSide);

					CProcess_Level* pLevel=GET_PROCESS(PROCESS_LEVELING, SM_MAIN,CProcess_Level);
					bool bOk;
					//值为0时不生效
					int iStartA = pLevel->m_Variants.get_VData(Var_Process_ProductSide_CutStartA)->toInt(&bOk);
					int iEndA = pLevel->m_Variants.get_VData(Var_Process_ProductSide_CutEndA)->toInt(&bOk);
					int iStartB = pLevel->m_Variants.get_VData(Var_Process_ProductSide_CutStartB)->toInt(&bOk);
					int iEndB = pLevel->m_Variants.get_VData(Var_Process_ProductSide_CutEndB)->toInt(&bOk);

					int iCutFirstStart = iStartA;
					int iCutFirstEnd = iEndA;
					int iCutSecondStart = iStartB;
					int iCutSencondEnd =iEndB;
					if(bfirstCutB){
						iCutFirstStart = iStartB;
						iCutFirstEnd = iEndB;
						iCutSecondStart = iStartA;
						iCutSencondEnd =iEndA;
					}

					//消息处理时，iStart iEnd以id为准
					//切第一面
					((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
							pushback_Msg(VarMsg_Cut_Process_ID,
										 QObject::trUtf8("Cut_Process"),
										 QVariantList()<<iFirstSide<<iCutFirstStart-1<<iCutFirstEnd-1<<true<<0<<0);
					//切第二面
					((VST_Work_Main*)m_pNextState)->m_VarMsgProcess.
							pushback_Msg(VarMsg_Cut_Process_ID,
										 QObject::trUtf8("Cut_Process"),
										 QVariantList()<<iSecondSide<<iCutSecondStart-1<<iCutSencondEnd-1<<true<<0<<0);
				}
			}

            ((VST_Work_Main*)m_pNextState)->LoadMsgProcess();
        }

        m_pParent->SetState(m_pNextState);
        m_gSystem.Reset_All_Side();

		g_SecsManager.SendEvent(EVENT_CutingStarted);

        //pushfront_Msg(VarMsg_AcquireResouce,
        //             QObject::trUtf8("Acquire Sig"));
		//切片结束
        pushback_Msg(VarMsg_Cut_Finish_ID,
                     QObject::trUtf8("Auto Cut Finish Sig"));

       /* pushback_Msg(VarMsg_ReleaseResouce,
                     QObject::trUtf8("Release Acquire Sig"));*/

        /////加工开始计时
		m_gSystem.m_cellTime.ClearTime();
        m_gSystem.m_cellTime.StartTime();
        ///加工开始数据库记录
        CProductSide* pSideA=GET_CHDIRECT(SIDE_A,CProductSide);
        double dStepA=pSideA->m_Variants.get_VData(Var_ProductSide_SideStep)
                ->toDouble();
        CProductSide* pSideB=GET_CHDIRECT(SIDE_B,CProductSide);
        double dStepB=pSideB->m_Variants.get_VData(Var_ProductSide_SideStep)
                ->toDouble();
        int iSlotID=0;
        CProcess_Trans* pTrans=GET_PROCESS(PROCESS_TRANS,
                                           SM_TRANS,
                                           CProcess_Trans);
        CASSSLOT* pSlot= pTrans->m_pSlotWT;
		QString waferId = "NotSet";
        if(pSlot)
        {
            iSlotID=pSlot->index+1;
			waferId=pSlot->WaferID;
        }
        QString str=QObject::trUtf8("WaferID:%5,DID:%2,INDEX1:%3,INDEX2:%4,DNo:%1")
                .arg(m_gSystem.GetCurFile())
                .arg(iSlotID)
                .arg(dStepA*1000)
                .arg(dStepB*1000)
				.arg(waferId);
        m_gSystem.EvtLog(QString::fromUtf8("CUTSTART"),str);
        ///////////////加工开始数据库记录 结束


        break;
    }
    case VarMsg_Cut_Finish_ID:
    {
        /////加工结束计时
        m_gSystem.m_cellTime.StopTime();

		g_SecsManager.SendEvent(EVENT_CutingComplete);
        ///加工结束数据库记录
        int iSlotID=0;
        CProcess_Trans* pTrans=GET_PROCESS(PROCESS_TRANS,
                                           SM_TRANS,
                                           CProcess_Trans);
        CASSSLOT* pSlot= pTrans->m_pSlotWT;
		QString waferId = "NotSet";
        if(pSlot)
        {
            iSlotID=pSlot->index+1;
			waferId = m_gSystem.GetMainWaferId().c_str();
        }
        QString str=QObject::trUtf8("WaferID:%4,DID:%2,TM:%3,DNo:%1")
                .arg(m_gSystem.GetCurFile())
                .arg(iSlotID)
                .arg(m_gSystem.m_cellTime.FormatTime())
				.arg(waferId);
        m_gSystem.EvtLog(QString::fromUtf8("CUTEND"),str);
		//切片完成
        QMutexLocker l(&pTrans->m_slotMutex);
        if(pTrans->m_pSlotWT)
        {
            pTrans->m_pSlotWT->WPstatus=WPCUTFINISH;
            pTrans->m_pSlotWT->bCutFinished = true;
        }
        l.unlock();
        if (m_pParent->IsWaitTask()) {
            MqDebug() << "err-------cut finished but wait";
        }
		m_gSystem.AddProductInfo(PROCESS_CUT, QString("Cut Finish %1 SpendTime:%2S").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss zzz")).arg(m_gSystem.m_cellTime.GetTime()));
		//切割完成后发送VarMsg_Transfer_CheckState消息
        //Lock,保证不能切换状态
        VSM_Thread* pSM=(VSM_Thread*)m_gSystem.FindSM(SM_TRANS);
        pSM->pushBack_Msg_toState(pSM->m_pState_Wait,
                                  V_Msg(VarMsg_Transfer_CheckState,
                                  QObject::trUtf8("Cut Finish")));
        break;
    }
    case VarMsg_AcquireResouce:
        if (false == ResManager().Acquire(m_pParent->m_iID, kResWt)) {
            MQT_THROW_STR("can't acquire resouce");
        }
        break;
    //case VarMsg_ReleaseResouce:
    //    ResManager().Release(m_pParent->m_iID, kResWt);
    //    break;
    }
    VST_Wait::do_Msg(msg);
}

bool VST_Wait_Main::NeedPowerCheck()
{
	CProcess_LaserPowerCali* pLaserPowercali=GET_PROCESS(PROCESS_POWERCALI_D_NARROW,SM_MAIN,CProcess_LaserPowerCali);
	uint iPowerCheckType = pLaserPowercali->m_Variants.get_VData(Var_Process_PowerCheckType)->toUInt();
	bool bNeedCheck=false;

	//功率检测类型 0不使用 1 首片 2每片 3按频率 4按时间间隔
	if(iPowerCheckType == 2){
		bNeedCheck = true;
	}else if(iPowerCheckType == 1){
		//首片
		CProcess_Trans* pTrans=GET_PROCESS(PROCESS_TRANS,
			SM_TRANS,CProcess_Trans);
		CCassette* pCass=GET_CHDIRECT(CASSETTE,CCassette);
		bool bIsFirstSlot=pCass->IsSlotFirstInCass(pTrans->m_pSlotWT);
		if(bIsFirstSlot)
		{
			bNeedCheck = true;
		}
		
	}else if(iPowerCheckType == 3){
		int iFreq = pLaserPowercali->m_Variants.get_VData(Var_Process_PowerCheckTimeInterval)->toInt();
		if(iFreq<=1)
		{
				bNeedCheck = true;
		}

		//计算频率
		if(0 == pLaserPowercali->m_iLastCheckPowerWafer%iFreq)
		{
			bNeedCheck = true;
			pLaserPowercali->m_iLastCheckPowerWafer = 1;
		}else{
			pLaserPowercali->m_iLastCheckPowerWafer++;
		}
		
	}
	else if(iPowerCheckType == 4){
		//按时间间隔
		int iHour = pLaserPowercali->m_Variants.get_VData(Var_Process_PowerCheckTimeInterval)->toInt();
		QDateTime lastDateTime = QDateTime::fromString(pLaserPowercali->m_Variants.get_VData(Var_Process_PowerChekDate)->toString(), "yyyy-MM-dd hh:mm:ss");
		if(lastDateTime.addSecs(iHour*3600)>QDateTime::currentDateTime()){
			bNeedCheck = true;
		}
	}

	return bNeedCheck;
}

