#include "cmwcalilaserbeam.h"
#include "ui_cmwcalilaserbeam.h"
#include "common_include.h"
#include "cpowermeterdriver_lp.h"
#include "cctrlgraph.h"
#ifdef __USE_LASER_BAEM__POWER__
static bool m_bfreshPower = false;
CMWCaliLaserBeam::CMWCaliLaserBeam(QWidget* parent, int iLaserPathID) :
    CMWidget(parent),
    ui(new Ui::CMWCaliLaserBeam)
{
    ui->setupUi(this);
    m_iLaserPathID = iLaserPathID;

	m_pLaserPowercali = GET_PROCESS(PROCESS_POWERCALI_D_WIDE,
		SM_MAIN,
		CProcess_LaserPowerCali);
    Q_ASSERT(m_pLaserPowercali);
    m_iTimerInterval = 200;
}

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

void CMWCaliLaserBeam::MInit()
{
    Q_ASSERT(m_pLaserPowercali);
    Variant* pparam[20] = { 0 };
    int iID[20] = { 0 };

    pparam[0] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_XPos);
    pparam[1] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_YPos);
    pparam[2] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_ZPos);
    pparam[3] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_Step);
    pparam[4] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_MeasTime);
    pparam[5] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_StableTime);
    pparam[6] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_StableThres);
    pparam[7] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_PowerChekDate);
    pparam[8] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_PowerCheck_Thres);
    pparam[9] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_LaserPowerCali_PowerCheck_ThresPercent);

    pparam[10] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_PowerCheckType);
    pparam[11] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_PowerCheckTimeInterval);
    pparam[12] = m_pLaserPowercali->m_Variants.get_Variant(Var_Process_PowerCheckFreq);

    CLaserPath* pLaserPath = GET_CHDIRECT(LASERPATH_D_NARROW, CLaserPath);
    pparam[13] = pLaserPath->m_Variants.get_Variant(Var_LaserPath_UseFixPowerSetting);
    pparam[14] = pLaserPath->m_Variants.get_Variant(Var_LaserPath_PowerSet);

    pparam[15] = pLaserPath->m_Variants.get_Variant(Var_LaserPath_AdjsutRate);

    iID[0] = MOTORX | (CMotorDriver::ABSMOVE_TYPE << 16);
    iID[1] = MOTORY | (CMotorDriver::ABSMOVE_TYPE << 16);
    iID[2] = MOTORZ | (CMotorDriver::ABSMOVE_TYPE << 16);

    ui->widget->MParamInit_list(pparam, 16, iID);


    mchildwidgets[(uintptr_t)ui->widget] = ui->widget;
    ui->label_Name->setText(_SysExt_Instance.m_mapNameList[m_iLaserPathID]);


    ui->widget_Coord->m_sName = QObject::trUtf8("Beam Chart");
    ui->widget_Coord_Cur->m_sName = QObject::trUtf8("Cur Beam Chart");

    ui->widget_Coord_Cur->MInit();
    ui->widget_Coord->MInit();

    CMWidget::MInit();
}
void CMWCaliLaserBeam::MTimeFresh()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Beam fresh Sig"),
                          QVariantList()
                          << POWERMETERDRIVER
                          << CPowerMeterDriver::FRESHRESULT
                          << POWERMETERHEAD, 0);
    _SysExt_Instance.start_test(SM_MAIN, msgqueue, false);

    CPowerMeter* pPowerMeter = GET_CHDIRECT(POWERMETERHEAD,
                                            CPowerMeter);
    double dPower = pPowerMeter->m_Variants
        .get_VData(Var_PowerMeter_MeasResult_ID)
        ->toDouble();

    ui->label_Power->setText(QString::number(dPower, 'f', 3));

    MFreshCurBeamCaliParam();

    ui->widget_Coord_Cur->MTimeFresh();
    ui->widget_Coord->MTimeFresh();

    CMWidget::MTimeFresh();
}

void CMWCaliLaserBeam::MFresh()
{
    if(m_iLaserPathID == LASERPATH_D_WIDE) {
        MFreshCombo();
    }
    MFreshBeamCaliParam();
    CMWidget::MFresh();

    ui->pushButton_CaliPChange->setVisible(false);
    /*ui->comboBox_SINDEX->setVisible(false);
    ui->label_4->setVisible(false);
    ui->label_7->setVisible(false);*/

    //ui->label_Epulse->setVisible(false);
    //ui->comboBox_Epulse->setVisible(false);
    //ui->label_EpulseKHz->setVisible(false);
    if (m_iLaserPathID == LASERPATH_D_NARROW)
    {
        ui->label_4->setVisible(false);
        ui->comboBox_SINDEX->setVisible(false);
        ui->label_7->setVisible(false);
    }
}

void CMWCaliLaserBeam::calipower_msg(int iFreq, int iEpulse, double dBeamWidth,
                                      V_MsgQueue& msgqueue)
{
    msgqueue.pushback_Msg(VarMsg_PowerCali_PowerRange_ID,
                          QObject::trUtf8("Cali Beam Range Sig"),
                          QVariantList()
                          << m_pLaserPowercali->m_iID
                          << (int)iFreq << iEpulse << dBeamWidth, 0);
}

void CMWCaliLaserBeam::calibeampower_msg(int iFreq, int iEpulse, double dBeamWidth, double dAngle, V_MsgQueue &msgqueue)
{
	msgqueue.pushback_Msg(VarMsg_PowerCali_BeamRange_ID,
		QObject::trUtf8("Cali Beam Range Sig"),
		QVariantList()
		<< m_pLaserPowercali->m_iID
		<< (int)iFreq << iEpulse << dBeamWidth << dAngle, 0);
}

void CMWCaliLaserBeam::MFreshCombo()
{
    CLaserPath* pLaserPath = GET_CHDIRECT(m_iLaserPathID, CLaserPath);
    Q_ASSERT(pLaserPath);
    ui->comboBox_SINDEX->clear();
    LPATHBEAMPOSMAP::iterator ii = pLaserPath->m_mBeamPos.begin();
    for (; ii != pLaserPath->m_mBeamPos.end(); ii++)
    {
        double sindex = ii.key() / 1000.0;
        ui->comboBox_SINDEX->addItem
        (QString::number(sindex, 'f', 3), sindex);
    }
    return;


    if(m_iLaserPathID == LASERPATH_D_WIDE) {
#ifdef __USE_MOTOR_PATH__
        CLaserPath* pLaserPath = GET_CHDIRECT(m_iLaserPathID, CLaserPath);
        Q_ASSERT(pLaserPath);
        ui->comboBox_SINDEX->clear();
        LPATHBEAMPOSMAP::iterator ii = pLaserPath->m_mBeamPos.begin();
        for(; ii != pLaserPath->m_mBeamPos.end(); ii++) {
            double sindex = ii.key() / 1000.0;
            ui->comboBox_SINDEX->addItem
            (QString::number(sindex, 'f', 3), sindex);
        }
#endif
    } else {
        ui->comboBox_SINDEX->setEnabled(true);
        
        CLaserPath* pLaserPath = GET_CHDIRECT(m_iLaserPathID, CLaserPath);
        Q_ASSERT(pLaserPath);
        ui->comboBox_SINDEX->clear();
        auto ii = pLaserPath->m_vDIndexParam.begin();
        for(; ii != pLaserPath->m_vDIndexParam.end(); ii++) {
            double sindex = (*ii).first / 1000.0;
            ui->comboBox_SINDEX->addItem
            (QString::number(sindex, 'f', 3), sindex);
        }
        //ui->comboBox_SINDEX->setEnabled(false);
    }
}


void CMWCaliLaserBeam::on_pushButton_CaliPos_clicked()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Process_ID,
                          QObject::trUtf8("Move Beam Cali Pos Sig"),
                          QVariantList()
                          << m_pLaserPowercali->m_iID
                          << CProcess_LaserPowerCali::MOVECALIPOS, 0);
    _SysExt_Instance.start_test(SM_MAIN, msgqueue, false);
}

void CMWCaliLaserBeam::on_pushButton_CaliStart_clicked()
{
    SetCoord45();
    int iFreq = ui->comboBox_Freq->currentText().toInt();
    int iEpulse = ui->comboBox_Epulse->currentText().toInt();
    double dBeamWidth = ui->comboBox_SINDEX->currentText().toDouble();


	if (iFreq > iEpulse) {
        _SysExt_Instance.m_SysMsg.SetMsg(QObject::tr("Epulse need lower Freq"), WARN_MSG_TYPE);
		return;
	}

    V_MsgQueue msgqueue;
    calipower_msg(iFreq, iEpulse, dBeamWidth, msgqueue);
    _SysExt_Instance.start_test(SM_MAIN, msgqueue);
}


void CMWCaliLaserBeam::on_pushButton_CaliAllStart_clicked()
{
    //更新Epulse相关功率测量
    SetCoord45();

    int isizeFreq = ui->comboBox_Freq->count();
    int isizeSIndex = ui->comboBox_SINDEX->count();
    int iEpulse = ui->comboBox_Epulse->currentText().toInt();
    V_MsgQueue msgqueue;
    
    for(int i = 0; i < isizeFreq; i++) {
        int iFreq = ui->comboBox_Freq->itemText(i).toInt();
        if(iFreq > iEpulse) {
            continue;
        }
        if(m_iLaserPathID == LASERPATH_D_WIDE) {
            for(int j = 0; j < isizeSIndex; j++) {
                double dBeamWidth = ui->comboBox_SINDEX->itemText(j).toDouble();
                calipower_msg(iFreq, iEpulse, dBeamWidth, msgqueue);
            }
        } else {
            calipower_msg(iFreq, iEpulse, 0, msgqueue);
        }
    }
    _SysExt_Instance.start_test(SM_MAIN, msgqueue);

}

void CMWCaliLaserBeam::on_pushButton_CaliStop_clicked()
{
    _Sys_Instance_.FindSM(SM_MAIN)->pushfront_Msg(VarMsg_Stop_ID,
                                             QObject::trUtf8("Stop Cali Beam"));

}


void CMWCaliLaserBeam::on_pushButton_CaliPChange_clicked()
{
    SetCoord90();
    double dFreq = ui->comboBox_Freq->currentText().toDouble();
    double dSIndex = ui->comboBox_SINDEX->currentText().toDouble();

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_PowerCali_PowerPChange_ID,
                          QObject::trUtf8("Cali PChange Sig"),
                          QVariantList()
                          << m_pLaserPowercali->m_iID
                          << (int)dFreq << dSIndex, 0);
    _SysExt_Instance.start_test(SM_MAIN, msgqueue);
}

void CMWCaliLaserBeam::on_pushButton_CaliMaxPower_clicked()
{
    SetCoord90();
    double dFreq = ui->comboBox_Freq->currentText().toDouble();
    double dSIndex = ui->comboBox_SINDEX->currentText().toDouble();

    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_PowerCali_PowerMax_ID,
                          QObject::trUtf8("Cali Max Beam Sig"),
                          QVariantList()
                          << m_pLaserPowercali->m_iID
                          << (int)dFreq << dSIndex, 0);
    _SysExt_Instance.start_test(SM_MAIN, msgqueue);
}

#ifdef __USE_LASER_BAEM__POWER__
void CMWCaliLaserBeam::MFreshCurBeamCaliParam()
{
    CLaserPath* pLaserPath = GET_CHDIRECT(m_iLaserPathID, CLaserPath);
	QVector<DBafflePowerRate> vScaleParam = pLaserPath->m_vScaleParam;
    int iSize = vScaleParam.size();
    ui->widget_Coord_Cur->m_ptVector.resize(iSize);

	double dPowerMaxAngle = 100;
	dPowerMaxAngle += 45;
	ui->widget_Coord->SetStartXY(dPowerMaxAngle, 0);
	ui->widget_Coord_Cur->SetStartXY(dPowerMaxAngle, 0);

    for(int i = 0; i < iSize; i++) {
        ui->widget_Coord_Cur->m_ptVector[i].tY = vScaleParam[i].dCurPower;
        ui->widget_Coord_Cur->m_ptVector[i].tX = (vScaleParam[i].dPowerRate - dPowerMaxAngle);
    }
    QString str = QObject::trUtf8("scale:%1Hz\nSIndex:%2mm\n")
        .arg(m_pLaserPowercali->m_iCurFreq)
        .arg(m_pLaserPowercali->m_dCurWidth);
    ui->widget_Coord_Cur->SetString(str);
    ui->widget_Coord_Cur->refreshPixmap();

}

void CMWCaliLaserBeam::MFreshBeamCaliParam()
{
    double dFreq = ui->comboBox_Freq->currentText().toDouble();
    double dSIndex = ui->comboBox_SINDEX->currentText().toDouble();
    int iEpulse = ui->comboBox_Epulse->currentText().toInt();

    CLaserPath* pLaserPath = GET_CHDIRECT(m_iLaserPathID, CLaserPath);
	double dPowerMaxAngle = 100;
	dPowerMaxAngle += 45;

	BEAMPOSVECTOR ptVector;
    bool b = pLaserPath->FindBeamPosVector(dFreq, iEpulse, dSIndex, ptVector);
    if(b) {
        int iSize = ptVector.size();
        ui->widget_Coord->m_ptVector.resize(iSize);
        for(int i = 0; i < iSize; i++) {
            ui->widget_Coord->m_ptVector[i].tY = ptVector[i].dCurPower;
            ui->widget_Coord->m_ptVector[i].tX = ptVector[i].dPowerRate - dPowerMaxAngle;
        }
        QString str = QObject::trUtf8("scale:%1Hz\nSIndex:%2mm\n")
            .arg(dFreq).arg(dSIndex);
        ui->widget_Coord->SetString(str);
        ui->widget_Coord->refreshPixmap();
    } else {
        ui->widget_Coord->m_ptVector.resize(0);
    }
}
#endif
void CMWCaliLaserBeam::SetCoord45()
{
    ui->widget_Coord_Cur->m_iZeroPos = CCtrlGraph::LEFT_BOTTOM;
    ui->widget_Coord_Cur->m_dRangeYMax = 15;
    ui->widget_Coord_Cur->init_rectWindow();
}

void CMWCaliLaserBeam::SetCoord90()
{
    ui->widget_Coord_Cur->m_iZeroPos = CCtrlGraphOpenGL::LEFT_CENTER;
    ui->widget_Coord_Cur->m_dRangeYMax = 15;
    ui->widget_Coord_Cur->init_rectWindow();
}

void CMWCaliLaserBeam::on_comboBox_Freq_currentIndexChanged(const QString& arg1)
{
    UNUSED(arg1);
#ifdef __USE_LASER_BAEM__POWER__
    MFreshBeamCaliParam();
#endif
}

void CMWCaliLaserBeam::on_comboBox_SINDEX_currentIndexChanged(const QString& arg1)
{
    UNUSED(arg1);
#ifdef __USE_LASER_BAEM__POWER__
    MFreshBeamCaliParam();
#endif
}

void CMWCaliLaserBeam::on_comboBox_Epulse_currentIndexChanged(const QString& arg1)
{
#ifdef __USE_LASER_BAEM__POWER__
    MFreshBeamCaliParam();
#endif
}

void CMWCaliLaserBeam::on_pushButton_Test_clicked(bool checked)
{
    V_MsgQueue msgqueue;
    if(checked) {
        int iFreq = ui->comboBox_Freq->currentText().toDouble();
        double dWidth = ui->comboBox_SINDEX->currentText().toDouble();
        double dPower = ui->lineEdit_TestPower->text().toDouble();
        int iEpulse = ui->comboBox_Epulse->currentText().toInt();
        msgqueue.pushback_Msg(VarMsg_Process_ID,
                              QObject::trUtf8("Move Beam Cali Pos Sig"),
                              QVariantList()
                              << m_pLaserPowercali->m_iID
                              << CProcess_LaserPowerCali::MOVECALIPOS, 0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("Move Path Angle"),
                              QVariantList()
                              << LASERPATH_DRIVER
                              << CLaserPathDriver::MOVEPATHANGLE
                              << m_iLaserPathID
                              << iEpulse << dWidth << iFreq << dPower, 0);

        //msgqueue.pushback_Msg(VarMsg_Driver_ID,
        //                      QObject::trUtf8("Set Gate Source"),
        //                      QVariantList()
        //                      <<LASER_DRIVER
        //                      <<CLaserDriver::SETGATESOURCE
        //                      <<LASER <<true,0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("Open Laser Gate"),
                              QVariantList()
                              << LASER_DRIVER
                              << CLaserDriver::OPENLASERGATE
                              << m_iLaserPathID << true, 0);

		msgqueue.pushback_Msg(VarMsg_Process_ID,
			QObject::trUtf8("OPEN_LENS_BLOW Gate"),
			QVariantList()
			<< m_pLaserPowercali->m_iID
			<< CProcess_LaserPowerCali::OPEN_LENS_BLOW
			<< FALSE, 0);

		
    } else {

        //        msgqueue.pushback_Msg(VarMsg_Driver_ID,
        //                              QObject::trUtf8("Set Gate Source"),
        //                              QVariantList()
        //                              <<LASER_DRIVER
        //                              <<CLaserDriver::SETGATESOURCE
        //                              <<LASER <<false,0);

        msgqueue.pushback_Msg(VarMsg_Driver_ID,
                              QObject::trUtf8("Close Laser Gate"),
                              QVariantList() << LASER_DRIVER
                              << CLaserDriver::OPENLASERGATE
                              << m_iLaserPathID << false, 0);
    }
    _SysExt_Instance.start_test(SM_MAIN, msgqueue);
}

void CMWCaliLaserBeam::on_btnPowerMeterZero_clicked()
{
    V_MsgQueue msgqueue;
    msgqueue.pushback_Msg(VarMsg_Driver_ID,
                          QObject::trUtf8("Set beam meter ZERO"),
                          QVariantList()
                          << POWERMETERDRIVER
                          << CPowerMeterDriver_lp::ZERO_POWERMETER
                          << POWERMETERHEAD, 0);
    _SysExt_Instance.start_manual(SM_MAIN, msgqueue);
}

void CMWCaliLaserBeam::on_btnExport_clicked()
{
    //导出功率计量


}

void CMWCaliLaserBeam::on_pushButton_CaliBeamStart_clicked()
{
	SetCoord45();
	int iFreq = ui->comboBox_Freq->currentText().toInt();
	int iEpulse = ui->comboBox_Epulse->currentText().toInt();
	double dBeamWidth = ui->comboBox_SINDEX->currentText().toDouble();
	double dAngle = ui->lineEdit_AngleG2->text().toDouble();

	if (iFreq > iEpulse)
	{
		_SysExt_Instance.m_SysMsg.SetMsg(QObject::tr("Epulse need lower Freq"), WARN_MSG_TYPE);
		return;
	}

	V_MsgQueue msgqueue;
	calibeampower_msg(iFreq, iEpulse, dBeamWidth, dAngle, msgqueue);
	_SysExt_Instance.start_test(SM_MAIN, msgqueue);
}
#endif