#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <qscreen.h>
#include <qtooltip.h>

#include "cimagecontainer.h"
#include "cmakepath.h"
#include "cmwcamproperty.h"
#include "cmwcompmotor.h"
#include "cmwidget.h"
#include "cmwmanualmodel.h"
#include "cmwparamproduct.h"
#include "cstatusmotorpos.h"
#include "cstatussensor.h"
#include "logic.h"

#include "cctrllineedit.h"
#include "cmwauto.h"
#include "cmwcalicass.h"
#include "cmwcaliclean.h"
#include "cmwcalicoat.h"
#include "cmwcalihalfcutcheck.h"
#include "cmwcalikerfcheck.h"
#include "cmwcalilaserfoucsall.h"
#include "cmwcalilaserkerf.h"
#include "cmwcalimultilaserkerf.h"
#include "cmwcalilaserpathall.h"
#include "cmwcalilaserpowerall.h"
#include "cmwcalilevel.h"
#include "cmwcalilocate.h"
#include "cmwcalitrans.h"
#include "cmwcaliworktablecoord.h"
#include "cmwcamfindage_h.h"
#include "cmwcamkerf_h.h"
#include "cmwcamkerfhalfcut.h"
#include "cmwcamkerflaser.h"
#include "cmwcammatchncc_h.h"
#include "cmwcompeap.h"
#include "cmwcompioin.h"
#include "cmwcompioout.h"
#include "cmwcompioinout.h"
#include "cmwcomplaser.h"
#include "cmwcomplaser_pi.h"
#include "cmwcomplight.h"
#include "cmwcompother.h"
#include "cmwcomppowermeter.h"

#include "cmwfactorylaseroffsetadjust.h"
#include "cmwfactorymotorconfig.h"
#include "cmwfactoryoffsetadjust.h"
#include "cmwfactorysysconfig.h"
#include "cmwfactoryio.h"
#include "cmwfactoryioanalog.h"

#include "cmwmanualcut.h"
#include "cmwmanualhalfcutkerf.h"
#include "cmwmanualkerf.h"
#include "cmwmanuallaserkerf.h"
#include "cmwmanualload.h"
#include "cmwmanuallocate.h"
#include "cmwmanualmeas.h"
#include "cmwmanualrecover.h"
#include "cmwmanualresettrans.h"
#include "cmwmanualstep.h"
#include "cmwmanualtechnology.h"
#include "cmwmanualtrans.h"

#include "cmwparamalignment.h"
#include "cmwparamcoatclean.h"
#include "cmwparamcut.h"
#include "cmwparamhalfkerf.h"
#include "cmwparamkerf.h"

#include "cmwparamside.h"
#include "cmwsettingbase.h"
#include "cmwsettingkerf.h"
#include "cmwsettinglevel.h"

#include "cmwviewcam.h"
#include "cmwviewtrans.h"
#include "cmwviewworktable.h"

#include "cstatusmodelview.h"
#include "cstatusview.h"
#include "cstatuslog.h"
#include "qmymessagebox.h"

//#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "glog/logging.h"
#include <QFileDialog>
MainWindow* m_gMainWindow = 0;

MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);

    ui->btnAlarmProcess->setVisible(false);

    ui->tableView->horizontalHeader()->setStretchLastSection(true);

    ui->lineEdit_record_eventID->m_bNumOnly = false;
    ui->page_manual->AddPermmision(LEVEL_OPERATOR);
    ui->page_setup->AddPermmision(LEVEL_EQUIPMENT);
    ui->page_comp->AddPermmision(LEVEL_ENGINEER);
    //复位状态
    CMWidget* pWidget = 0;
    pWidget = new CStatusMotorPos(ui->tabWidget_reset, false);
    ui->tabWidget_reset->addTab(pWidget, pWidget->m_sName);
    mMWidgets[MW_reset_StatusMotorPos] = pWidget;
    pWidget = new CStatusMotorPos(ui->tabWidget_reset_Trans, true);
    ui->tabWidget_reset_Trans->addTab(pWidget, pWidget->m_sName);
    mMWidgets[MW_reset_StatusMotorPos_Trans] = pWidget;

    //自动 工作台 2X 6X相机
    pWidget = new CMWViewWorkTable(ui->tabWidget_view);
    ui->tabWidget_view->addTab(pWidget, QObject::trUtf8("WorkStatus"));
    mMWidgets[MW_view_WT] = pWidget;

    pWidget = new CMWViewCam(ui->tabWidget_view, CAM6X);
    ui->tabWidget_view->addTab(pWidget, QObject::trUtf8("6X"));
    mMWidgets[MW_view_Cam6X] = pWidget;

    pWidget = new CMWViewCam(ui->tabWidget_view, CAM2X);
    ui->tabWidget_view->addTab(pWidget, QObject::trUtf8("2X"));
    mMWidgets[MW_view_Cam2X] = pWidget;

    //HACK:4X相机
#ifdef __USE_THIRD_CAMERA__
    pWidget = new CMWViewCam(ui->tabWidget_view, CAMKerf);
    ui->tabWidget_view->addTab(pWidget, QObject::trUtf8("CAM4X"));
    mMWidgets[MW_view_Cam4X] = pWidget;
#else
    //ui->pushButton_box_cam4X->setVisible(false);
#endif

    pWidget = new CMWViewTrans(ui->tabWidget_view);
    ui->tabWidget_view->addTab(pWidget, QObject::trUtf8("Trans"));
    mMWidgets[MW_view_Trans] = pWidget;

    //部件相机2X 和 6X
    pWidget = new CMWCamProperty(ui->tabWidget_cam2X, CAM2X);
    ui->tabWidget_cam2X->addTab(pWidget, tr("Property"));
    mMWidgets[MW_cam_property2X] = pWidget;

    //pWidget=new CMWCamMatchShape_h(  ui->tabWidget_cam2X,CAM2X);
    //ui->tabWidget_cam2X->addTab(pWidget,tr("Match Shape"));
    //mMWidgets[MW_cam_MATCHSHAPE_H2X]=pWidget;

    pWidget = new CMWCamMatchNCC_h(ui->tabWidget_cam2X, CAM2X);
    ui->tabWidget_cam2X->addTab(pWidget, tr("Match NCC"));
    mMWidgets[MW_cam_MATCHNCC_H2X] = pWidget;

    pWidget = new CMWCamFindAge_H(ui->tabWidget_cam2X, CAM2X);
    ui->tabWidget_cam2X->addTab(pWidget, tr("Find Eage"));
    mMWidgets[MW_cam_FINDEAGE_H2X] = pWidget;


    pWidget = new CMWCamProperty(ui->tabWidget_cam6X, CAM6X);
    ui->tabWidget_cam6X->addTab(pWidget, tr("Property"));
    mMWidgets[MW_cam_property6X] = pWidget;

    //pWidget=new CMWCamMatchShape_h(  ui->tabWidget_cam6X,CAM6X);
    //ui->tabWidget_cam6X->addTab(pWidget,tr("Match Shape"));
    //mMWidgets[MW_cam_MATCHSHAPE_H6X]=pWidget;

    pWidget = new CMWCamMatchNCC_h(ui->tabWidget_cam6X, CAM6X);
    ui->tabWidget_cam6X->addTab(pWidget, tr("Match NCC"));
    mMWidgets[MW_cam_MATCHNCC_H6X] = pWidget;

    //相机较正模板定位
    //pWidget=new CMWCamMatch_Calibration(  ui->tabWidget_cam6X,CAM6X);
    //ui->tabWidget_cam6X->addTab(pWidget,tr("Calibration"));
    //mMWidgets[MW_cam_CALINCC_H6X]=pWidget;

#ifdef __USE_HALFCUT_CHECK__
    pWidget = new CMWCamKerfHalfCut(ui->tabWidget_cam6X, CAM6X);
    ui->tabWidget_cam6X->addTab(pWidget, tr("HalfKerf"));
    mMWidgets[MW_cam_HalfcutKerf_H6X] = pWidget;
#endif
    pWidget = new CMWCamKerf_H(ui->tabWidget_cam6X, CAM6X);
    ui->tabWidget_cam6X->addTab(pWidget, tr("Kerf"));
    mMWidgets[MW_cam_AKERF_H6X] = pWidget;

#ifdef __USE_JIG_MODULE__
    pWidget = new CMWCamKerfLaser(ui->tabWidget_cam6X, CAM6X);
    ui->tabWidget_cam6X->addTab(pWidget, tr("LaserCali."));
    mMWidgets[MW_cam_LaserKerf_H6X] = pWidget;
#endif

    //HACK:4X相机
#ifdef __USE_THIRD_CAMERA__
    pWidget = new CMWCamProperty(ui->tabWidget_cam4X, CAMKerf);
    ui->tabWidget_cam4X->addTab(pWidget, tr("Property"));
    mMWidgets[MW_cam_property4X] = pWidget;

    pWidget = new CMWCamMatchNCC_h(ui->tabWidget_cam4X, CAMKerf);
    ui->tabWidget_cam4X->addTab(pWidget, tr("Match NCC"));
    mMWidgets[MW_cam_MATCHNCC_H4X] = pWidget;

    pWidget = new CMWCamKerf_H(ui->tabWidget_cam4X, CAMKerf);
    ui->tabWidget_cam4X->addTab(pWidget, tr("Laser Kerf"));
    mMWidgets[MW_cam_AKERF_H4X] = pWidget;
#endif

    //电机 光源
    pWidget = new CMWCompMotor(ui->tabWidget_comp);
    ui->tabWidget_comp->addTab(pWidget, tr("Motor"));
    mMWidgets[MW_comp_Motor] = pWidget;

    pWidget = new CMWCompLight(ui->tabWidget_comp);
    ui->tabWidget_comp->addTab(pWidget, tr("Light"));
    mMWidgets[MW_comp_Light] = pWidget;


    //功率计，激光器
    pWidget = new CMWCompPowerMeter(ui->tabWidget_comp);
    ui->tabWidget_comp->addTab(pWidget, tr("Powermeter"));
    mMWidgets[MW_comp_PowerMeter] = pWidget;

    pWidget = new CMWCompLaser(ui->tabWidget_comp);
    ui->tabWidget_comp->addTab(pWidget, tr("Laser"));
    mMWidgets[MW_comp_Laser] = pWidget;

    pWidget = new CMWCompEap(ui->tabWidget_comp);
    ui->tabWidget_comp->addTab(pWidget, tr("Eap"));
    mMWidgets[MW_comp_Eap] = pWidget;

    pWidget = new CMWCompOther(ui->tabWidget_comp);
    ui->tabWidget_comp->addTab(pWidget, tr("Other Parts"));
    mMWidgets[MW_comp_Other] = pWidget;

    //部件，输入输出
    pWidget = new CMWCompIOIn(ui->tabWidget_Input, 0, 15);
    ui->tabWidget_Input->addTab(pWidget, tr("IN0"));
    mMWidgets[MW_comp_IO_INPUT_IN0] = pWidget;

    pWidget = new CMWCompIOIn(ui->tabWidget_Input, 16, 31);
    ui->tabWidget_Input->addTab(pWidget, tr("IN1"));
    mMWidgets[MW_comp_IO_INPUT_IN1] = pWidget;

    pWidget = new CMWCompIOIn(ui->tabWidget_Input, 32, 47);
    ui->tabWidget_Input->addTab(pWidget, tr("IN2"));
    mMWidgets[MW_comp_IO_INPUT_IN2] = pWidget;

    pWidget = new CMWCompIOIn(ui->tabWidget_Input, 48, 63);
    ui->tabWidget_Input->addTab(pWidget, tr("IN3"));
    mMWidgets[MW_comp_IO_INPUT_IN3] = pWidget;

    pWidget = new CMWCompIOOut(ui->tabWidget_Output, 0, 15);
    ui->tabWidget_Output->addTab(pWidget, tr("OUT0"));
    mMWidgets[MW_comp_IO_OUTPUT_OUT0] = pWidget;

    pWidget = new CMWCompIOOut(ui->tabWidget_Output, 16, 31);
    ui->tabWidget_Output->addTab(pWidget, tr("OUT1"));
    mMWidgets[MW_comp_IO_OUTPUT_OUT1] = pWidget;

    pWidget = new CMWCompIOOut(ui->tabWidget_Output, 32, 47);
    ui->tabWidget_Output->addTab(pWidget, tr("OUT2"));
    mMWidgets[MW_comp_IO_OUTPUT_OUT2] = pWidget;

    pWidget = new CMWCompIOOut(ui->tabWidget_Output, 48, 63);
    ui->tabWidget_Output->addTab(pWidget, tr("OUT3"));
    mMWidgets[MW_comp_IO_OUTPUT_OUT3] = pWidget;

	QVector<int> io_input, io_output;
    io_input << IN_LASER_Shutter_All_Down << IN_LASER_Shutter_All_Up;
    io_output << OUT_LASERGATE << OUT_Shutter_All_Open << OUT_LENS_Blow_Inner << OUT_LENS_Blow_Outter << OUT_CCD_AIR << OUT_CCD_AIR_6X;
	pWidget = new CMWCompIOInOut(ui->tabWidget, io_input, io_output);
	pWidget->MInit();
	ui->tabWidget->addTab(pWidget, QObject::tr("Laser"));
    io_input.clear();
    io_output.clear();

    io_input << IN_CLEAN_CURTAIN_CLOSED << IN_CLEAN_CURTAIN_OPENED;
    io_output << OUT_CLEAN_CURTAIN_OPENED << OUT_CLEAN_AIR << OUT_CLEAN_TWOFLUID_WATER << OUT_CLEAN_TWOFLUID_AIR << OUT_CLEAN_ELECT_AIR << OUT_CLEAN_CURTAIN_AIR;
	pWidget = new CMWCompIOInOut(ui->tabWidget, io_input, io_output);
	pWidget->MInit();
	ui->tabWidget->addTab(pWidget, QObject::tr("Clean"));
    io_input.clear();
    io_output.clear();

    io_input << IN_COAT_CURTAIN_CLOSED << IN_COAT_CURTAIN_OPENED;
    io_output << OUT_COAT_CURTAIN_OPENED << OUT_COAT_ARM_UP 
        << OUT_COAT_TWOFLUID_WATER << OUT_COAT_TWOFLUID_AIR
        << OUT_COAT_WASHRING_WATER << OUT_COAT_CLEANING_GLUE_WATER 
        << OUT_COAT_CURTAIN_AIR << OUT_COAT_ELECT_AIR;
	pWidget = new CMWCompIOInOut(ui->tabWidget, io_input, io_output);
	pWidget->MInit();
	ui->tabWidget->addTab(pWidget, QObject::tr("Coat"));
    io_input.clear();
    io_output.clear();

    io_input << IN_LOAD_VACUUM << IN_UNLOAD_VACUUM << IN_TRANS_VACUUM;
    io_output << OUT_LOAD_VACUUM << OUT_UNLOAD_VACUUM << OUT_TRANSFER_VACUUM
        << OUT_LOAD_VACUUM_BREAK << OUT_UNLOAD_VACUUM_BREAK
        << OUT_TRANSFER_VACUUM_BREAK << OUT_CLAW_CLOSED << OUT_CLAW_PUSHOUT;
    pWidget = new CMWCompIOInOut(ui->tabWidget, io_input, io_output);
    pWidget->MInit();
    ui->tabWidget->addTab(pWidget, QObject::tr("Trans"));

    io_input.clear();
    io_output.clear();
    io_output << OUT_POWER_ELECT_ENTRY << OUT_ELECT_Entry
        << OUT_POWER_ELECT_WT << OUT_ELECT_Wt
        << OUT_POWER_ELECT_Other
        << OUT_ELECT_Transfer << OUT_ELECT_Load << OUT_ELECT_Unload;
    pWidget = new CMWCompIOInOut(ui->tabWidget, io_input, io_output);
    pWidget->MInit();
    ui->tabWidget->addTab(pWidget, QObject::tr("Elect"));

    //参数模块
    pWidget = new CMWParamProduct(ui->tabWidget_param);
    ui->tabWidget_param->addTab(pWidget, tr("Product"));
    mMWidgets[MW_param_product] = pWidget;

    pWidget = new CMWParamCut(ui->tabWidget_param);
    ui->tabWidget_param->addTab(pWidget, tr("Cut"));
    mMWidgets[MW_param_cut] = pWidget;

    pWidget = new CMWParamSide(ui->tabWidget_param, SIDE_A);
    ui->tabWidget_param->addTab(pWidget, tr("SideA"));
    mMWidgets[MW_param_SideA] = pWidget;

    pWidget = new CMWParamSide(ui->tabWidget_param, SIDE_B);
    ui->tabWidget_param->addTab(pWidget, tr("SideB"));
    mMWidgets[MW_param_SideB] = pWidget;

    pWidget = new CMWParamCoatClean(ui->tabWidget_param,
                                    CMWParamCoatClean::COAT_WIDGET);
    ui->tabWidget_param->addTab(pWidget, tr("Coat"));
    mMWidgets[MW_param_Coat] = pWidget;

    pWidget = new CMWParamCoatClean(ui->tabWidget_param,
                                    CMWParamCoatClean::CLEAN_WIDGET);
    ui->tabWidget_param->addTab(pWidget, tr("Clean"));
    mMWidgets[MW_Param_Clean] = pWidget;

    pWidget = new CMWParamAlignment(ui->tabWidget_param);
    ui->tabWidget_param->addTab(pWidget, tr("Alignment"));
    mMWidgets[MW_Param_Locate] = pWidget;

    pWidget = new CMWParamKerf(ui->tabWidget_param);
    ui->tabWidget_param->addTab(pWidget, tr("LaserKerf"));
    mMWidgets[MW_Param_Kerf] = pWidget;

#ifdef __USE_HALFCUT_CHECK__
    pWidget = new CMWParamHalfKerf(ui->tabWidget_param);
    ui->tabWidget_param->addTab(pWidget, tr("HalfcutKerf"));
    mMWidgets[MW_Param_HalfKerf] = pWidget;
#endif

    pWidget = new CMWAuto(ui->stackedWidget_ctrl);
    ui->stackedWidget_ctrl->addWidget(pWidget);
    mMWidgets[MW_AUTO] = pWidget;

    m_strSystemstate = 0;
    m_pMsgDlg = new CDlgMsg(this);
    m_pMsgDlg->setModal(false);

    m_pDlgPowerMsg = new CDlgPowerMsg(this);
    m_pDlgPowerMsg->setModal(false);

    m_pDlgTerminal = new CDlgTerminal(this);
    m_pDlgTerminal->setModal(false);

    m_pDlgKeyboard = &CDlgKeyboard::GetInstance();
    m_pDlgKeyboard->setModal(false);
    //m_pDlgKeyboard->SetMainWindow(this);
    //m_pDlgKeyboard->setEnabled(true);

    m_pDlgLogin = new CDlgLogin(this);
    m_pDlgLogin->setModal(false);

    m_pDlgLotCode = new CDlgLotCode(this);
    m_pDlgLotCode->setModal(false);

    m_pMWKeyboard = new CMWKeyboard(this);
    m_pMWKeyboard->hide();

    m_pDlgNewFile = new CDlgNewFile(this);
    m_pDlgNewFile->setModal(false);

    m_pDlgCasslotStatuSet = std::make_unique<CDlgCasslotStatuSet>();
    m_pDlgCasslotStatuSet->setModal(true);

    m_bAllHomeState = 0;

    icon_off.addFile(CMakePath::make_bin_path("../theme/led_off.png"));
    icon_blue.addFile(CMakePath::make_bin_path("../theme/led_blue.png"));
    icon_red.addFile(CMakePath::make_bin_path("../theme/led_red.png"));

    connect(ui->page_param, SIGNAL(shown()), ui->treeWidget_file, SLOT(MFresh()));

    //维护
    //坐标
    pWidget = new CMWCaliWorkTableCoord(ui->tabWidget_setup);
    mMWidgets[MW_cali_WT_COORD] = pWidget;
    pWidget->AddPermmision(LEVEL_FACTORAY);
    ui->tabWidget_setup->addTab(pWidget, QObject::trUtf8("Coord"));

    //料盒 
    pWidget = new CMWCaliCass(ui->tabWidget_setup);
    mMWidgets[MW_cali_CASS] = pWidget;
    ui->tabWidget_setup->addTab(pWidget, QObject::trUtf8("Cassette"));

    //维护工作台相关
    pWidget = new CMWCaliHalfcutCheck(ui->tabWidget_Setup_WorkTable);
    mMWidgets[MW_cali_HalfcutKerf] = pWidget;
    ui->tabWidget_Setup_WorkTable->addTab(pWidget, QObject::trUtf8("HalfcutCheck"));

    pWidget = new CMWCaliKerfCheck(ui->tabWidget_Setup_WorkTable);
    mMWidgets[MW_cali_KERF] = pWidget;
    ui->tabWidget_Setup_WorkTable->addTab(pWidget, QObject::trUtf8("KerfCheck"));

#ifdef __USE_JIG_MODULE__
    pWidget = new CMWCaliMultiLaserKerf(ui->tabWidget_Setup_WorkTable);
    mMWidgets[MW_cali_LaserKerf_D_Narrow] = pWidget;
    ui->tabWidget_Setup_WorkTable->addTab(pWidget, QObject::trUtf8("LaserCheck"));
#endif

    pWidget = new CMWCaliLevel(ui->tabWidget_Setup_WorkTable);
    mMWidgets[MW_cali_LEVEL] = pWidget;
    ui->tabWidget_Setup_WorkTable->addTab(pWidget, QObject::trUtf8("Level"));

    pWidget = new CMWCaliLocate(ui->tabWidget_Setup_WorkTable);
    mMWidgets[MW_cali_LOCATE] = pWidget;
    ui->tabWidget_Setup_WorkTable->addTab(pWidget, QObject::trUtf8("Locate"));

    //设置
    pWidget = new CMWSettingBase(ui->tabWidgetSetting);
    mMWidgets[MW_setting_BASE] = pWidget;
    ui->tabWidgetSetting->addTab(pWidget, QObject::trUtf8("Base"));

    pWidget = new CMWCaliCass(ui->tabWidgetSetting, true);
    mMWidgets[MW_setting_CASS] = pWidget;
    ui->tabWidgetSetting->addTab(pWidget, QObject::trUtf8("Cassette"));

    pWidget = new CMWCaliCoat(ui->tabWidgetSetting, true);
    mMWidgets[MW_setting_COAT] = pWidget;
    ui->tabWidgetSetting->addTab(pWidget, QObject::trUtf8("Coat"));

    pWidget = new CMWCaliClean(ui->tabWidgetSetting, true);
    mMWidgets[MW_setting_CLEAN] = pWidget;
    ui->tabWidgetSetting->addTab(pWidget, QObject::trUtf8("Clean"));

    pWidget = new CMWSettingLevel(ui->tabWidgetSetting);
    mMWidgets[MW_setting_Leveling] = pWidget;
    ui->tabWidgetSetting->addTab(pWidget, QObject::trUtf8("Level"));

    pWidget = new CMWSettingKerf(ui->tabWidgetSetting);
    mMWidgets[MW_setting_Kerf] = pWidget;
    ui->tabWidgetSetting->addTab(pWidget, QObject::trUtf8("Kerf"));


    //维护涂敷
    pWidget = new CMWCaliCoat(ui->tabWidget_setup);
    mMWidgets[MW_cali_COAT] = pWidget;
    ui->tabWidget_setup->addTab(pWidget, QObject::trUtf8("Coat"));

    //维护清洗
    pWidget = new CMWCaliClean(ui->tabWidget_setup);
    mMWidgets[MW_cali_CLEAN] = pWidget;
    ui->tabWidget_setup->addTab(pWidget, QObject::trUtf8("Clean"));

    //维护上下料
    pWidget = new CMWCaliTrans(ui->tabWidget_setup);
    mMWidgets[MW_cali_TRANS] = pWidget;
    ui->tabWidget_setup->addTab(pWidget, QObject::trUtf8("Transport"));

    //激光
    //光路
    pWidget = new CMWCaliLaserPathAll(ui->tabWidget_Setup_Laser);
    mMWidgets[MW_cali_LASERPATH] = pWidget;
    ui->tabWidget_Setup_Laser->addTab(pWidget, QObject::trUtf8("Laser Path"));

    //维护激光 焦点
    pWidget = new CMWCaliLaserFoucsAll(ui->tabWidget_Setup_Laser);
    mMWidgets[MW_cali_LASERFOUCS] = pWidget;
    ui->tabWidget_Setup_Laser->addTab(pWidget, QObject::trUtf8("Laser Foucs"));
    //维护激光 功率
    pWidget = new CMWCaliLaserPowerAll(ui->tabWidget_Setup_Laser);
    mMWidgets[MW_cali_LASERPOWER] = pWidget;
    ui->tabWidget_Setup_Laser->addTab(pWidget, QObject::trUtf8("Laser Power"));

    pWidget = new CMWManualTechnology(ui->tabWidget_manual);
    pWidget->AddPermmision(LEVEL_OPERATOR);
    mMWidgets[MW_manual_Technology] = pWidget;
    ui->tabWidget_manual->addTab(pWidget, QObject::trUtf8("Technology"));

    pWidget = new CMWManualResetTrans(ui->tabWidget_manual);
    mMWidgets[MW_manual_Reset] = pWidget;
    ui->tabWidget_manual->addTab(pWidget, QObject::trUtf8("Reset Trans."));

    QTabWidget* tabWidgetManual = new QTabWidget(ui->tabWidget_manual);
    ui->tabWidget_manual->addTab(tabWidgetManual, QObject::trUtf8("Tools"));
    tabWidgetManual->setTabPosition(QTabWidget::South);
    //手动的几个页面，测量，上下料，上下料重置
    

    pWidget = new CMWManualMeas(tabWidgetManual);
    pWidget->AddPermmision(LEVEL_ENGINEER);
    mMWidgets[MW_manual_Meas] = pWidget;
    tabWidgetManual->addTab(pWidget, QObject::trUtf8("Meas."));

    pWidget = new CMWManualRecover(tabWidgetManual);
    mMWidgets[MW_manual_Recover] = pWidget;
    tabWidgetManual->addTab(pWidget, QObject::trUtf8("Recover"));

    //tabWidgetManual = new QTabWidget(ui->tabWidget_manual);
    //ui->tabWidget_manual->addTab(tabWidgetManual, QObject::trUtf8("Maintain"));
    //tabWidgetManual->setTabPosition(QTabWidget::South);

    pWidget = new CMWManualLoad(tabWidgetManual);
    pWidget->AddPermmision(LEVEL_OPERATOR);
    mMWidgets[MW_manual_Load] = pWidget;
    tabWidgetManual->addTab(pWidget, QObject::trUtf8("Load"));

    pWidget = new CMWManualTrans(tabWidgetManual);
    pWidget->AddPermmision(LEVEL_ENGINEER);
    mMWidgets[MW_manual_Trans] = pWidget;
    tabWidgetManual->addTab(pWidget, QObject::trUtf8("Maintain"));

#ifdef __USE_JIG_MODULE__
    CMWManualLaserKerf* pManualLaserKerf = new CMWManualLaserKerf(ui->stackedWidget_ctrl);
    pManualLaserKerf->SetProcess(PROCESS_LASERKERF);
    pWidget = pManualLaserKerf;
    mMWidgets[MW_manual_LaserCalibration_D_Narrow] = pWidget;
    tabWidgetManual->addTab(pWidget, QObject::trUtf8("LaserCali.Narrow"));

    pManualLaserKerf = new CMWManualLaserKerf(ui->stackedWidget_ctrl);
    pManualLaserKerf->SetProcess(PROCESS_LASERKERF_D_WIDE);
    pWidget = pManualLaserKerf;
    mMWidgets[MW_manual_LaserCalibration_D_Wide] = pWidget;
    tabWidgetManual->addTab(pWidget, QObject::trUtf8("LaserCali.Wide"));
#endif

    //工作台的子页面
    pWidget = new CMWManualLocate(ui->tabWidget_manual_WT);
    mMWidgets[MW_manual_Locate] = pWidget;
    ui->tabWidget_manual_WT->addTab(pWidget, QObject::trUtf8("Eage Locate"));


    pWidget = new CMWManualStep(ui->tabWidget_manual_WT);
    mMWidgets[MW_manual_Step_Level] = pWidget;
    ui->tabWidget_manual_WT->addTab(pWidget, QObject::trUtf8("Step&&Level"));


    pWidget = new CMWManualModel(ui->tabWidget_manual_WT);
    mMWidgets[MW_manual_Model] = pWidget;
    pWidget->AddPermmision(LEVEL_ENGINEER);
    ui->tabWidget_manual_WT->addTab(pWidget, QObject::trUtf8("Model"));


    pWidget = new CMWManualCut(ui->tabWidget_manual_WT);
    mMWidgets[MW_manual_Cut] = pWidget;
    ui->tabWidget_manual_WT->addTab(pWidget, QObject::trUtf8("Cut"));

    pWidget = new CMWManualHalfCutKerf(ui->stackedWidget_ctrl);
    mMWidgets[MW_manual_LocateKerf] = pWidget;
    ui->tabWidget_manual_WT->addTab(pWidget, QObject::trUtf8("HalfcutKerf"));

    pWidget = new CMWManualKerf(ui->tabWidget_manual_WT);
    mMWidgets[MW_manual_Kerf] = pWidget;
    ui->tabWidget_manual_WT->addTab(pWidget, QObject::trUtf8("LaserKerf"));

    //自动下面的状态全景、工作台位置 、上下料位置
    pWidget = new CStatusView(ui->tabWidget_status);
    mMWidgets[MW_state_View] = pWidget;
    ui->tabWidget_status->addTab(pWidget, QObject::trUtf8("View"));

    //    pWidget=new CStatusCam(ui->tabWidget_status);
    //    mMWidgets[MW_state_Cam]=pWidget;
    //    ui->tabWidget_status->addTab(pWidget,QObject::trUtf8("cam"));

    pWidget = new CStatusMotorPos(ui->tabWidget_status, false);
    ui->tabWidget_status->addTab(pWidget, pWidget->m_sName);
    mMWidgets[MW_status_StatusMotorPos] = pWidget;

    pWidget = new CStatusMotorPos(ui->tabWidget_status, true);
    ui->tabWidget_status->addTab(pWidget, pWidget->m_sName);
    mMWidgets[MW_status_StatusMotorPos_Trans] = pWidget;


    pWidget = new CStatusSensor(ui->tabWidget_status);
    mMWidgets[MW_state_Sensor] = pWidget;
    ui->tabWidget_status->addTab(pWidget, QObject::trUtf8("Sensor"));

    //A B面模板
    pWidget = new CStatusModelView(ui->tabWidget_status);
    ((CStatusModelView*)pWidget)->m_iSideID = SIDE_A;
    mMWidgets[MW_state_model_SIDE_A] = pWidget;
    ui->tabWidget_status->addTab(pWidget, QObject::trUtf8("Model A"));

    pWidget = new CStatusModelView(ui->tabWidget_status);
    ((CStatusModelView*)pWidget)->m_iSideID = SIDE_B;
    mMWidgets[MW_state_model_SIDE_B] = pWidget;
    ui->tabWidget_status->addTab(pWidget, QObject::trUtf8("Model B"));

    pWidget = new CStatusLog(ui->tabWidget_status);
    mMWidgets[MW_state_Log] = pWidget;
    ui->tabWidget_status->addTab(pWidget, QObject::tr("Log"));

    connect(this, &MainWindow::NotifyLogMesasge, static_cast<CStatusLog*>(pWidget), &CStatusLog::OnNotifyLogMessage, Qt::QueuedConnection);
    connect(this, &MainWindow::NotifyTerminalMessage, this, &MainWindow::OnTerminalMessage, Qt::QueuedConnection);
    connect(this, &MainWindow::NotifyPowerMessage, this, &MainWindow::OnShowPowerMessage, Qt::QueuedConnection);
    //厂商相关的几个页面
    pWidget = new CMWFactoryOffsetAdjust(ui->tabWidget_factory);
    ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("Offset Adjust"));
    mMWidgets[MW_Factory_Offset_Adjust] = pWidget;

    pWidget = new CMWFactoryLaserOffsetAdjust(ui->tabWidget_factory);
    ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("Laser Offset"));
    mMWidgets[MW_Factory_Laser_Offset_Adjust] = pWidget;

    pWidget = new CMWFactoryMotorConfig(ui->tabWidget_factory);
    ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("Motor Config"));
    mMWidgets[MW_Factory_Motor_Config] = pWidget;

    pWidget = new CMWFactorySysConfig(ui->tabWidget_factory);
    ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("System Config"));
    mMWidgets[MW_Factory_System_Config] = pWidget;

    pWidget = new CMWFactoryIO(IO_INPUT, ui->tabWidget_factory);
    ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("Input IO"));
    mMWidgets[MW_Factory_Motor_INPUT_IO] = pWidget;

    pWidget = new CMWFactoryIO(IO_OUTPUT, ui->tabWidget_factory);
    ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("Out IO"));
    mMWidgets[MW_Factory_Motor_OUT_IO] = pWidget;

	pWidget = new CMWFactoryIOAnalog(IO_INPUT_ANALOG, ui->tabWidget_factory);
	ui->tabWidget_factory->addTab(pWidget, QObject::trUtf8("AIN"));
	mMWidgets[MW_Factor_Motor_INPUT_Analog] = pWidget;

    m_iCurSideID = 0;
    m_iCurChID = 0;

    memset(m_iCurStateID, 0, MAXSTATEMACHINE * 4);

    //复位，电机复位
    CMotorDriver* pMotorDriver = GET_CARD(MOTOR_DRIVER, CMotorDriver);
    Q_ASSERT(pMotorDriver);
    CHANNELMAP::iterator ii = pMotorDriver->mchannels.begin();
    int index = 0;
    ui->gridLayout_resetMotor->setSpacing(10);
    for (; ii != pMotorDriver->mchannels.end(); ii++) {
        if ((*ii)->m_itype == CMotorDriver::MODULE_MOTOR) {
            int id = (*ii)->m_iID;
            if (/*id == MOTORG2_POWER || */id == MOTORG3_WIDEINDEX || id == MOTORG4_WIDE5050
                || id == MOTORG7_MASK)
            {
                continue;
            }

#ifndef __USE_G5_G6__
            if (id == MOTORG5_NARROWINDEX || id == MOTORG6_NARROW5050)
            {
                continue;
            }
#endif
            RESETBUTTON resetbutton;
            resetbutton.pButtonMotor = new CCtrlButtonIDIcon(ui->page_reset,
                                                             ii.key());
            resetbutton.pButtonMotor->setMinimumHeight(50);
            resetbutton.pButtonMotor->setMaximumWidth(160);
            resetbutton.pButtonMotor->setMinimumWidth(160);
            resetbutton.pButtonMotor->setText(m_gSystem.m_mapNameList[ii.key()]);
            mresetButtons[ii.key()] = resetbutton;
            connect(resetbutton.pButtonMotor,
                    SIGNAL(MClick_Signal(int32_t)),
                    this,
                    SLOT(mon_resetButton_clicked(int32_t)));
            ui->gridLayout_resetMotor->addWidget(resetbutton.pButtonMotor,
                                                 index / 3, index % 3);
            index++;
        }
    }
    m_iLaserEmitState = -1;

    ui->page_factory->AddPermmision(LEVEL_FACTORAY);
    //隐藏菜单选择栏

    connect(ui->tableView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onLogTips(const QModelIndex&)));
    ui->tableView->setMouseTracking(true);//开启捕获鼠标功能

    m_pEMODlg = new CMWEmo(this);
    m_pEMODlg->hide();
    m_pCoverDlg = new CMWCover(this);
    m_pCoverDlg->hide();

#ifdef __USE_IO_UPLOAD__
    ui->groupBox_10->setVisible(true);
    ui->groupBox_9->setVisible(true);
#else
    ui->groupBox_10->setVisible(false);
    ui->groupBox_9->setVisible(false);
#endif

    //	ui->pushButton_user->setVisible(false);

    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    pWorkDriver->m_ModelWorker->setHeaderData(0, Qt::Horizontal, QObject::trUtf8("UserName"));
    pWorkDriver->m_ModelWorker->setHeaderData(1, Qt::Horizontal, QObject::trUtf8("UserNo."));
    pWorkDriver->m_ModelWorker->setHeaderData(2, Qt::Horizontal, QObject::trUtf8("UserPassword"));
    pWorkDriver->m_ModelWorker->setHeaderData(3, Qt::Horizontal, QObject::trUtf8("UserLevel"));
    pWorkDriver->m_ModelWorker->setHeaderData(4, Qt::Horizontal, QObject::trUtf8("UserGroup"));

    ui->lblEapComm->setText("EAP(C):DISABLED");
    ui->lblEapMode->setText("EAP(M):DISABLED");

    ui->btnVaccUnLoadBreak->setVisible(false);
    ui->btnVaccLoadBreak->setVisible(false);
    ui->btnVaccTransBreak->setVisible(false);

    ui->cbxUserTeam->clear();
    ui->cbxUserTeam->addItem("Operator", LEVEL_OPERATOR);
    ui->cbxUserTeam->addItem("Engineer", LEVEL_ENGINEER);
    ui->cbxUserTeam->addItem("Equipment", LEVEL_EQUIPMENT);
    ui->cbxUserTeam->addItem("Administrator", LEVEL_ADMINISTRATOR);

    ui->btnInitLaser->setIcon(icon_off);
    ui->btnInitLaser->setCheckable(false);
    ui->pushButton_reset_all->setIcon(icon_off);

    ui->btnSetCheck->setVisible(false);
}

MainWindow::~MainWindow()
{
    m_gMainWindow = 0;
    delete m_pDlgTerminal;
    delete m_pDlgLogin;
    delete m_pMWKeyboard;
    delete m_pDlgNewFile;

    m_pDlgTerminal = 0;
    m_pDlgLogin = 0;
    //m_pDlgKeyboard = 0;
    m_pMWKeyboard = 0;
    m_pDlgNewFile = 0;

    delete ui;
    mRESETBUTTONs::iterator ii = mresetButtons.begin();
    for (; ii != mresetButtons.end(); ii++) {
        delete ii->pButtonMotor;
    }
}

void MainWindow::SendNotifyLogMessage(const QString& info, int type)
{
    emit NotifyLogMesasge(info, type);
}

void MainWindow::SendTerminalMessage(const std::string& info)
{
    QString msg = QString(info.c_str());
    emit NotifyTerminalMessage(msg);
}

void MainWindow::SendPowerMessage(bool bVisible)
{
    emit NotifyPowerMessage(bVisible);
}

void MainWindow::OnTerminalMessage(const QString& msg)
{
    QString info = msg;
    m_pDlgTerminal->AddResponse(info);
    m_pDlgTerminal->show();
}

void MainWindow::OnShowPowerMessage(bool bVisible)
{
    if (bVisible) {
        m_pDlgPowerMsg->show();
    }
    else {
        m_pDlgPowerMsg->hide();
    }
}

void MainWindow::mon_resetButton_clicked(int32_t motorID)
{
    if (motorID == MOTORF_CLEAN_SPINDLE
        || motorID == MOTORE_COAT_SPINDLE
        || motorID == MOTORB1_LOCK
        || motorID == MOTORE3_COAT_BUMP) {
        //do nothing
    } else {
        if (false == IsOperatorCanOperate())
            return;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Claw  Close Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::HOME
                          << motorID, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue);
}


void MainWindow::on_pushButton_reset_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_reset);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_reset);

    ui->checkBox_MoveAfterHome->setChecked(m_gSystem.m_bMoveInitPos);
}

void MainWindow::on_pushButton_param_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_param);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_param);
    ui->treeWidget_file->MFresh();
    ui->treeWidget_file->setFocus();
    FreshAuthority();
}

void MainWindow::on_pushButton_auto_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_auto);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
    ui->stackedWidget_ctrl->MsetCurrentWidget(mMWidgets[MW_AUTO]);

    m_gSystem.m_bCamMove = false;
}

void MainWindow::on_pushButton_manual_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_manual);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
    ui->stackedWidget_ctrl->MsetCurrentWidget(ui->page_manual);


}

void MainWindow::on_pushButton_setup_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_manual);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
    ui->stackedWidget_ctrl->MsetCurrentWidget(ui->page_setup);
}

void MainWindow::on_pushButton_comp_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_manual);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
    ui->stackedWidget_ctrl->MsetCurrentWidget(ui->page_comp);
}

void MainWindow::on_pushButton_record_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_log);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_record);
    ui->radioButton_day->setChecked(true);
    FreshLog(QString());
}

void MainWindow::on_pushButton_setting_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_setting);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
    ui->stackedWidget_ctrl->MsetCurrentWidget(ui->page_setting);
}

void MainWindow::on_pushButton_emg_clicked(bool checked)
{
    try {
        if (checked) {
            LOG(ERROR) << "EMG ON";
            m_gSystem.EMO();
        } else {
            LOG(ERROR) << "EMG OFF";
            m_gSystem.LEAVE_EMO();
        }

        m_pEMODlg->ShowDlg(checked);
    } catch (QString& s) {
        MqDebug() << s;
    }
}

void MainWindow::showEvent(QShowEvent* event)
{
    LoginFresh();
    UNUSED(event);
}

void MainWindow::hideEvent(QHideEvent* event)
{
    UNUSED(event);

}

void MainWindow::set_homeState(int32_t motorid, bool_t bhasHomed)
{
    QIcon& icon = bhasHomed ? icon_blue : icon_off;
    if (motorid > 0) {
        mresetButtons[motorid].pButtonMotor->setIcon(icon);
    } else {
        ui->pushButton_reset_all->setIcon(icon);
    }
}


void MainWindow::freshOutputView()
{
    VSM_Thread* pSMMain = GET_STATEMACHINE(SM_MAIN, VSM_Thread);

    QMutexLocker l(&pSMMain->mutex);
    int iStateType = pSMMain->GetMachineCurState();
    l.unlock();
    CMWViewWorkTable* pMWViewWT = (CMWViewWorkTable*)(mMWidgets[MW_view_WT]);

    if (m_iCurSMStateType != iStateType) {
        m_iCurSMStateType = iStateType;
        m_iCurSideID = -1;
        m_iCurChID = -1;
        m_iCurProcessID = -1;
        if (iStateType == VSM_Thread::RUN) {
            if (ui->tabWidget_view->currentWidget() != pMWViewWT) {
                ui->tabWidget_view->setCurrentWidget(pMWViewWT);
            }
        }
    }

    if (iStateType == VSM_Thread::RUN) {
        if (m_iCurProcessID != m_gSystem.m_iCurProcessID ||
            m_gSystem.m_iCurSideID != m_iCurSideID) {
            m_iCurProcessID = m_gSystem.m_iCurProcessID;
            Q_ASSERT(pMWViewWT);
            switch (m_iCurProcessID) {
            case PROCESS_LOCATE:
                pMWViewWT->setCurrentTabIndex(1);
                ui->tabWidget_status->setCurrentIndex(0);
                //pMWViewWT->setResizeTabIndex(1);
                break;
            case PROCESS_LEVELING:
            {
                switch (m_gSystem.m_iCurSideID) {
                case SIDE_A:
                    pMWViewWT->setCurrentTabIndex(2);
                    ui->tabWidget_status->setCurrentIndex(4);
                    pMWViewWT->setKerfStyle(false, m_gSystem.m_iCurSideID);
                    pMWViewWT->setHalfcutKerfStyle(false, m_gSystem.m_iCurSideID);
                    break;
                case SIDE_B:
                    pMWViewWT->setCurrentTabIndex(3);
                    ui->tabWidget_status->setCurrentIndex(5);
                    pMWViewWT->setKerfStyle(false, m_gSystem.m_iCurSideID);
                    pMWViewWT->setHalfcutKerfStyle(false, m_gSystem.m_iCurSideID);
                    break;
                default:
                    break;
                }
            }
            break;
            case PROCESS_KERFCHECK:
            {
                switch (m_gSystem.m_iCurSideID) {
                case SIDE_A:
                    pMWViewWT->setCurrentTabIndex(2);
                    //ui->tabWidget_status->setCurrentIndex(0);
                    pMWViewWT->setKerfStyle(true, m_gSystem.m_iCurSideID);
                    pMWViewWT->setHalfcutKerfStyle(true, m_gSystem.m_iCurSideID);
                    break;
                case SIDE_B:
                    pMWViewWT->setCurrentTabIndex(3);
                    //ui->tabWidget_status->setCurrentIndex(0);
                    pMWViewWT->setKerfStyle(true, m_gSystem.m_iCurSideID);
                    pMWViewWT->setHalfcutKerfStyle(true, m_gSystem.m_iCurSideID);
                    break;
                default:
                    break;
                }
            }
            break;
            case PROCESS_CUT:
            {
                //pMWViewWT->setCurrentTabIndex(0);
                ui->tabWidget_status->setCurrentIndex(0);
                /*switch (m_gSystem.m_iCurSideID)
                {
                case SIDE_A:
                    pMWViewWT->setCurrentTabIndex(2);
                    break;
                case SIDE_B:
                    pMWViewWT->setCurrentTabIndex(3);
                    break;
                default:
                    break;
                }*/
            }
            break;
            }
        }
    } else {
        if (m_iCurChID != m_gSystem.m_iCurChID) {
            switch (m_gSystem.m_iCurChID) {
            case CAM2X:
                ui->tabWidget_view->setCurrentWidget(mMWidgets[MW_view_Cam2X]);
                ui->tabWidget_cam->setCurrentWidget(ui->tab2X);
                break;
            case CAM6X:
                pMWViewWT->setKerfStyle(false, SIDE_A);
                pMWViewWT->setHalfcutKerfStyle(false, SIDE_A);
                pMWViewWT->setKerfStyle(false, SIDE_B);
                pMWViewWT->setHalfcutKerfStyle(false, SIDE_B);

                ui->tabWidget_view->setCurrentWidget(mMWidgets[MW_view_Cam6X]);
                ui->tabWidget_cam->setCurrentWidget(ui->tab6X);
                break;
#ifdef __USE_THIRD_CAMERA__
            case CAMKerf:
                ui->tabWidget_view->setCurrentWidget(mMWidgets[MW_view_Cam4X]);
                ui->tabWidget_cam->setCurrentWidget(ui->tab4X);
                break;
#endif
            case LASERPATH_D_NARROW:
                ui->tabWidget_view->setCurrentWidget(pMWViewWT);
                pMWViewWT->setCurrentTabIndex(0);
                break;
#ifdef __USE_D_WIDE__
            case LASERPATH_D_WIDE:
                ui->tabWidget_view->setCurrentWidget(pMWViewWT);
                pMWViewWT->setCurrentTabIndex(0);
                break;
#endif
            default:
                //  Q_ASSERT(0);
                break;
            }
        }
    }
    if (m_iCurChID != m_gSystem.m_iCurChID) {
        m_iCurChID = m_gSystem.m_iCurChID;
        switch (m_iCurChID) {
        case CAM2X:
            ui->pushButton_box_cam2X->setChecked(true);
            break;
        case CAM6X:
            ui->pushButton_box_cam6X->setChecked(true);
            break;
#ifdef __USE_THIRD_CAMERA__
        case CAMKerf:
            ui->pushButton_box_cam4X->setChecked(true);
            break;
#endif
        case LASERPATH_D_NARROW:
            ui->pushButton_box_D_NORROW->setChecked(true);
            break;
        case LASERPATH_S_NARROW:
            ui->btnSingleNarrow->setChecked(true);
            break;
        case LASERPATH_L_NARROW:
            ui->btnLNarrow->setChecked(true);
            break;
        case DistanceSensor:
            ui->btnDistanceSensor->setChecked(true);
            break;
#ifdef __USE_D_WIDE__
        case LASERPATH_D_WIDE:
            ui->pushButton_box_D_WIDE->setChecked(true);
            break;
#endif
        default:
            //pMWViewWT->setKerfStyle(false, m_gSystem.m_iCurSideID);
            //pMWViewWT->setHalfcutKerfStyle(false, m_gSystem.m_iCurSideID);
            break;
        }
        MWidgetsFresh();
    }
    if (m_iCurSideID != m_gSystem.m_iCurSideID) {
        m_iCurSideID = m_gSystem.m_iCurSideID;
        switch (m_iCurSideID) {
        case SIDE_A:
            ui->pushButton_box_A_SIDE->setChecked(true);
            break;
        case SIDE_B:
            ui->pushButton_box_B_SIDE->setChecked(true);
            break;
        default:
            ui->pushButton_box_LOAD_SIDE->setChecked(true);
            break;
        }
        MWidgetsFresh();
    }
}

void MainWindow::freshMsgDlg()
{
    if (m_gSystem.m_SysMsg.m_bSet) {
        m_gSystem.m_SysMsg.m_bSet = false;
        QString msg = m_gSystem.m_SysMsg.GetMsg();
        int iErrType = m_gSystem.m_SysMsg.m_berrtype;
        m_pMsgDlg->SetMsg(msg, iErrType);
        if (m_pDlgPowerMsg && m_pDlgPowerMsg->isVisible()) {
            m_pDlgPowerMsg->hide();
        }
        if (iErrType == ERR_MSG_TYPE) {
            CWorkerDriver* pWorkerDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriver);
            pWorkerDriver->LogWrite(QString::fromUtf8("ERR"), msg);
        }
    }
}

void MainWindow::freshStateMachine()
{
    //当前状态机使用的当前状态
    //当前消息描述
    QString strState, strComm;
    DWORD dLight = m_gSystem.GetIndicatorLight();
    if (dLight & (1 << 2)) { ui->label_output_status->m_BKColor = Qt::red; } else if (dLight & (1 << 0)) { ui->label_output_status->m_BKColor = Qt::green; } else if (dLight & (1 << 1)) { ui->label_output_status->m_BKColor = Qt::yellow; } else if (dLight & (1 << 3)) { ui->label_output_status->m_BKColor = Qt::blue; } else { ui->label_output_status->m_BKColor = Qt::red; }
    SMMAP::const_iterator iii = m_gSystem.msms.cbegin();
    for (; iii != m_gSystem.msms.cend(); iii++) {

        if (iii.key() == SM_CAMGRAB2X || iii.key() == SM_CAMGRAB4X
            || iii.key() == SM_CAMGRAB6X || iii.key() == SM_IO
            || iii.key() == SM_GEM) {
            continue;
        }

        strState += (*iii)->get_CurStateName().toStdString().c_str();
        QString sMsg;
        int iMsgCnt;
        CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
        QString extInfo = (*iii)->GetCurInfo(iMsgCnt, sMsg, pWorker->m_workLevel > LEVEL_EQUIPMENT);

        strState += QString::number(iMsgCnt) + ";";
        strComm += sMsg;
        strState += extInfo;
        strState += " ";
        int iKey = iii.key();
        if (iKey == SM_CLEAN) {
            strState += "     ";
        }
        //TODO:m_pCurState会析构，也可能会切换State导致没有锁保护这里会异常
        //if(pWorker->m_workLevel >= LEVEL_FACTORAY){
        if (iKey == SM_MAIN || iKey == SM_TRANS || iKey == SM_COAT || iKey == SM_CLEAN) {
            strComm += ";";
        }
        //}

    }
    ui->label_output_status->setText(strState + strComm);
    ui->label_output_action->setText("");
    //更新Recipe只显示ID不显示路径及名称
    //ui->label_output_file->setText(m_gSystem.GetCurFile());
    QFileInfo fileInfo;
    fileInfo.setFile(m_gSystem.GetCurFile());
    ui->label_output_file->setText(fileInfo.baseName());
    ui->label_output_action->setText(fileInfo.path());

    ui->lblLotNo->setText(m_gSystem.GetLotId().c_str());

    //if(m_gSystem.IsAllSMStopped()){
    //	ui->groupBox_6->setEnabled(true);
    //}else{
    //	ui->groupBox_6->setEnabled(false);
    //}
}

void MainWindow::freshResetButton()
{
    CMotorDriver* pMotorDriver = GET_CARD(MOTOR_DRIVER, CMotorDriver);

    CHANNELMAP::iterator ii = pMotorDriver->mchannels.begin();
    int32_t ball = true;
    for (; ii != pMotorDriver->mchannels.end(); ii++) {
        if ((*ii)->m_itype == CMotorDriver::MODULE_MOTOR) {
            CMotor* pMotor = (CMotor*)(*ii);
            int id = pMotor->m_iID;
            if (/*id == MOTORG2_POWER || */id == MOTORG3_WIDEINDEX || id == MOTORG4_WIDE5050
                || id == MOTORG7_MASK)
            {
                continue;
            }

#ifndef __USE_G5_G6__
            if (id == MOTORG5_NARROWINDEX || id == MOTORG6_NARROW5050)
            {
                continue;
            }
#endif
            bool ihomestate = pMotor->m_Variants.get_VData(Var_Motor_Hashome_ID)
                ->toBool();
            //  qDebug()<<iserialID<<ihomestate;
            if (ihomestate != mresetButtons[ii.key()].m_bHomeState) {
                mresetButtons[ii.key()].m_bHomeState = ihomestate;
                set_homeState((*ii)->m_iID, ihomestate);

            }
            ball &= ihomestate;
        }
    }
    if (ball != m_bAllHomeState) {
        m_bAllHomeState = ball;
        set_homeState(-1, m_bAllHomeState);
    }
}

static void hide_layout_child(QLayout* pLayout, bool_t bhide)
{
    if (!pLayout)return;
    int isize = pLayout->count();
    for (int i = 0; i < isize; i++) {
        QLayoutItem* pitem = pLayout->itemAt(i);
        if (pitem->widget()) {
            if (bhide) {
                pitem->widget()->setHidden(true);
            } else {
                pitem->widget()->setHidden(false);
            }
            hide_layout_child(pitem->widget()->layout(), bhide);
        } else if (pitem->layout()) {
            hide_layout_child(pitem->layout(), bhide);
        }
    }

}

void MainWindow::FreshAuthority()
{
    ui->pushButton_setup->setHidden(true);
    ui->pushButton_user->setHidden(true);
    ui->pushButton_comp->setHidden(true);
    ui->pushButton_setup->setHidden(true);
    ui->pushButton_setting->setHidden(true);
    ui->pushButton_factory->setHidden(true);

    ui->btnSubmit->setHidden(true);
    ui->lblState->setHidden(true);
    ui->btnAlarmReset->setHidden(true);

    CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
    if (pWorker->m_workLevel > LEVEL_OPERATOR) {
        ui->pushButton_param_delete->setHidden(false);
        ui->pushButton_param_new->setHidden(false);
        ui->pushButton_param_new_dir->setHidden(false);
        ui->pushButton_param_save->setHidden(false);
        hide_layout_child(ui->page_button_manual->layout(), false);
        ui->pushButton_box_save_2->setVisible(true);
        ui->page_param->SetReadOnly(false);
        if (pWorker->m_workLevel >= LEVEL_ENGINEER) {
            ui->pushButton_setting->setHidden(false);
            ui->pushButton_user->setHidden(false);
            hide_layout_child(ui->page_button_log->layout(), false);
        }
        if (pWorker->m_workLevel >= LEVEL_EQUIPMENT) {
            ui->pushButton_comp->setHidden(false);
            ui->pushButton_setup->setHidden(false);
        }

        //参数设置
        int iCount = ui->tabWidget_param->count();
        for (int i = 0; i < iCount; i++) {
            CMWidget* pWidget = (CMWidget*)ui->tabWidget_param->widget(i);
            pWidget->SetReadOnly(false);
        }

        if (pWorker->m_workLevel >= LEVEL_ADMINISTRATOR) {
            CMWidget* pWidget = mMWidgets[MW_cali_LASERFOUCS];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_LASERPOWER];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_COAT];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_CLEAN];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_TRANS];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_CASS];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_comp_Motor];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_comp_Laser];
            pWidget->SetReadOnly(false);
            ui->pushButton_log_delete->setVisible(true);

        } else {
            CMWidget* pWidget = mMWidgets[MW_cali_LASERFOUCS];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_LASERPOWER];
            pWidget->SetReadOnly(false);
            pWidget = mMWidgets[MW_cali_COAT];
            pWidget->SetReadOnly(true);
            pWidget = mMWidgets[MW_cali_CLEAN];
            pWidget->SetReadOnly(true);
            pWidget = mMWidgets[MW_cali_TRANS];
            pWidget->SetReadOnly(true);
            pWidget = mMWidgets[MW_cali_CASS];
            pWidget->SetReadOnly(true);
            pWidget = mMWidgets[MW_comp_Motor];
            pWidget->SetReadOnly(true);
            pWidget = mMWidgets[MW_comp_Laser];
            pWidget->SetReadOnly(true);
            ui->pushButton_log_delete->setVisible(false);
        }

        if (pWorker->m_workLevel >= LEVEL_FACTORAY) {
            ui->pushButton_factory->setHidden(false);
            ui->btnSubmit->setHidden(false);
        }

        ui->pushButton_Stop->setHidden(false);
        ui->btnSafeDoor->setHidden(false);
    } else {
        ui->pushButton_param_delete->setHidden(true);
        ui->pushButton_param_new->setHidden(true);
        ui->pushButton_param_new_dir->setHidden(true);
        ui->pushButton_param_save->setHidden(true);
        hide_layout_child(ui->page_button_manual->layout(), false);
        ui->pushButton_box_save_2->setVisible(false);
        hide_layout_child(ui->page_button_log->layout(), true);

        int iCount = ui->tabWidget_param->count();
        for (int i = 0; i < iCount; i++) {
            CMWidget* pWidget = (CMWidget*)ui->tabWidget_param->widget(i);
            pWidget->SetReadOnly(true);
        }
        ui->pushButton_Stop->setHidden(true);

        ui->pushButton_setup->setHidden(true);
        ui->pushButton_user->setHidden(true);
        ui->pushButton_comp->setHidden(true);
        ui->pushButton_factory->setHidden(true);
        ui->btnSubmit->setVisible(false);
        ui->btnSafeDoor->setHidden(true);
    }

    //ui->pushButton_auto->click();
    //更新用户管理
    ui->cbxUserTeam->clear();
    ui->cbxUserTeam->addItem("Operator", LEVEL_OPERATOR);
    ui->cbxUserTeam->addItem("Engineer", LEVEL_ENGINEER);
    if (pWorker->m_workLevel >= LEVEL_EQUIPMENT) {
        ui->cbxUserTeam->addItem("Equipment", LEVEL_EQUIPMENT);
    }
    if (pWorker->m_workLevel >= LEVEL_ADMINISTRATOR) {
        ui->cbxUserTeam->addItem("Administrator", LEVEL_ADMINISTRATOR);
    }
    if (pWorker->m_workLevel >= LEVEL_FACTORAY)
    {
        ui->cbxUserTeam->addItem("Factory", 10);
        ui->btnDistanceSensor->setVisible(true);
    }
    else
    {
        ui->btnDistanceSensor->setVisible(false);
    }

    if (pWorker->m_workLevel > LEVEL_OPERATOR) {
        ui->checkBox_MoveAfterHome->setVisible(true);
    } else {
        ui->checkBox_MoveAfterHome->setVisible(false);
    }

    if (pWorker->m_workLevel <= LEVEL_OPERATOR) {
        ui->groupBox_7->setEnabled(false);
        ui->groupBox_4->setEnabled(false);
        ui->pushButton_emg->setVisible(false);
    } else {
        ui->groupBox_7->setEnabled(true);
        ui->groupBox_4->setEnabled(true);
        ui->pushButton_emg->setVisible(true);
    }

    //设置按钮
    //bool bEnable = pWorker->m_workLevel>LEVEL_OPERATOR?true:false;
    //for(auto iter=mresetButtons.cbegin();iter!=mresetButtons.cend();iter++){
    //	(*iter).pButtonMotor->setEnabled(bEnable);
    //}

#ifdef __USE_D_WIDE__
    ui->pushButton_box_D_WIDE->setVisible(true);
#else
    ui->pushButton_box_D_WIDE->setVisible(false);
#endif
#ifdef __USE_S_NARROW__
    ui->btnSingleNarrow->setVisible(true);
#else
    ui->btnSingleNarrow->setVisible(false);
#endif

#ifdef __USE_D_NARROW__
    ui->pushButton_box_D_NORROW->setVisible(true);
#else
    ui->pushButton_box_D_NORROW->setVisible(false);
#endif

#ifdef __USE_L_NARROW__
    ui->btnLNarrow->setVisible(true);
#else
    ui->btnLNarrow->setVisible(false);
#endif
}

bool MainWindow::IsOperatorCanOperate()
{
    CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
    if (pWorker->m_workLevel <= LEVEL_OPERATOR) {
        m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("Operator does not have permission"));
        return false;
    }
    return true;
}

void MainWindow::LoginFresh()
{
    ui->page_manual->MFresh();
    ui->page_setup->MFresh();
    ui->page_comp->MFresh();
    ui->page_factory->MFresh();
    //    ui->groupBox_Light->setEnabled(pWorker->m_workLevel>10);
    FreshAuthority();

    //如果不是厂商，则需要刷新界面
    CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
    if (pWorker->m_workLevel < LEVEL_FACTORAY)
        m_gSystem.m_bNeedFreshUI = true;

    FileTreeFresh();
}

void MainWindow::FileTreeFresh()
{
    //ui->label_output_file->setText(m_gSystem.GetCurFile());
    ui->treeWidget_file->reBuildCtrl();
}

void MainWindow::GetLightData(int& iLight1, int& iLight2, int iCamIndex)
{
	CMWCamLight* pCamLight = static_cast<CMWCamLight*>(GetCamLightCtrol(iCamIndex));
	if (pCamLight == nullptr) {
		return;
	}
	pCamLight->GetLightData(iLight1, iLight2);
}

void MainWindow::GetCamInfo(int& iExposure1, int& iExposure2, int iCamIndex)
{
    CMWCamLight* pCamLight = static_cast<CMWCamLight*>(GetCamLightCtrol(iCamIndex));
    if (pCamLight == nullptr) {
        return;
    }

	pCamLight->GetCamInfo(iExposure1, iExposure2);
}

void MainWindow::SetLightData(int iLight1, int iLight2, int iCamIndex)
{
	CMWCamLight* pCamLight = static_cast<CMWCamLight*>(GetCamLightCtrol(iCamIndex));
	if (pCamLight == nullptr) {
		return;
	}

	pCamLight->SetLightData(iLight1, iLight2);
}

void MainWindow::SetCamInfo(int iExposure1, int iExposure2, int iCamIndex)
{
	CMWCamLight* pCamLight = static_cast<CMWCamLight*>(GetCamLightCtrol(iCamIndex));
	if (pCamLight == nullptr) {
		return;
	}

	pCamLight->SetCamData(iExposure1, iExposure2);
}

void* MainWindow::GetCamLightCtrol(int iCamIndex)
{
	CMWCamLight* pCamLight = NULL;
	if (iCamIndex == CAM6X) {
		pCamLight = (CMWCamLight*)m_gSystem.m_pMWCamLight6X;
	}
	else if (iCamIndex == CAM2X) {
		pCamLight = (CMWCamLight*)m_gSystem.m_pMWCamLight2X;
    }
    else {
        return nullptr;
    }
}

static void continueState(QSqlQuery& query, QDateTime& dateTime,
                          PI_Graph_Data* pCurState)
{
    QDateTime dateTimeCur = query.value(0).toDateTime();
    qint64 secs = dateTime.secsTo(dateTimeCur);
    pCurState->dData += secs / 3600.0;
    dateTime = dateTimeCur;
}
static void changeState(QSqlQuery& query, PI_Graph_Data* pCurState,
                        QDateTime& dateTime, PI_Graph_Data* pState)
{
    continueState(query, dateTime, pCurState);
    pCurState = pState;
}
void MainWindow::LogStateAnalyse(const QDateTime& startDate,
                                 LPI_Graph_Data& data, QStringList& list)
{
    PI_Graph_Data dataIdle = PI_Graph_Data(QObject::trUtf8("Idle"),
                                           0, Qt::yellow, QObject::trUtf8("Hour"));
    PI_Graph_Data dataPause = PI_Graph_Data(QObject::trUtf8("Pause"),
                                            0, Qt::darkRed, QObject::trUtf8("Hour"));
    PI_Graph_Data dataError = PI_Graph_Data(QObject::trUtf8("Error"),
                                            0, Qt::red, QObject::trUtf8("Hour"));
    PI_Graph_Data dataWork = PI_Graph_Data(QObject::trUtf8("Work"),
                                           0, Qt::green, QObject::trUtf8("Hour"));

    PI_Graph_Data* pCurState = &dataIdle;
    QDateTime dateTime = startDate;
    CWorkerDriver* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriver);
    QSqlQuery query(pWorkDriver->GetDatabase());
    Q_ASSERT(pWorkDriver);
    query.prepare("select * from Log where time>:querydate and (evtID='FAS' or evtID='PAUSE' or evtID='ERR' or evtID='STP' or evtID='DML' or evtID='START');");
    query.bindValue(":querydate", startDate.toString("yyyy-MM-dd hh:mm:ss"));
    pWorkDriver->LogRead(startDate, query);
    MqDebug() << "Exec LogStateAnalyse" << QDateTime::currentDateTime();
    while (query.next()) {
        QString strEvt = query.value(1).toString();


        if (pCurState == &dataIdle) {
            if (strEvt == "FAS") {
                changeState(query, pCurState, dateTime, &dataWork);
            } else {
                continueState(query, dateTime, &dataIdle);
            }
        }
        if (pCurState == &dataWork) {
            if (strEvt == "PAUSE") {
                changeState(query, pCurState, dateTime, &dataPause);
            } else if (strEvt == "ERR") {
                changeState(query, pCurState, dateTime, &dataError);
            } else if (strEvt == "STP" || strEvt == "DML") {
                changeState(query, pCurState, dateTime, &dataIdle);
            } else {
                continueState(query, dateTime, &dataWork);
            }
        }
        if (pCurState == &dataError) {
            if (strEvt == "START") {
                changeState(query, pCurState, dateTime, &dataWork);
            } else if (strEvt == "STP" || strEvt == "DML") {
                changeState(query, pCurState, dateTime, &dataIdle);
            } else {
                continueState(query, dateTime, &dataError);
            }
        }
        if (pCurState == &dataPause) {
            if (strEvt == "START") {
                changeState(query, pCurState, dateTime, &dataWork);
            } else if (strEvt == "STP" || strEvt == "DML") {
                changeState(query, pCurState, dateTime, &dataIdle);
            } else {
                continueState(query, dateTime, &dataPause);
            }
        }
    }
    data << dataError << dataPause << dataIdle << dataWork;
    double dTotal = dataError.dData + dataPause.dData +
        dataIdle.dData + dataWork.dData;
    double dratio = 0;
    if (!DEQUAL0(dTotal)) {
        dratio = dataWork.dData / dTotal * 100;
    }
    MqDebug() << "End LogStateAnalyse" << QDateTime::currentDateTime();
    QString str = QObject::trUtf8("Activation ratio :%1%")
        .arg(dataWork.dData / dTotal * 100, 0, 'f', 1);
    list << str;
}

void MainWindow::LogProductionAnalyse(const QDateTime& startDate,
                                      Chart_Data_Vector& vdataUPH,
                                      Chart_Data_Vector& vdataPCS)
{
    
    CWorkerDriver* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriver);
    Q_ASSERT(pWorkDriver);
    QSqlQuery query(pWorkDriver->GetDatabase());
    pWorkDriver->LogSel("JOB", startDate, query);
    
    QRegExp reg("(\\d{1,2}):(\\d{1,2}):(\\d{1,2})");
    QDate dateStart = startDate.date();

    QString dateStartStr = startDate.toString("yyyy-MM-dd hh:mm:ss");

    Chart_Data dataUPH;
    Chart_Data dataPCS;
    int iPos = 0;//startDate.daysTo(QDateTime::currentDateTime());
    vdataUPH.push_back(dataUPH);
    vdataPCS.push_back(dataPCS);
    vdataUPH.last().pt.setX(iPos);
    vdataPCS.last().pt.setX(iPos);
    double dHourTotal = 0;
    int count = query.record().count();
    while (query.next()) {
        QString strData = query.value(2).toString();
        if (reg.indexIn(strData) >= 0) {
            int iHour = reg.cap(1).toInt();
            int iMin = reg.cap(2).toInt();
            int iSecs = reg.cap(3).toInt();
            dHourTotal += iHour + iMin / 60.0 + iSecs / 3600.0;

            QDate date = query.value(0).toDate();
            QString dateStr = date.toString();
            QString dateStartStr = dateStart.toString();
            int iPosCur = dateStart.daysTo(date);
            if (iPos != iPosCur) {
                vdataUPH.last().pt.setX(iPos);
                vdataPCS.last().pt.setX(iPos);
                vdataUPH.push_back(dataUPH);
                vdataPCS.push_back(dataPCS);
                dataPCS = dataUPH = Chart_Data();
                dHourTotal = 0;
                iPos = iPosCur;
                vdataUPH.last().pt.setX(iPosCur);
                vdataPCS.last().pt.setX(iPosCur);
            }
            vdataPCS.last().pt.ry()++;
            if (!DEQUAL0(dHourTotal)) {
                vdataUPH.last().pt.ry()
                    = vdataPCS.last().pt.y() / dHourTotal;
            }
        }
    }

    Chart_Data_Vector::iterator ii = vdataPCS.begin();

    for (; ii != vdataPCS.end(); ii++) {
        QPointF data = (*ii).pt;
    }
}



void MainWindow::timerEvent(QTimerEvent* event)
{
    if (isHidden())return;
    m_bEnableSendFreshMsg = true;
    if (m_iTimerShowMax == event->timerId()) {
        showMaximized();
        killTimer(m_iTimerShowMax);
        return;
    }
    //HACK:
    if (event->timerId() == timer_time_fast) {
        //freshStateMachine();
    }

    if (event->timerId() == timer_time_id) {
        QDateTime time = QDateTime::currentDateTime();
        ui->label_output_time->setText(time.toString(Qt::ISODate));
        //const char* ch=m_gSystem.m_Variants.get_VData(Var_ALLSystem_State_ID)->toUInt();
//        if(ch&&ch!=m_strSystemstate)
//        {
            //m_strSystemstate=ch;

        CGEMDriver* pDriverGEM = GET_CARD(GEM_DRIVER_JNG, CGEMDriver);
        m_gSystem.m_strserialID = pDriverGEM->m_Variants.get_VData(Var_MES_MDLN)->toString();
        QString strVer = pDriverGEM->m_Variants.get_VData(Var_MES_SoftVersion)->toString();
        QString str = tr("%1 (v%2)").arg(m_gSystem.m_strserialID).arg(strVer);
        ui->label_output_machine_ID->setText(str);
        //        }


        freshMsgDlg();
        freshResetButton();
        freshOutputView();
        if (m_gSystem.m_bNeedFreshUI) {
            m_gSystem.m_bNeedFreshUI = false;
            MWidgetsFresh();
        }
        freshStateMachine();
        //freshButtonStatus();
        CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
        if (m_sCurWorkName != pWorker->m_workName) {
            m_sCurWorkName = pWorker->m_workName;
            ui->label_output_level->setText(m_sCurWorkName +
                                            "(" +
                                            QString::number(pWorker->m_workLevel) +
                                            ")");
            FreshAuthority();

        }
        CMProduct* pProduct = GET_CHDIRECT(PRODUCT, CMProduct);
        int iWaferSize = pProduct->m_Variants.get_VData(Var_MProduct_SizeType_ID)
            ->toUInt();
        if (m_iCurWaferSize != iWaferSize) {
            m_iCurWaferSize = iWaferSize;
            if (m_iCurWaferSize == 0) {
                ui->label_output_WP_ID->setText(tr("(6Inch)"));
            }
            if (m_iCurWaferSize == 1) {
                ui->label_output_WP_ID->setText(tr("(8Inch)"));
            }
            if (m_iCurWaferSize == 2) {
                ui->label_output_WP_ID->setText(tr("(12Inch)"));
            }
        }
        freshDirectIO();

        //TODO:激光器状态监视
        CLaserDriver_SP* pLaser = GET_CARD(LASER_DRIVER, CLaserDriver_SP);
        if (nullptr != pLaser) {
            if (false == pLaser->m_bInited) {
                ui->widget_laserState->setStyleSheet("background-color:gray");
            } else if (pLaser->m_bError) {
                ui->widget_laserState->setStyleSheet("background-color:red");
            } else if (pLaser->m_bPreheat) {
                ui->widget_laserState->setStyleSheet("background-color:yellow");
            } else if (!pLaser->m_bInternalGate) {
                ui->widget_laserState->setStyleSheet("background-color:#999221");
            } else if (!pLaser->m_bEmissionOn) {
                ui->widget_laserState->setStyleSheet("background-color:#999221");
            } else {
                //如果激光出光则显示蓝色
                CMotorDriver* pDriver = GET_CARD(MOTOR_DRIVER, CMotorDriver);
                int iSet = pDriver->get_iodata(IO_OUTPUT, OUT_LASERGATE, true);
                if (iSet == IO_TRIGGER_ON) {
                    ui->widget_laserState->setStyleSheet("background-color:blue");
                } else {
                    ui->widget_laserState->setStyleSheet("background-color:green");
                }

            }
        }
        else
        {
            ui->widget_laserState->setStyleSheet("background-color:gray");
        }

        //		if(iLaserState!=m_iLaserEmitState)
        //		{
        //		m_iLaserEmitState=iLaserState;
        //		if(m_iLaserEmitState)
        //		{
        //            //连接成功
        //		ui->widget_laserState->setStyleSheet("background-color:green");
        //		}
        //		else
        //		{
        //            //未连接
        //		ui->widget_laserState->setStyleSheet("background-color:gray");

        //        //异常
        //        ui->widget_laserState->setStyleSheet("background-color:yellow");
        //		}
        //        }
        if (ui->widget_State_PI->isVisible()) {
            ui->widget_State_PI->MTimeFresh();
        }
        if (ui->widget_UPH_Bar->isVisible()) {
            ui->widget_UPH_Bar->MTimeFresh();
        }
        if (ui->widget_PCS_Bar->isVisible()) {
            ui->widget_PCS_Bar->MTimeFresh();
        }
    }
    //    else if(timer_widget_id==event->timerId())
    //    {
    //        MWidgetsTimerFresh();
    //    }
    else  if (m_iJogTimerID == event->timerId()) {
        CMotorDriver* pMotorDriver = GET_CARD(MOTOR_DRIVER, CMotorDriver);
        double dSpd = pMotorDriver->get_highSpd(m_iJogMotorID) * (-m_iDirect);

        V_MsgQueue msgqueue;
        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("Claw  Close Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETSPEED
                              << m_iJogMotorID << dSpd
                              << 0 << 0, 0);
        m_gSystem.start_test(SM_MAIN, msgqueue);

        killTimer(m_iJogTimerID);
    } else if (timer_time_slow == event->timerId()) {
        freshButtonStatus();

        int iSMID = SM_IO;
        VS_Thread* m_pState = (VS_Thread*)m_gSystem.FindSM(iSMID)->GetIdleState();
        if (m_pState->QueueSize() < 100) {
            //激光器状态刷新,如果激光器未打开，这里会一直刷新不了
            if (m_pState->QueueSize() < 5) {
                if ((VS_Thread*)m_gSystem.FindSM(SM_MAIN)->IsIdle()) {
                    m_pState->pushback_Msg(VarMsg_Driver_ID,
                                           QObject::trUtf8("Laser Get Current Sig"),
                                           QVariantList()
                                           << LASER_DRIVER << CLaserDriver_PI::GETSTATE
                                           << LASER, 0);
                }
            }

            //刷新漏液报警
            //涂敷区漏液
            m_pState->pushback_Msg(VarMsg_Driver_ID, QObject::tr("Fresh Input IO Sig"),
                                   QVariantList() << MOTOR_DRIVER << CMotorDriver::FRESHIO
                                   << IO_INPUT << IN_LIQUID_ALM_CLEAN);
            //清洗区漏液
            m_pState->pushback_Msg(VarMsg_Driver_ID, QObject::tr("Fresh Input IO Sig"),
                                   QVariantList() << MOTOR_DRIVER << CMotorDriver::FRESHIO
                                   << IO_INPUT << IN_LIQUID_ALM_COOLING);
            //激光漏液检测
            m_pState->pushback_Msg(VarMsg_Driver_ID, QObject::tr("Fresh Input IO Sig"),
                                   QVariantList() << MOTOR_DRIVER << CMotorDriver::FRESHIO
                                   << IO_INPUT << IN_LIQUID_ALARM_LASER);

            m_pState->pushback_Msg(VarMsg_Driver_ID,
                                   QObject::trUtf8("Measure volume"),
                                   QVariantList()
                                   << COATVOLUME_SENSOR << CCoatVolumeSensor::MeasureVolume
                                   << 0, 0);
        }

        freshEAPStatus();
    }
}

void MainWindow::closeEvent(QCloseEvent* e)
{
    CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
    if (pWorker->m_workLevel <= LEVEL_OPERATOR) {

        QMessageBox msgBox(QMessageBox::Information, tr("Notice"), tr("Operator can't exit application"));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);
        msgBox.setButtonText(QMessageBox::Ok, tr("Ok"));
        msgBox.exec();
        e->ignore();
        return;
    }

    QMessageBox msgBoxAsk(QMessageBox::Question, tr("Confirm information"), tr("Are you sure exit application immediately?"));
    msgBoxAsk.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBoxAsk.setDefaultButton(QMessageBox::No);
    msgBoxAsk.setButtonText(QMessageBox::Yes, tr("Yes"));
    msgBoxAsk.setButtonText(QMessageBox::No, tr("No"));
    int ret = msgBoxAsk.exec();
    if (ret == QMessageBox::Yes) {
        e->accept();
    } else {
        e->ignore();
    }
}

void MainWindow::resizeEvent(QResizeEvent* event)
{
    UNUSED(event);
    ResizeCtrlSize(Ctrl_Normal);
    if (m_pEMODlg->isVisible()) {
        m_pEMODlg->ShowDlg(true);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
    QMainWindow::mouseReleaseEvent(event);
    //   QWidget *pWidget=QApplication::widgetAt(event->globalPos());
    //   CCtrlLineEdit* pLineEdit=qobject_cast<CCtrlLineEdit*>(pWidget);
    //   if(pLineEdit)
    //   {
    //       m_pDlgKeyboard->show();
    //       m_pDlgKeyboard->MoveToPos(pLineEdit);
    //   }
    //   else
    //   {
    //       m_pDlgKeyboard->hide();
    //   }
}

void MainWindow::keyPressEvent(QKeyEvent* event)
{
    if (event->key() == Qt::Key_I &&
        event->modifiers() ==
        (Qt::AltModifier | Qt::ControlModifier)) {
        if (m_pCoverDlg->isVisible()) {
            m_pCoverDlg->hide();
        } else {
            m_pCoverDlg->ShowDlg(true);
        }
    }
    if (m_pCoverDlg->isVisible()) {
        return;
    }
}


void MainWindow::MWidgetsFresh()
{

    for (QMap<int32_t, CMWidget*>::iterator ii = mMWidgets.begin();
         ii != mMWidgets.end(); ii++) {
        if ((*ii)->isMWidgetHidden()) continue;
        //        QApplication::processEvents();
        //qDebug()<<"Fresh:"<<ii.key()<<(*ii)->m_sName;
        (*ii)->MFresh();
    }
}

void MainWindow::MWidgetsTimerFresh()
{
    for (QMap<int32_t, CMWidget*>::iterator ii = mMWidgets.begin();
         ii != mMWidgets.end(); ii++) {
        if ((*ii)->isMWidgetHidden()) continue;
        //        QApplication::processEvents();
        //	qDebug()<<"TimeFresh:"<<ii.key()<<(*ii)->m_sName;
        (*ii)->MTimeFresh();
    }
}

void MainWindow::MWidgetsApply()
{
    for (QMap<int32_t, CMWidget*>::iterator ii = mMWidgets.begin();
         ii != mMWidgets.end(); ii++) {
        if ((*ii)->isMWidgetHidden() || (*ii)->m_bHide) continue;
        //        QApplication::processEvents();
        (*ii)->MApply();

    }
}

void MainWindow::MWidgetsInit()
{
    for (QMap<int32_t, CMWidget*>::iterator ii = mMWidgets.begin(); ii != mMWidgets.end(); ii++) {
        // qDebug()<<ii.key()<<(*ii)->m_sName;
        (*ii)->MInit();
    }
}

void MainWindow::MWidgetsExit()
{

    for (QMap<int32_t, CMWidget*>::iterator ii = mMWidgets.begin(); ii != mMWidgets.end(); ii++) {
        (*ii)->MExit();
    }
}


void MainWindow::mainwindow_Init()
{
    QPixmap logo;
    logo.load(CMakePath::make_bin_path("../theme/LOGO.bmp"));
    QPalette palette;
    palette.setBrush(QPalette::Background, QBrush(logo));
    ui->frame_Logo->setPalette(palette);
    MWidgetsInit();
    on_pushButton_auto_clicked();
    timer_time_fast = startTimer(10);
    timer_time_id = startTimer(200);
    timer_time_slow = startTimer(5000);
    //    timer_widget_id=startTimer(1000/25);

    load_File(CMakePath::make_data_path(m_gSystem.GetCurFile()),
              m_gSystem.GetCurFile());
    ui->treeWidget_file->MFresh();

    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    ui->tableView->setModel(pWorkDriver->m_pmodelLog);
    ui->viewUser->setModel(pWorkDriver->m_ModelWorker);


    ui->widget_State_PI->MInit();
    ui->widget_UPH_Bar->MInit();
    ui->widget_PCS_Bar->MInit();

    ui->widget_UPH_Bar->m_dRangeYMax = 50;
    ui->widget_PCS_Bar->m_dRangeYMax = 500;

    ui->widget_State_PI->m_sName = QObject::trUtf8("State:");
    ui->widget_UPH_Bar->m_sName = QObject::trUtf8("UPH:");
    ui->widget_PCS_Bar->m_sName = QObject::trUtf8("PCS:");

    connect(ui->viewUser, SIGNAL(clicked(const QModelIndex&)), this, SLOT(on_tabUserClicked(const QModelIndex&)));
    ui->dateStart->setDate(QDate::currentDate().addYears(-1));
    ui->dateEnd->setDate(QDate::currentDate());

	ui->treeWidget_logRecord->setFont(QFont("Arial", 15));
	ui->textBrowser_logRecord->setFont(QFont("Arial", 15));
	ui->comboBox_logRecord->setFont(QFont("Arial", 15));
	connect(ui->comboBox_logRecord, SIGNAL(currentIndexChanged(int)), this, SLOT(on_cmbLogRecord_Changed(int)));
	connect(ui->treeWidget_logRecord, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
		this, SLOT(on_treeItemDoubleClicked(QTreeWidgetItem *, int)));
	on_cmbLogRecord_Changed(0);

    QList<QPushButton*> button = this->findChildren<QPushButton*>();
    for (int i = 0; i < button.size(); i++) {
        connect(button.at(i), &QPushButton::clicked, this, [this]()
        {
            QPushButton* pButton = (QPushButton*)sender();
            if (pButton)
            {
                std::string sPathName = fmt::format("{}  {}  ", ((QPushButton*)sender())->text().toLocal8Bit().data(), pButton->objectName().toStdString());
                QWidget* pParent = pButton->parentWidget();
                while (pParent)
                {
                    sPathName += "->" + pParent->objectName().toLocal8Bit().toStdString();
                    pParent = pParent->parentWidget();
                }

                __LOGINSTANCE__.AddRecord(sPathName, "ButtonEvent");
            }
            //std::string sName = ((QPushButton*)sender())->text().toLocal8Bit().data();
        });
    }
}

void MainWindow::mainwindow_Exit()
{
    killTimer(timer_time_id); timer_time_id = 0;
    killTimer(timer_time_slow);
    //    killTimer(timer_widget_id);timer_widget_id=0;
    MWidgetsExit();
}


void MainWindow::on_pushButton_box_apply_2_clicked()
{
    CPreciseTime time1;
    time1.StartTime();
    MWidgetsApply();
    time1.StopTime();
    //    QMessageBox::critical(this,QString("pushButton_box_apply_2"),QString::fromLocal8Bit("pushButton_box_apply_2:%1s")
    //                          .arg(time1.GetTime(),0,'f',3));
}

CThreadWrite::CThreadWrite(MainWindow* pWindow)
{
    m_pWindow = pWindow;
}

void CThreadWrite::run()
{
    Q_ASSERT(m_pWindow);
    try {
        m_gSystem.write_config(true);
        QString path = CMakePath::make_data_path(m_gSystem.GetCurFile());
        m_pWindow->save_File(path);
    } catch (QString& s) {
        m_gSystem.m_SysMsg.SetMsg(s);
    }
}

void MainWindow::on_pushButton_box_save_2_clicked()
{
    ui->pushButton_box_save_2->setEnabled(false);
    ui->pushButton_box_save_2->blockSignals(true);

    QCoreApplication::processEvents();
    on_pushButton_box_apply_2_clicked();
    QTime time1;
    time1.start();

    //    ui->pushButton_box_save_2->setEnabled(false);
    //    CThreadWrite threadwrite(this);
    //    threadwrite.start();
    //    while(threadwrite.isRunning())
    //    {
    //        QApplication::processEvents();
    //    }
    //    ui->pushButton_box_save_2->setEnabled(true);

    m_gSystem.write_config(true);

    MqDebug() << "Write All Config Time:" << time1.elapsed() << "ms";
    QString path = CMakePath::make_data_path(m_gSystem.GetCurFile());
    save_File(path);

    m_gSystem.m_SysMsg.SetMsg(tr("Save param successed"));
    ui->pushButton_box_save_2->setEnabled(true);

    ui->pushButton_box_save_2->blockSignals(false);

    //    time1.StopTime();
    //        QMessageBox::critical(this,QString("threadwrite"),QString::fromLocal8Bit("threadwrite:%1s")
    //                              .arg(time1.GetTime(),0,'f',3));
}


void MainWindow::home_axis_msg(int32_t motorid)
{

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Home"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::HOME
                          << motorid, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}


void MainWindow::on_pushButton_reset_all_clicked()
{
    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }

    QMyMessageBox msgBoxAsk(QMessageBox::Question, tr("Confirm information"), tr("Are you sure to reset all axis?"),
                            QMessageBox::Yes | QMessageBox::No);
    //msgBoxAsk.setStandardButtons();
    msgBoxAsk.setDefaultButton(QMessageBox::No);
    msgBoxAsk.setButtonText(QMessageBox::Yes, tr("Yes"));
    msgBoxAsk.setButtonText(QMessageBox::No, tr("No"));
    int ret = msgBoxAsk.exec();
    if (ret == QMessageBox::No) {
        return;
    }

    try {
        m_gSystem.SafeDoorCheck();
    } catch (const QString& ex) {
        m_gSystem.CloseSafeDoor();
        QString msg = ex;
        m_gSystem.m_SysMsg.SetMsg(msg);
        return;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_All_Home,
                          QObject::trUtf8("Home All"));
    m_gSystem.start_test(SM_TRANS, msgqueue, true);
}

void MainWindow::on_pushButton_box_diagnosis_clicked()
{
    m_pMsgDlg->show();
}


bool MainWindow::load_File(QString path, QString relPath)
{
    if (!m_gSystem.FindSM(SM_TRANS)->IsStop() ||
        !m_gSystem.FindSM(SM_MAIN)->IsStop() ||
        !m_gSystem.FindSM(SM_COAT)->IsStop() ||
        !m_gSystem.FindSM(SM_CLEAN)->IsStop() || 
        !m_gSystem.FindSM(SM_WTLoad)->IsStop() ||
        !m_gSystem.FindSM(SM_WTUnload)->IsStop()) {
        m_gSystem.m_SysMsg.
            SetMsg(QObject::trUtf8("Stop Machine before open file."
                                   "file path:%1").arg(path), WARN_MSG_TYPE);
        return false;
    }
    QFileInfo info(path);
    if (!info.exists() || relPath.isEmpty()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("File is delete or file name is empty,"
                                                  "file name:%1.\nwill select demo file to open:%2.")
                                  .arg(relPath).arg(DEMO_FILE));

        path = CMakePath::make_data_path(DEMO_FILE);
        relPath = DEMO_FILE;
    }
    info = QFileInfo(path);
    if (info.isDir()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("Can not open dir,please select file."
                                                  "file path:%1").arg(relPath));
        return false;
    }

    QMutexLocker locker(&m_MutextRecipe);
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("Can not open file."
                                                  "file path:%1").arg(path));
        ui->treeWidget_file->MFresh();
        return false;
    }
    try {
        //QDataStream stream(&file);
        //m_gSystem.Serialize(stream,false);

        ConfigStreamReader stream(&file);
        m_gSystem.ReadRecipe(stream, 0);
        file.close();

        locker.unlock();

        m_gSystem.SetCurFile(relPath);
        m_gSystem.EvtLog(QString::fromUtf8("DML"),
                         m_gSystem.GetCurFile());

        __LOGINSTANCE__.AddRecord(fmt::format("Param: Load Recipe {}", relPath.toLocal8Bit().data()), "ParamChanged");

        V_MsgQueue msgqueue;
        int maxId = 2;
#ifdef __USE_THIRD_CAMERA__
        maxId = 3;
#endif
        for (int i = 0; i < maxId; i++) {
            int iCamID = CAM2X;
            if (i == maxId - 1)iCamID = CAMKerf;
            if (i == 1)iCamID = CAM6X;
            CCam* pCam = GET_CHDIRECT(iCamID, CCam);
            Q_ASSERT(pCam);
            int ivalue[4] = { 0 };
            ivalue[0] = pCam->m_Variants.get_VData(Var_Cam_Exposure_default_ID)->toInt();
            ivalue[1] = pCam->m_Variants.get_VData(Var_Cam_Brightness_default_ID)->toInt();

            ivalue[2] = pCam->m_Variants.get_VData(Var_Cam_Gain_default_ID)->toInt();
            ivalue[3] = pCam->m_Variants.get_VData(Var_Cam_Contrast_default_ID)->toInt();
            int iID[4] = { Var_Cam_Exposure_ID,Var_Cam_Brightness_ID,
                        Var_Cam_Gain_ID,Var_Cam_Contrast_ID };


            for (int i = 0; i < 4; i++) {
                msgqueue.pushback_Msg(VarMsg_Driver_ID,
                                      QObject::trUtf8("Set Cam Property Sig"),
                                      QVariantList()
                                      << CAM_DRIVER << CCamDriver::SET_CAM_PROPERTY
                                      << iCamID << iID[i] << ivalue[i] << true, 0);
            }
        }

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("Set Multiplier Sig"),
                              QVariantList()
                              << LIGHT_DRIVER_DIRECT << CLightDriver::SETALLMULTIPLIER, 0);

        msgqueue.pushback_Msg(VarMsg_Process_ID,
                              QObject::trUtf8("Load All Model Sig"),
                              QVariantList() << PROCESS_LEVELING
                              << CProcess_Level::LOADLEVELMODEL
                              << relPath, 0);

        m_gSystem.start_manual(SM_MAIN, msgqueue);

        CMProduct* pProduct = GET_CHDIRECT(PRODUCT, CMProduct);
        pProduct->m_dThickDiff = 0;

        if (m_gSystem.m_pMWCamLight2X) {
            CMWCamLight* pCamLight = (CMWCamLight*)m_gSystem.m_pMWCamLight2X;
            pCamLight->SetDefaultLight();
            pCamLight->SetCamDefault();
        }
        if (m_gSystem.m_pMWCamLight6X) {
            CMWCamLight* pCamLight = (CMWCamLight*)m_gSystem.m_pMWCamLight6X;
            pCamLight->SetDefaultLight();
            pCamLight->SetCamDefault();
        }
#ifdef __USE_THIRD_CAMERA__
        if (m_gSystem.m_pMWCamLight4X) {
            CMWCamLight* pCamLight = (CMWCamLight*)m_gSystem.m_pMWCamLight4X;
            pCamLight->SetDefaultLight();
            pCamLight->SetCamDefault();
        }
#endif
        m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("Load recipe successed"));
    } catch (QString& s) {
        m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("read file failed:%1.").arg(s));
        return false;
    }

    return true;
    MWidgetsFresh();
}

void MainWindow::on_pushButton_param_read_clicked()
{
    if (m_gSystem.FindSM(SM_MAIN)->m_pCurState->m_iID != VarState_Idle_Main) {
        return;
    }
    QString path = ui->treeWidget_file->GetSelFullPath();
    QString selPath = ui->treeWidget_file->GetSelRelPath();
    load_File(path, selPath);
    ui->treeWidget_file->MFresh();
    m_gSystem.m_bNeedFreshUI = true;
}
void MainWindow::save_File(const QString& path)
{
    QMutexLocker locker(&m_MutextRecipe);
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly)) {
        MQT_THROW_STR(QObject::trUtf8("Can not open file."
                                      "file path:%1").arg(path));
    }
    //QDataStream stream(&file);
    //m_gSystem.Serialize(stream,true);

    ConfigStreamWriter stream(&file);
    m_gSystem.WriteRecipe(stream, 0);
    file.close();

    __LOGINSTANCE__.AddRecord(fmt::format("Param: Load Recipe {}", path.toLocal8Bit().data()), "ParamChanged");


    //    MWidgetsFresh();
}

void MainWindow::on_pushButton_param_save_clicked()
{
    try {
        ui->pushButton_param_save->setEnabled(false);
        ui->pushButton_param_save->blockSignals(true);

        MWidgetsApply();
        QString path = CMakePath::make_data_path(m_gSystem.GetCurFile());
        save_File(path);
        m_gSystem.EvtLog(QString::fromUtf8("DMW"),
                         m_gSystem.GetCurFile());

        m_gSystem.m_SysMsg.SetMsg(tr("Save param successed"));
        //    MWidgetsFresh();
        //    ui->treeWidget_file->MFresh();

        ui->pushButton_param_save->setEnabled(true);
        ui->pushButton_param_save->blockSignals(false);
    } catch (QString& s) {
        m_gSystem.m_SysMsg
            .SetMsg(QObject::trUtf8("save file failed:%1.")
                    .arg(s));

    }
}

void MainWindow::on_btnSettingSave_clicked()
{
    ui->btnSettingSave->setEnabled(false);
    ui->btnSettingSave->blockSignals(true);

    QCoreApplication::processEvents();
    on_pushButton_box_apply_2_clicked();
    QTime time1;
    time1.start();
    m_gSystem.write_config(true);

    //qDebug()<<"Write All Config Time:"<<time1.elapsed()<<"ms";
    //QString path=CMakePath::make_data_path(m_gSystem.GetCurFile());
    //save_File( path);

    m_gSystem.m_SysMsg.SetMsg(tr("Save param successed"));
    ui->btnSettingSave->setEnabled(true);
    ui->btnSettingSave->blockSignals(false);
}

void MainWindow::on_pushButton_param_new_clicked()
{
    QString path = ui->treeWidget_file->GetSelFullPath();
    QFileInfo info(path);
    QString relpath;
    if (info.isDir()) {
        relpath = ui->treeWidget_file->GetSelRelPath();
        path = info.absoluteFilePath();
    } else {
        relpath = ui->treeWidget_file->GetSelRelDir();
        path = info.absoluteDir().absolutePath();
    }
    QFileInfo infocur(m_gSystem.GetCurFile());
    QString strName = infocur.baseName();
    m_pDlgNewFile->SetCreateInfo(path, strName, relpath, CDlgNewFile::FILE_NORMAL);
    m_pDlgNewFile->show();
}

void MainWindow::on_pushButton_param_new_dir_clicked()
{
    QString path = ui->treeWidget_file->GetSelFullPath();
    QFileInfo info(path);
    QString relpath;
    if (info.isDir()) {
        relpath = ui->treeWidget_file->GetSelRelPath();
        path = info.absoluteFilePath();
    } else {
        relpath = ui->treeWidget_file->GetSelRelDir();
        path = info.absoluteDir().absolutePath();
    }
    m_pDlgNewFile->SetCreateInfo(path, QString(""), relpath, CDlgNewFile::FILE_DIR);
    m_pDlgNewFile->show();
}

void MainWindow::on_pushButton_param_delete_clicked()
{
    int irtn = QMessageBox::warning(this, QObject::trUtf8("Delete File"),
                                    QObject::trUtf8("Deleting file ,can not recovery.\nclick yes continue."),
                                    QMessageBox::Yes, QMessageBox::No);
    if (irtn == QMessageBox::No)return;
    QString path = ui->treeWidget_file->GetSelFullPath();
    QString relpath = ui->treeWidget_file->GetSelRelPath();
    QFileInfo infodata(path);
    QString pathpattern = CMakePath::make_pattern_path(relpath);

    if (infodata.isDir()) {
        if (!relpath.isEmpty()) {
            QDir qDir(path);
            qDir.removeRecursively();

            QDir qDirpattern(pathpattern);
            qDirpattern.removeRecursively();

            if (CMakePath::make_data_path(m_gSystem.GetCurFile()).contains(path, Qt::CaseInsensitive)) {
                load_File(CMakePath::make_data_path(QString(DEMO_FILE)),
                          QString(DEMO_FILE));
            }
        } else {
            m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("can not delete root dir")
                                      .arg(path));
            ui->treeWidget_file->MFresh();
            return;
        }
    } else {
        if (relpath == DEMO_FILE) {
            m_gSystem.m_SysMsg.SetMsg(QObject::trUtf8("can not delete demo file")
                                      .arg(path));
            return;
        }
        QFile::remove(path);

        pathpattern = pathpattern.left(pathpattern.length() - 4);
        QDir qDirpattern(pathpattern);
        qDirpattern.removeRecursively();

        if (relpath == m_gSystem.GetCurFile()) {
            load_File(CMakePath::make_data_path(QString(DEMO_FILE)),
                      QString(DEMO_FILE));
        }
    }

    ui->treeWidget_file->reBuildCtrl();
}


void MainWindow::FreshLog(QString& evtid)
{

    MqDebug() << "Start" << QDateTime::currentDateTime();
    CWorkerDriver* pWorkerDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriver);
    pWorkerDriver->m_pmodelLog->setSort(0, Qt::DescendingOrder);
    qint64 days = 1;
    if (ui->radioButton_day->isChecked())days = 1;
    else if (ui->radioButton_week->isChecked())days = 7;
    else if (ui->radioButton_month->isChecked())days = 30;
    else if (ui->radioButton_year->isChecked())days = 365;
    QDateTime time = QDateTime::currentDateTime().addDays(-days);
    QDateTime datetime = QDateTime::currentDateTime();
    if (ui->radioButton_auto->isChecked()) {
        time = ui->dateStart->dateTime();
        datetime = ui->dateEnd->dateTime();
        days = time.daysTo(datetime);
    }
    if (evtid.isEmpty()) {
        //QDateTime datetime=QDateTime::currentDateTime();
        QString str = QString::fromUtf8("time between '%1' and '%2'")
            .arg(time.toString("yyyy-MM-dd hh:mm:ss"))
            .arg(datetime.toString("yyyy-MM-dd hh:mm:ss"));
        pWorkerDriver->m_pmodelLog->setFilter(str);

        MqDebug() << "Start Analyse" << QDateTime::currentDateTime();
        ui->widget_UPH_Bar->m_dRangeXMax = days + 1;
        ui->widget_PCS_Bar->m_dRangeXMax = days + 1;
        ui->widget_UPH_Bar->m_StartDate = time.date().addDays(0);
        ui->widget_PCS_Bar->m_StartDate = time.date().addDays(0);
        LPI_Graph_Data data; QStringList stringlist;
        LogStateAnalyse(time, data, stringlist);
        ui->widget_State_PI->SetString(stringlist);
        QMutexLocker locker(&ui->widget_State_PI->m_mutex);
        ui->widget_State_PI->m_dataList = data;
        locker.unlock();
        MqDebug() << "End Analyse" << QDateTime::currentDateTime();
        Chart_Data_Vector dataUPH;
        Chart_Data_Vector dataPCS;
        MqDebug() << "Start Production" << QDateTime::currentDateTime();
        LogProductionAnalyse(time, dataUPH, dataPCS);
        ui->widget_PCS_Bar->m_ptVector = dataPCS;
        ui->widget_UPH_Bar->m_ptVector = dataUPH;

        MqDebug() << "End Production Analyse" << QDateTime::currentDateTime();
        ui->widget_PCS_Bar->ZoomFit();
        ui->widget_UPH_Bar->ZoomFit();
    } else {
        QDateTime datetime = QDateTime::currentDateTime();
        QString eveInfo = "'" + evtid.toUpper().replace(",", "','") + "'";
        MqDebug() << eveInfo;
        QString str = QString::fromUtf8("evtID in(%1) and time between '%2' and '%3'")
            .arg(eveInfo)
            .arg(time.toString("yyyy-MM-dd hh:mm:ss"))
            .arg(datetime.toString("yyyy-MM-dd hh:mm:ss"));
        MqDebug() << str;
        pWorkerDriver->m_pmodelLog->setFilter(str);
    }
    MqDebug() << "Start Select" << QDateTime::currentDateTime();
    pWorkerDriver->m_pmodelLog->select();
    MqDebug() << "End" << QDateTime::currentDateTime();

}

void MainWindow::FreshUser()
{
    CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
    QString filter = "";
    if (pWorker->m_workLevel > 3) {
        ui->viewUser->setEditTriggers(QAbstractItemView::DoubleClicked);
        ui->viewUser->setColumnHidden(2, false); //密码
        ui->viewUser->setColumnHidden(3, false); //权限级别
    } else {
        filter = "Level<10";
        ui->viewUser->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->viewUser->setColumnHidden(2, true);
        ui->viewUser->setColumnHidden(3, true);
    }

    //viewUser
    CWorkerDriverUser* pWorkerDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    pWorkerDriver->m_ModelWorker->setSort(0, Qt::DescendingOrder);

    pWorkerDriver->m_ModelWorker->setFilter(filter);
    pWorkerDriver->m_ModelWorker->select();
}

void MainWindow::on_radioButton_day_clicked()
{
    FreshLog(QString());
}

void MainWindow::on_radioButton_week_clicked()
{
    FreshLog(QString());

}

void MainWindow::on_radioButton_month_clicked()
{
    FreshLog(QString());
}

void MainWindow::on_radioButton_year_clicked()
{
    FreshLog(QString());
}
void MainWindow::on_pushButton_record_SelectEvent_clicked()
{
    QString evtid = ui->lineEdit_record_eventID->text();
    FreshLog(evtid);

}

void MainWindow::on_pushButton_log_delete_clicked()
{
    qint64 days = 1;
    if (ui->radioButton_day->isChecked())days = 1;
    else if (ui->radioButton_week->isChecked())days = 7;
    else if (ui->radioButton_month->isChecked())days = 30;
    else if (ui->radioButton_year->isChecked())days = 365;
    QDateTime time = QDateTime::currentDateTime().addDays(-days);
    CWorkerDriver* pWorkerDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriver);
    pWorkerDriver->LogDel(time);
    FreshLog(QString());
}

void MainWindow::on_pushButton_log_export_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, QString(),
                                                CMakePath::make_file_path(""), QString("*.xls"));
    MqDebug() << path;
    if (path.isEmpty()) return;
    qint64 days = 1;
    if (ui->radioButton_day->isChecked())days = 1;
    else if (ui->radioButton_week->isChecked())days = 7;
    else if (ui->radioButton_month->isChecked())days = 30;
    else if (ui->radioButton_year->isChecked())days = 365;
    QDateTime time = QDateTime::currentDateTime().addDays(-days);
    CWorkerDriver* pWorkerDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriver);
    pWorkerDriver->LogExport(time, path);
}
void MainWindow::on_pushButton_login_clicked()
{
    //    CDlgLogin login(this);
    //    int dlgrtn=login.exec();
    //    CWorkerDriver* pWorkerDriver=GET_CARD(M_WORKERDRIVER,CWorkerDriver);
    //    CWorker* pWorker=GET_CHDIRECT(M_WORKER,CWorker);
    //    while(1)
    //    {
    //        if(dlgrtn==QDialog::Accepted)
    //        {
    //            pWorker->m_workName=login.m_name;
    //            bool bGetWorker= pWorkerDriver->GetWorker(M_WORKER);
    //            if(!bGetWorker||pWorker->m_workPWD!=login.m_PWD)
    //            {
    //                pWorker->m_workName=_str_workername[0];
    //                pWorker->m_workPWD="";
    //                pWorker->m_workLevel=1;
    //                login.m_Info=QObject::trUtf8("Unknown user name "
    //                                             "or password.");
    //                dlgrtn=login.exec();
    //            }
    //            else
    //            {
    //                break;
    //            }
    //        }
    //        else
    //        {
    //            pWorker->m_workName=_str_workername[0];
    //            pWorker->m_workPWD="";
    //            pWorker->m_workLevel=1;
    //            pWorkerDriver->GetWorker(M_WORKER);
    //            break;
    //        }
    //    }
    //    ui->page_manual->MFresh();
    //    ui->page_setup->MFresh();
    //    ui->page_comp->MFresh();
    //    ui->page_factory->MFresh();
    ////    ui->groupBox_Light->setEnabled(pWorker->m_workLevel>10);
    //    FreshAuthority();
    m_pDlgLogin->show();
}

void MainWindow::on_pushButton_auto_start_clicked()
{
    QString msg;
    bool bAsk = false;
    if (true == m_gSystem.CheckAutoStart(msg, bAsk)) {

        if (bAsk) {
            QMyMessageBox msgBoxAsk(QMessageBox::Question, tr("Confirm information"), tr("Are you sure to start immediately?"),
                                    QMessageBox::Yes | QMessageBox::No);
            msgBoxAsk.setDefaultButton(QMessageBox::No);
            msgBoxAsk.setButtonText(QMessageBox::Yes, tr("Yes"));
            msgBoxAsk.setButtonText(QMessageBox::No, tr("No"));
            int ret = msgBoxAsk.exec();
            if (QMessageBox::Yes == ret) {
                m_gSystem.publish_msg(V_Msg(VarMsg_StartAuto_ID,
                                            QObject::trUtf8("Start Auto")));
            }
        } else {
            m_gSystem.publish_msg(V_Msg(VarMsg_StartAuto_ID,
                                        QObject::trUtf8("Start Auto")));

        }

        /*if(ui->btnAlarmProcess->isChecked())
        {
            ui->btnAlarmProcess->click();
        }*/

        g_SecsManager.SendEvent(EVENT_ManualStarted);
    } else {
        m_gSystem.m_SysMsg.SetMsg(msg, WARN_MSG_TYPE);
    }
}

void MainWindow::on_pushButton_auto_pause_clicked()
{
    m_gSystem.FindSM(SM_Schedular)->pushfront_Msg(VarMsg_Pause_ID,
                                                  QObject::trUtf8("Pause Sig"));

    m_gSystem.FindSM(SM_MAIN)->pushfront_Msg(VarMsg_Pause_ID,
                                             QObject::trUtf8("Pause Sig"));

    m_gSystem.FindSM(SM_TRANS)->pushfront_Msg(VarMsg_Pause_ID,
                                              QObject::trUtf8("Pause Sig"));

    m_gSystem.EvtLog(QObject::tr("OP"), QObject::tr("Pause Trans And Cut"));
    g_SecsManager.SendEvent(EVENT_ManualPaused);
    //    m_gSystem.publish_msg(V_Msg(VarMsg_Pause_ID,
    //                                QObject::trUtf8("Pause Sig")));
}


void MainWindow::on_pushButton_box_LOAD_SIDE_clicked()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_System_ChangeSide,
                          QObject::trUtf8("Change Side Load"),
                          QVariantList() << -1, 0);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_pushButton_box_A_SIDE_clicked()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_System_ChangeSide,
                          QObject::trUtf8("Change Side A"),
                          QVariantList() << SIDE_A, 0);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_pushButton_box_B_SIDE_clicked()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_System_ChangeSide,
                          QObject::trUtf8("Change Side B"),
                          QVariantList() << SIDE_B, 0);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_pushButton_box_cam2X_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(CAM2X, true, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_pushButton_box_cam6X_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(CAM6X, true, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_pushButton_box_D_NORROW_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(LASERPATH_D_NARROW, true, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_btnLNarrow_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(LASERPATH_L_NARROW, true, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_btnDistanceSensor_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(DistanceSensor, true, msgqueue);
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_pushButton_box_D_WIDE_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(LASERPATH_D_WIDE, true, msgqueue);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}

void MainWindow::on_pushButton_auto_cass_up_clicked()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Cass Up"),
                          QVariantList()
                          << PROCESS_SCAN
                          << CProcess_Scan::CASSUP << CASSETTE, 0);
    m_gSystem.start_test(SM_TRANS, msgqueue, false);
}

void MainWindow::on_pushButton_auto_pause_coat_clicked()
{
    m_gSystem.publish_msg(V_Msg(VarMsg_Pause_ID,
                                QObject::trUtf8("Pause Sig")));

    m_gSystem.EvtLog(QObject::tr("OP"), QObject::tr("Pause Coat Clean"));

    g_SecsManager.SendEvent(EVENT_ManualPaused);
}

void MainWindow::on_pushButton_direct_homeTrans_clicked()
{
    if (false == IsOperatorCanOperate())return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Home,
                          QObject::trUtf8("Trans Home"),
                          QVariantList() << true);
    m_gSystem.start_test(SM_TRANS, msgqueue, false);
}

void MainWindow::on_pushButton_direct_WTReset_clicked()
{
    if (false == IsOperatorCanOperate())return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Home,
                          QObject::trUtf8("WT Home"),
                          QVariantList() << true);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}

//void on_pushButton_direct_CLeanTReset_clicked()
//{
//    V_MsgQueue msgqueue;
//    msgqueue.pushback_Msg(VarMsg_Home,
//                          QObject::trUtf8("Clean Home"),
//                          QVariantList()<<true);
//    m_gSystem.start_test(SM_CLEAN, msgqueue,false);
//}

void MainWindow::on_pushButton_direct_CTReset_clicked()
{
    if (false == IsOperatorCanOperate())return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Home,
                          QObject::trUtf8("Coat Home"),
                          QVariantList() << true);
    m_gSystem.start_test(SM_COAT, msgqueue, false);
}

void MainWindow::on_pushButton_direct_CLeanTReset_clicked()
{
    if (false == IsOperatorCanOperate())return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Home,
                          QObject::trUtf8("Clean Home"),
                          QVariantList() << true);
    m_gSystem.start_test(SM_CLEAN, msgqueue, false);
}

void MainWindow::on_pushButton_direct_TransReset_clicked()
{
    if (false == IsOperatorCanOperate())return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Home,
                          QObject::trUtf8("Transfer Home"),
                          QVariantList() << true);
    m_gSystem.start_test(SM_TRANS, msgqueue, false);
}



void MainWindow::on_pushButton_direct_VaccWT_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //if(!m_gSystem.IsAllSMStopped()) 
    //{
    //	m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
    //	return;
    //}
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("WT.Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_WT_WAFER_VACUUM
                          << checked, 0);
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("WT. Ring Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_WT_RING_VACUUM
                          << checked, 0);
    if (!checked) {
        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("WT.Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_WT_WAFER_VACUUM_BREAK
                              << true, 0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("WT.Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_WT_WAFER_VACUUM_BREAK
                              << false, 0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("WT. Ring Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_WT_RING_VACUUM_BREAK
                              << true, 0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("WT. Ring Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_WT_RING_VACUUM_BREAK
                              << false, 0);
    }
    m_gSystem.start_test(SM_MAIN, msgqueue);
}

void MainWindow::on_pushButton_direct_VaccCT_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //    if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("CT. Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_COAT_VACUUM
                          << checked, 0);
    if (!checked) {
        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("CT. Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_COAT_VACUUM_BREAK
                              << true, 0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("CT. Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_COAT_VACUUM_BREAK
                              << false, 0);
    }
    m_gSystem.start_test(SM_COAT, msgqueue);
}

void MainWindow::on_pushButton_direct_VaccClean_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //    if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("CT. Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_CLEAN_VACUUM
                          << checked, 0);
    if (!checked) {
        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("CT. Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_CLEAN_VACUUM_BREAK
                              << true, 0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("CT. Vacc Break OpenClose Sig"),
                              QVariantList()
                              << MOTOR_DRIVER << CMotorDriver::SETIO
                              << IO_OUTPUT << OUT_CLEAN_VACUUM_BREAK
                              << false, 0);
    }
    m_gSystem.start_test(SM_CLEAN, msgqueue);
}

void MainWindow::on_pushButton_direct_VaccUnLoad_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //    if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Load Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_UNLOAD_VACUUM
                          << checked, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue);
}

void MainWindow::on_pushButton_direct_VaccLoad_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //    if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Load Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_LOAD_VACUUM
                          << checked, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue);
}

void MainWindow::on_pushButton_direct_VaccTrans_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //    if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Trans Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_TRANSFER_VACUUM
                          << checked, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue);
}

void MainWindow::freshDirectIO()
{
    CMotorDriver* pMotorDriver = GET_CARD(MOTOR_DRIVER, CMotorDriver);
    bool bvaccumTrans = pMotorDriver->get_iodata(IO_OUTPUT, OUT_TRANSFER_VACUUM, false) ? true : false;
    bool bvaccumLoad = pMotorDriver->get_iodata(IO_OUTPUT, OUT_LOAD_VACUUM, false) ? true : false;
    bool bvaccumUnload = pMotorDriver->get_iodata(IO_OUTPUT, OUT_UNLOAD_VACUUM, false) ? true : false;
    bool bvaccumWT = pMotorDriver->get_iodata(IO_OUTPUT, OUT_WT_WAFER_VACUUM, false) ? true : false;
    bool bvaccumCoat = pMotorDriver->get_iodata(IO_OUTPUT, OUT_COAT_VACUUM, false) ? true : false;
    bool bvaccumClean = pMotorDriver->get_iodata(IO_OUTPUT, OUT_CLEAN_VACUUM, false) ? true : false;

    bool bvaccumWTBreak = pMotorDriver->get_iodata(IO_OUTPUT, OUT_WT_WAFER_VACUUM_BREAK, false) ? true : false;
    bool bvaccumCoatBreak = pMotorDriver->get_iodata(IO_OUTPUT, OUT_COAT_VACUUM_BREAK, false) ? true : false;
    bool bvaccumCleanBreak = pMotorDriver->get_iodata(IO_OUTPUT, OUT_CLEAN_VACUUM_BREAK, false) ? true : false;

    /*bool bspindleCoat = pMotorDriver->get_iodata(IO_OUTPUT, OUT_COAT_SPINDLE_UPDOWN, false) ? true : false;
    bool bspindleClean = pMotorDriver->get_iodata(IO_OUTPUT, OUT_CLEAN_SPINDLE_UPDOWN, false) ? true : false;*/

    bool bCurtainOpendCoat = pMotorDriver->get_iodata(IO_OUTPUT, OUT_COAT_CURTAIN_OPENED, false);
    bool bCurtainOpendClean = pMotorDriver->get_iodata(IO_OUTPUT, OUT_CLEAN_CURTAIN_OPENED, false);

    //true的时候是打开
    bool bGrabOpened = pMotorDriver->get_iodata(IO_OUTPUT, OUT_CLAW_CLOSED, true);
    if (ui->pushButton_direct_ClawOpen->isChecked() != !bGrabOpened) {
        ui->pushButton_direct_ClawOpen->setChecked(!bGrabOpened);
    }

    if (ui->pushButton_direct_ClawClose->isChecked() != bGrabOpened) {
        ui->pushButton_direct_ClawClose->setChecked(bGrabOpened);
    }

    if (ui->pushButton_direct_VaccTrans->isChecked() != bvaccumTrans)
        ui->pushButton_direct_VaccTrans->setChecked(bvaccumTrans);

    if (ui->pushButton_direct_VaccLoad->isChecked() != bvaccumLoad)
        ui->pushButton_direct_VaccLoad->setChecked(bvaccumLoad);

    if (ui->pushButton_direct_VaccUnLoad->isChecked() != bvaccumUnload)
        ui->pushButton_direct_VaccUnLoad->setChecked(bvaccumUnload);

    if (ui->pushButton_direct_VaccWT->isChecked() != bvaccumWT)
        ui->pushButton_direct_VaccWT->setChecked(bvaccumWT);

    if (ui->pushButton_direct_VaccCT->isChecked() != bvaccumCoat)
        ui->pushButton_direct_VaccCT->setChecked(bvaccumCoat);

    if (ui->pushButton_direct_VaccClean->isChecked() != bvaccumClean)
        ui->pushButton_direct_VaccClean->setChecked(bvaccumClean);

    //if (ui->pushButton_direct_Spindle_Coat->isChecked() != bspindleCoat)
    //    ui->pushButton_direct_Spindle_Coat->setChecked(bspindleCoat);

    //if (ui->pushButton_direct_Spindle_Clean->isChecked() != bspindleClean)
    //    ui->pushButton_direct_Spindle_Clean->setChecked(bspindleClean);

    if (ui->pushButton_direct_CoatCurtain->isChecked() != bCurtainOpendCoat)
        ui->pushButton_direct_CoatCurtain->setChecked(bCurtainOpendCoat);

    if (ui->pushButton_direct_CleanCurtain->isChecked() != bCurtainOpendClean)
        ui->pushButton_direct_CleanCurtain->setChecked(bCurtainOpendClean);


    if (ui->btnVaccWTBreak->isChecked() != bvaccumWTBreak)
        ui->btnVaccWTBreak->setChecked(bvaccumWTBreak);

    if (ui->btnVaccCTBreak->isChecked() != bvaccumCoatBreak)
        ui->btnVaccCTBreak->setChecked(bvaccumCoatBreak);

    if (ui->btnVaccCleanBreak->isChecked() != bvaccumCleanBreak)
        ui->btnVaccCleanBreak->setChecked(bvaccumCleanBreak);
#ifdef __USE_IO_UPLOAD__
    bool bLoadRight = pMotorDriver->get_iodata(IO_OUTPUT, OUT_LOAD_LEFTRIGHT, false) ? true : false;
    bool bLoadDown = pMotorDriver->get_iodata(IO_OUTPUT, OUT_LOAD_UPDOWN, false) ? true : false;
    bool bUnLoadRight = pMotorDriver->get_iodata(IO_OUTPUT, OUT_UNLOAD_LEFTRIGHT, false) ? true : false;
    bool bUnLoadDown = pMotorDriver->get_iodata(IO_OUTPUT, OUT_UNLOAD_UPDOWN, false) ? true : false;


    if (ui->pushButton_direct_LoadRight->isChecked() != bLoadRight)
        ui->pushButton_direct_LoadRight->setChecked(bLoadRight);

    if (ui->pushButton_direct_LoadDown->isChecked() != bLoadDown)
        ui->pushButton_direct_LoadDown->setChecked(bLoadDown);


    if (ui->pushButton_direct_UnloadRight->isChecked() != bUnLoadRight)
        ui->pushButton_direct_UnloadRight->setChecked(bUnLoadRight);

    if (ui->pushButton_direct_UnloadDown->isChecked() != bUnLoadDown)
        ui->pushButton_direct_UnloadDown->setChecked(bUnLoadDown);
#endif
}

void MainWindow::freshEAPStatus()
{
    ui->lblEapComm->setText(g_SecsManager.GetCommStateStr(g_SecsManager.getCurCommState()).c_str());
    ui->lblEapMode->setText(g_SecsManager.GetCtrlStateStr(g_SecsManager.getCurCtrlState()).c_str());
}

void MainWindow::freshButtonStatus()
{
    freshButtonStatus(SM_COAT, VarState_ReplaceFluid_ID, ui->btnReplaceCoatLiquid);
    freshButtonStatus(SM_MAIN, VarState_PowerCheck_ID, ui->btnLaserCheck);
    freshButtonStatus(SM_TRANS, VarState_Home_Count, ui->pushButton_reset_all);

    if (m_gSystem.IsSafeDoorOpened()) {
        ui->btnSafeDoor->setChecked(false);
    } else {
        ui->btnSafeDoor->setChecked(true);
    }

    bool bLaserInited = false;
    bool bPreheat = true;
    static bool bLaserIconOn = false;
    CLaserDriver_Base* pLaser = GET_CARD(LASER_DRIVER, CLaserDriver_Base);
    QIcon& icon = pLaser ? icon_blue : icon_off;
    if (pLaser->m_bPreheat || pLaser->m_bError || !pLaser->m_bEmissionOn) {
        if (bLaserIconOn) {
            ui->btnInitLaser->setIcon(icon_off);
            bLaserIconOn = false;
        }
        ui->btnInitLaser->setEnabled(true);

    } else {
        if (!pLaser->m_bExternalGate || !pLaser->m_bInternalGate) {
            if (bLaserIconOn) {
                ui->btnInitLaser->setIcon(icon_off);
                bLaserIconOn = false;
            }
            ui->btnInitLaser->setEnabled(true);
        } else {
            if (pLaser->m_bInited) {
                if (ui->btnInitLaser->isEnabled() != true)
                    ui->btnInitLaser->setEnabled(true);

                if (false == bLaserIconOn) {
                    ui->btnInitLaser->setIcon(icon_blue);
                    bLaserIconOn = true;
                }
            }
        }
    }

    if (!pLaser->m_bInited) {
        if (bLaserIconOn) {
            ui->btnInitLaser->setIcon(icon_off);
            bLaserIconOn = false;
        }
        ui->btnInitLaser->setEnabled(false);
    }

}

void MainWindow::freshButtonStatus(int iSMID, int iStateId, QPushButton* pBtn)
{
    QMutexLocker l(&m_gSystem.FindSM(iSMID)->m_SMMutex);
    int iType = m_gSystem.FindSM(iSMID)->m_pCurState->m_iStateType;
    int iCurStateId = m_gSystem.FindSM(iSMID)->m_pCurState->m_iID;
    bool bSemiRun = false;
    if (iType == VS_Thread::State_Work_Test) {
        //手动指令运行中
        bSemiRun = true;
    }
    l.unlock();
    if (bSemiRun) {
        if (iCurStateId == iStateId) {
            pBtn->setChecked(true);
            pBtn->setEnabled(true);
        } else {
            pBtn->setChecked(false);
            pBtn->setEnabled(false);
        }
    } else {
        pBtn->setChecked(false);
        pBtn->setEnabled(true);
    }
}

void MainWindow::on_pushButton_box_save_screen_clicked()
{
    QScreen* screen = QGuiApplication::primaryScreen();

    QString filePathName = "screen-";

    filePathName += QDateTime::currentDateTime().toString("yyyy_MM_dd_hh_mm_ss");
    filePathName += ".jpg";
    QString filepath = CMakePath::make_file_path(filePathName);
    if (!screen->grabWindow(0).save(filepath, "jpg")) {
        m_gSystem.m_SysMsg.SetMsg(tr("Save screen failed"));
    }
}

void MainWindow::on_pushButton_direct_InitWT_clicked()
{
    if (false == IsOperatorCanOperate())
        return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("move WT Init  pos Sig"),
                          QVariantList()
                          << WORKTABLE_DRIVER
                          << CMWorkTableDriver::MANUALLOADPOS, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue);

}

void MainWindow::on_pushButton_direct_InitCT_clicked()
{
    if (false == IsOperatorCanOperate())
        return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("move CoatTable Init  pos Sig"),
                          QVariantList()
                          << PROCESS_COAT
                          << CProcess_CoatClean::INIT_POS, 0);
    m_gSystem.start_test(SM_COAT, msgqueue);
}

void MainWindow::on_pushButton_direct_InitCleanT_clicked()
{
    if (false == IsOperatorCanOperate())
        return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("move CoatTable Init  pos Sig"),
                          QVariantList()
                          << PROCESS_CLEAN
                          << CProcess_CoatClean::INIT_POS, 0);
    m_gSystem.start_test(SM_CLEAN, msgqueue);
}


void MainWindow::on_pushButton_direct_InitTrans_clicked()
{
    if (false == IsOperatorCanOperate())
        return;

    if (!m_gSystem.IsAllSMStopped()) {
        m_gSystem.m_SysMsg.SetMsg(QObject::tr("Other operator running"), NOTIFY_MSG_TYPE);
        return;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("move Trans Init  pos Sig"),
                          QVariantList()
                          << PROCESS_TRANS
                          << CProcess_Trans::MOVEINITPOS, 0);
    m_gSystem.start_test(SM_TRANS, msgqueue);
}

void MainWindow::on_pushButton_direct_ClawOpen_clicked()
{
    if (false == IsOperatorCanOperate())return;
    //if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Claw  Open Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_CLAW_CLOSED
                          << false, 0);
    m_gSystem.start_test(SM_TRANS, msgqueue);
}

void MainWindow::on_pushButton_direct_ClawClose_clicked()
{
    if (false == IsOperatorCanOperate())return;
    //if(!m_gSystem.IsAllSMStopped()) return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Claw  Close Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_CLAW_CLOSED
                          << true, 0);
    m_gSystem.start_test(SM_TRANS, msgqueue);
}

void MainWindow::on_pushButton_direct_AutoLight_clicked()
{
    if (m_iCurChID != CAM2X && m_iCurChID != CAM6X) return;
    V_MsgQueue msgqueue;
    m_gSystem.SetDefaultLight_Sig(m_iCurChID, msgqueue);

    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Cam Auto Adjust Sig"),
                          QVariantList()
                          << CAM_DRIVER << CCamDriver::AUTOADJUST_PROPERTY
                          << m_iCurChID, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}

void MainWindow::on_pushButton_terminal_clicked()
{
    m_pDlgTerminal->show();
}

void MainWindow::on_pushButton_auto_select_clicked(bool checked)
{
    if (!m_gSystem.IsAllSMStopped()) {
        ui->pushButton_auto_select->setChecked(!checked);
        return;
    }
    CCassette* pCass = GET_CHDIRECT(CASSETTE, CCassette);
    Q_ASSERT(pCass);
    for (int i = 0; i < MAX_SLOT; i++) {
        pCass->vslots[i].bEnableCut = checked;
    }
}

void MainWindow::on_pushButton_factory_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_manual);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
    ui->stackedWidget_ctrl->MsetCurrentWidget(ui->page_factory);
}


void MainWindow::onLogTips(const QModelIndex& index)
{
    if (index.column() != 2)return;
    int iReturnCount = 50;
    QString str = index.data().toString();
    int iSize = str.size();
    int i = iReturnCount;
    while (i < iSize) {
        str.insert(i, '\n');
        i += iReturnCount;
    }

    QToolTip::showText(QCursor::pos(), str);
    return;
}


void MainWindow::on_pushButton_direct_LoadDown_clicked(bool checked)
{
    Q_UNUSED(checked);
#ifdef __USE_IO_UPLOAD__
    if (!m_gSystem.IsAllSMStopped()) return;
    int iEndIO = IN_LOAD_UP_BACK;
    int iDirectIO = 0;
    if (checked) {
        iEndIO = IN_LOAD_DOWN_FORWARD;
        iDirectIO = 1;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Load Move Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::CYLINDERMOVE
                          << OUT_LOAD_UPDOWN_START << iEndIO << OUT_LOAD_UPDOWN
                          << OUT_LOAD_UPDOWN << iDirectIO << iDirectIO << -1);
    m_gSystem.start_test(SM_MAIN, msgqueue);
#endif
}

void MainWindow::on_pushButton_direct_LoadRight_clicked(bool checked)
{
    Q_UNUSED(checked);
#ifdef __USE_IO_UPLOAD__
    if (!m_gSystem.IsAllSMStopped()) return;
    int iEndIO = IN_LOAD_LEFT;
    int iDirectIO = 0;
    if (checked) {
        iEndIO = IN_LOAD_RIGHT;
        iDirectIO = 1;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Load Move Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::CYLINDERMOVE
                          << OUT_LOAD_LEFTRIGHT_START << iEndIO << OUT_LOAD_LEFTRIGHT
                          << OUT_LOAD_LEFTRIGHT << iDirectIO << iDirectIO << -1);
    m_gSystem.start_test(SM_MAIN, msgqueue);
#endif
}

void MainWindow::on_pushButton_direct_UnloadDown_clicked(bool checked)
{
    Q_UNUSED(checked)
#ifdef __USE_IO_UPLOAD__
        if (!m_gSystem.IsAllSMStopped()) return;
    int iEndIO = IN_UNLOAD_UP_BACK;
    int iDirectIO = 0;
    if (checked) {
        iEndIO = IN_UNLOAD_DOWN_FORWARD;
        iDirectIO = 1;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Load Move Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::CYLINDERMOVE
                          << OUT_UNLOAD_UPDOWN_START << iEndIO << OUT_UNLOAD_UPDOWN
                          << OUT_UNLOAD_UPDOWN << iDirectIO << iDirectIO << -1);
    m_gSystem.start_test(SM_MAIN, msgqueue);
#endif
}

void MainWindow::on_pushButton_direct_UnloadRight_clicked(bool checked)
{
    Q_UNUSED(checked)
#ifdef __USE_IO_UPLOAD__
        if (!m_gSystem.IsAllSMStopped()) return;
    int iEndIO = IN_UNLOAD_LEFT;
    int iDirectIO = 0;
    if (checked) {
        iEndIO = IN_UNLOAD_RIGHT;
        iDirectIO = 1;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Load Move Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::CYLINDERMOVE
                          << OUT_UNLOAD_LEFTRIGHT_START << iEndIO << OUT_UNLOAD_LEFTRIGHT
                          << OUT_UNLOAD_LEFTRIGHT << iDirectIO << iDirectIO << -1);
    m_gSystem.start_test(SM_MAIN, msgqueue);
#endif
}

void MainWindow::on_pushButton_box_showCtrl_clicked(bool checked)
{
    /*ui->tabWidget_status->setVisible(!checked&&
                                     !ui->pushButton_showState->isChecked());
    ui->tabWidget_view->setVisible(!checked);*/

    ui->stackedWidget_input->setVisible(!checked);

}

void MainWindow::on_pushButton_showState_clicked(bool checked)
{
    ui->tabWidget_status->setVisible(!checked);

    //CMWViewWorkTable* pMWViewWT=(CMWViewWorkTable*)(mMWidgets[MW_view_WT]);
    //pMWViewWT->setResizeTabIndex(1);
    //pMWViewWT->setResizeTabIndex(2);
    //pMWViewWT->setResizeTabIndex(3);

}

void MainWindow::ResizeCtrlSize(int istate)
{
    QSize size = this->size(); double dparent = 0.9;
    double dWidth = size.width() - ui->widget_Navigation->width()
        - ui->stackedWidget_button->width() - 10;
    switch (istate) {
    case Ctrl_Max:
    {
    }
    break;
    case Ctrl_Normal:
    {
        dparent = 0.5;
    }
    break;
    default:
        Q_ASSERT(0);
        break;
    }
    //    ui->tabWidget_view->setMinimumWidth(dWidth*dparent);
    //    ui->tabWidget_status->setMinimumWidth(dWidth*dparent);

    ui->stackedWidget_ctrl->setMinimumWidth(dWidth * dparent);
    ui->stackedWidget_ctrl->setMaximumWidth(dWidth * dparent);

    ui->stackedWidget_input->setMinimumWidth(dWidth * dparent);
    ui->stackedWidget_input->setMaximumWidth(dWidth * dparent);

}

void MainWindow::ShowMax()
{
    show();
    m_iTimerShowMax = startTimer(10);
}

void MainWindow::on_pushButton_box_cover_screen_clicked()
{
    m_pCoverDlg->ShowDlg(true);
}


void MainWindow::on_checkBox_MoveAfterHome_clicked(bool checked)
{
    m_gSystem.m_bMoveInitPos = checked;
}

void MainWindow::on_pushButton_direct_CoatCurtain_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Coat Curtain Open Close Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_COAT_CURTAIN_OPENED
                          << checked, 0);
    m_gSystem.start_test(SM_COAT, msgqueue);
}

void MainWindow::on_pushButton_direct_CleanCurtain_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Clean Curtain Open Close Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_CLEAN_CURTAIN_OPENED
                          << checked, 0);
    m_gSystem.start_test(SM_COAT, msgqueue);
}


void MainWindow::on_pushButton_direct_Spindle_Coat_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //if(!m_gSystem.IsAllSMStopped()) return;

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Load Move Sig"),
                          QVariantList()
                          << PROCESS_COAT << CProcess_CoatClean::SPINDLE_UP
                          << checked);
    m_gSystem.start_test(SM_COAT, msgqueue);
}

void MainWindow::on_pushButton_direct_Spindle_Clean_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //if(!m_gSystem.IsAllSMStopped()) return;

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Load Move Sig"),
                          QVariantList()
                          << PROCESS_CLEAN << CProcess_CoatClean::SPINDLE_UP
                          << checked);
    m_gSystem.start_test(SM_CLEAN, msgqueue);
}

void MainWindow::on_pushButton_Stop_clicked()
{
    m_gSystem.publish_msg(V_Msg(VarMsg_Stop_ID, QObject::trUtf8("Stop All")));
    m_gSystem.m_totalWorkTime.PauseTime();
    m_gSystem.m_fullAutoTime.StopTime();

    g_SecsManager.SendEvent(EVENT_ManualAborted);
}

void MainWindow::on_btnModifyWaferStatus_clicked()
{
    if (!m_gSystem.IsAllSMStopped())
    {
        return;
    }

    m_pDlgCasslotStatuSet->show();
}

void MainWindow::on_pushButton_box_cam4X_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(CAMKerf, true, msgqueue);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}

void MainWindow::on_btnSingleNarrow_clicked()
{
    V_MsgQueue msgqueue;
    m_gSystem.changeChannel_msg(LASERPATH_S_NARROW, true, msgqueue);
    m_gSystem.start_test(SM_MAIN, msgqueue, false);
}

void MainWindow::on_pushButton_user_clicked()
{
    ui->stackedWidget_button->MsetCurrentWidget(ui->pushButton_user);
    ui->stackedWidget_main->MsetCurrentWidget(ui->page_user);
    ui->radioButton_day->setChecked(true);
    FreshUser();
}

void MainWindow::on_tabUserClicked(const QModelIndex& index)
{
    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    Q_ASSERT(pWorkDriver);
    if (index.isValid()) {
        QString name = pWorkDriver->m_ModelWorker->index(index.row(), 0).data().toString();
        QString uid = pWorkDriver->m_ModelWorker->index(index.row(), 1).data().toString();
        QString pwd = pWorkDriver->m_ModelWorker->index(index.row(), 2).data().toString();
        QString level = pWorkDriver->m_ModelWorker->index(index.row(), 3).data().toString();
        QString group = pWorkDriver->m_ModelWorker->index(index.row(), 4).data().toString();

        ui->txtUserName->setText(name);
        ui->cbxUserTeam->setCurrentText(group);
        ui->txtUserPassword->setText(pwd);

        static STUserInfo* user = new STUserInfo;
        user->_uid = uid;
        user->_lid = level;
        ui->txtUserName->setUserData(Qt::UserRole, user);
    }
}

void MainWindow::on_btn_user_fresh_clicked()
{
    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    Q_ASSERT(pWorkDriver);
    FreshUser();
}

void MainWindow::on_btnSubmit_clicked()
{
    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    Q_ASSERT(pWorkDriver);
    pWorkDriver->Commit();
    FreshUser();
}

void MainWindow::on_btnDel_clicked()
{
    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    Q_ASSERT(pWorkDriver);
    QString error = "";
    pWorkDriver->DeleteUser(ui->txtUserName->text(), error);
    FreshUser();
}

void MainWindow::on_btnAdd_clicked()
{
    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    Q_ASSERT(pWorkDriver);
    QString error = "";
    pWorkDriver->AddUser(ui->txtUserName->text(), ui->cbxUserTeam->currentData().toInt(), ui->cbxUserTeam->currentText(), ui->txtUserPassword->text(), error);
    FreshUser();
}

void MainWindow::on_btnModify_clicked()
{
    CWorkerDriverUser* pWorkDriver = GET_CARD(M_WORKERDRIVER, CWorkerDriverUser);
    Q_ASSERT(pWorkDriver);
    QString error = "";
    STUserInfo* pUserInfo = (STUserInfo*)(ui->txtUserName->userData(Qt::UserRole));
    Q_ASSERT(pUserInfo);

    if (ui->chkModifyPwd->isChecked()) {
        pWorkDriver->ModifyUser(pUserInfo->_uid.toInt(), ui->txtUserName->text(), ui->cbxUserTeam->currentData().toInt(), ui->cbxUserTeam->currentText(), ui->txtUserPassword->text(), error);
    } else {
        pWorkDriver->ModifyUser(pUserInfo->_uid.toInt(), ui->txtUserName->text(), ui->cbxUserTeam->currentData().toInt(), ui->cbxUserTeam->currentText(), error);
    }
    FreshUser();
}

void MainWindow::on_pushButton_clicked()
{
    //TODO:激光器状态监控
    QString msg = "";
    CLaserDriver_SP* pLaser = GET_CARD(LASER_DRIVER, CLaserDriver_SP);
    if (nullptr != pLaser) {
        if (false == pLaser->m_bInited) {
            msg = QObject::tr("Laser is not connected");
        } else if (pLaser->m_bPreheat) {

            msg = QObject::tr("Laser is preheating,please waiting") + QString("Remain:%1 S").arg(pLaser->m_iPreheatTimeSecs);
        } else if (pLaser->m_bError) {
            msg = QObject::tr("Laser is error, please contact manager");
        }
    }
    m_gSystem.m_SysMsg.SetMsg(msg, WARN_MSG_TYPE);
}

void MainWindow::on_btnVaccWTBreak_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //WT平台破真空
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("WT.Vacc Break OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_WT_WAFER_VACUUM_BREAK
                          << checked, 0);
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("WT.Vacc Break OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_WT_RING_VACUUM_BREAK
                          << checked, 0);
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("WT.Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_WT_WAFER_VACUUM
                          << false, 0);
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("WT.Vacc OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_WT_RING_VACUUM
                          << false, 0);
    m_gSystem.start_test(SM_MAIN, msgqueue);
}

void MainWindow::on_btnVaccCTBreak_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //Coat平台破真空
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("CT. Vacc Break OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_COAT_VACUUM_BREAK
                          << checked, 0);
    m_gSystem.start_test(SM_COAT, msgqueue);
}

void MainWindow::on_btnVaccCleanBreak_clicked(bool checked)
{
    if (false == IsOperatorCanOperate())return;
    //Clean平台破真空
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("CT. Vacc Break OpenClose Sig"),
                          QVariantList()
                          << MOTOR_DRIVER << CMotorDriver::SETIO
                          << IO_OUTPUT << OUT_CLEAN_VACUUM_BREAK
                          << checked, 0);
    m_gSystem.start_test(SM_CLEAN, msgqueue);
}

void MainWindow::on_btnVaccUnLoadBreak_clicked(bool checked)
{

}

void MainWindow::on_radioButton_auto_clicked()
{
    FreshLog(QString());
}

void MainWindow::on_btnAlarmProcess_clicked(bool checked)
{
    /*if(checked){
        ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_auto);
        ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
        ui->stackedWidget_ctrl->MsetCurrentWidget(mMWidgets[MW_ALARM_PROCESS]);
    }
    else{
        ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_auto);
        ui->stackedWidget_main->MsetCurrentWidget(ui->page_ctrl);
        ui->stackedWidget_ctrl->MsetCurrentWidget(mMWidgets[MW_AUTO]);
    }*/
}

void MainWindow::on_btnLaserCheck_clicked()
{
    QMyMessageBox msgBoxAsk(QMessageBox::Question, tr("Confirm information"), tr("Are you sure to do laser recheck?"),
                            QMessageBox::Yes | QMessageBox::No);
    //msgBoxAsk.setStandardButtons();
    msgBoxAsk.setDefaultButton(QMessageBox::No);
    msgBoxAsk.setButtonText(QMessageBox::Yes, tr("Yes"));
    msgBoxAsk.setButtonText(QMessageBox::No, tr("No"));
    int ret = msgBoxAsk.exec();
    if (ret == QMessageBox::No) {
        return;
    }

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_PowerCheck_ID,
                          QObject::trUtf8("Power Check"));
    m_gSystem.start_manual(SM_MAIN, msgqueue, true);
}

void MainWindow::on_btnSafeDoor_clicked(bool checked)
{
    if (checked) {
        m_gSystem.CloseSafeDoor();
    } else {
        m_gSystem.OpenSafeDoor();
    }
}

void MainWindow::on_btnInitLaser_clicked()
{
    CLaserDriver_SP* pLaser = GET_CARD(LASER_DRIVER, CLaserDriver_SP);
    bool bEnabled = false;
    QString msg;
    if (nullptr != pLaser) {
        if (false == pLaser->m_bInited) {
            msg = QObject::tr("Laser is not connected");
        } else if (pLaser->m_bPreheat) {

            msg = QObject::tr("Laser is preheating,please waiting") + QString("Remain:%1 S").arg(pLaser->m_iPreheatTimeSecs);
        } else if (pLaser->m_bError) {
            msg = QObject::tr("Laser is error, please contact manager");
        } else {
            bEnabled = true;
        }
    }
    if (false == bEnabled) {
        m_gSystem.m_SysMsg.SetMsg(msg, WARN_MSG_TYPE);
        return;
    }


    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Open Laser External Gate ON Sig"),
                          QVariantList()
                          << LASER_DRIVER << CLaserDriver_SP::SETGATESOURCE
                          << LASER << TRUE, 0);

    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Open Laser Inner Gate On Sig"),
                          QVariantList()
                          << LASER_DRIVER << CLaserDriver_SP::SETINNERGATE
                          << LASER << true, 0);

    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Open Laser Emission ON Sig"),
                          QVariantList()
                          << LASER_DRIVER << CLaserDriver::SETLDD
                          << LASERPATH_D_NARROW << TRUE, 0);

    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Init Laser finished Sig"),
                          QVariantList()
                          << LASER_DRIVER << CLaserDriver_SP::INITINISHED << LASER, 0);

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

void MainWindow::on_btnReplaceCoatLiquid_clicked()
{
    QMyMessageBox msgBoxAsk(QMessageBox::Question, tr("Confirm information"), tr("Are you sure to Replace coat fluid?"),
                            QMessageBox::Yes | QMessageBox::No);
    //msgBoxAsk.setStandardButtons();
    msgBoxAsk.setDefaultButton(QMessageBox::No);
    msgBoxAsk.setButtonText(QMessageBox::Yes, tr("Yes"));
    msgBoxAsk.setButtonText(QMessageBox::No, tr("No"));
    int ret = msgBoxAsk.exec();
    if (ret == QMessageBox::No) {
        return;
    }
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Coat_ReplaceFluid,
                          QObject::trUtf8("Replace coat fluid"));
    m_gSystem.start_manual(SM_COAT, msgqueue, true);
}

void MainWindow::on_btnBarCode_clicked()
{
    m_pDlgLotCode->show();
}

void MainWindow::on_btnSetCheck_clicked()
{
    //设置某一片自检
    //QMessageBox::information(this, "tittle", "Text", QMessageBox::StandardButton::YES);
}

void MainWindow::on_pushButton_LogRecord_clicked()
{
	ui->stackedWidget_main->MsetCurrentWidget(ui->page_logrecord);
	ui->stackedWidget_button->MsetCurrentWidget(ui->page_button_log);
	//ui->stackedWidget_main->MsetCurrentWidget(ui->page_record);
}

void MainWindow::on_cmbLogRecord_Changed(int)
{
	QString sText = ui->comboBox_logRecord->currentText();

	ui->treeWidget_logRecord->clear();
	ui->textBrowser_logRecord->clear();

	std::string running_path = _pgmptr;
	size_t found = running_path.rfind('\\');
	if (found != std::string::npos)
	{
		found = running_path.rfind('\\', found - 1);
		running_path = running_path.substr(0, found + 1);
		sText = running_path.c_str() + sText;
	}

	loadLogRecord(sText, ui->treeWidget_logRecord->invisibleRootItem());
}

void MainWindow::loadLogRecord(QString sText, QTreeWidgetItem *parentItem)
{
	QDir dir(sText);
	QStringList files = dir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
	foreach(QString fileName, files)
	{
		QTreeWidgetItem *item = new QTreeWidgetItem(parentItem); 
		item->setText(0, fileName); 
		QFileInfoList lst = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
		if (dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot).size())
		{ 
			item->setIcon(0, QIcon(CMakePath::make_bin_path("../theme/dir.ico")));
			loadLogRecord(dir.absoluteFilePath(fileName), item);
		}
		else
		{
			item->setIcon(0, QIcon(CMakePath::make_bin_path("../theme/data.ico")));
			item->setData(0, Qt::UserRole, dir.absoluteFilePath(fileName));
		}
	}
}

void MainWindow::on_treeItemDoubleClicked(QTreeWidgetItem *item, int column)
{
	QString sFilePath = item->data(0, Qt::UserRole).toString();
	if (!sFilePath.isEmpty())
	{
		ui->textBrowser_logRecord->clear();

		QFile file(sFilePath);
		if (file.open(QIODevice::ReadOnly | QIODevice::Text))
		{
			QTextStream in(&file);
			ui->textBrowser_logRecord->setText(in.readAll());
		}
		file.close();
	}
}