#include "cctrlparamlist.h"

#include <QLineEdit>
#include <QHeaderView>
#include <QFileDialog>
#include "cctrlbuttonidtable.h"
#include "cctrllineedit.h"
#include "cctrlcombo.h"
#include "cctrltablewidget.h"
//#include "logic_compdef.h"
//#include "logic.h"
#include "cctrlcombo.h"
#include "cmakepath.h"
#include <QTextStream>
#include "macro_def.h"
#include "csystem_external.h"
#include "cworker.h"
#include "logic_local_def.h"
#include "cmotordriver.h"
//#include "glog/logging.h"
CCtrlParamList::CCtrlParamList(QWidget *parent) : CMWidget(parent)
{
    m_pTable=new CCtrlTableWidget(this);
    m_pLayOut=new QGridLayout(this);
    m_pLayOut->addWidget(m_pTable);
    setLayout(m_pLayOut);
    memset(m_pVariant,0,M_Max_List_RowY);
    m_iRowCntY=0;
    m_iColoumCntX=0;
    connect(m_pTable,SIGNAL(currentCellChanged(int,int,int,int)),
            this,SLOT(ListCellChanged(int,int,int,int)));

    m_pTable->setEditTriggers(QTableWidget::NoEditTriggers);

    //   m_pTable->setAlternatingRowColors(true);
    m_bHasButton=false;
    m_iCurRow=0;
    m_iCurColumn=0;
    m_pLayOut->setSpacing(0);
    m_pLayOut->setContentsMargins(0,0,0,0);
}



void CCtrlParamList::MParamInit_list(Variant **pVariant, int32_t iRowY, int32_t *pID)
{
    if(pID)m_bHasButton=true;
    m_iRowCntY=iRowY;
    m_iColoumCntX=M_Max_List_ColoumX;
    m_pTable->setSortingEnabled(false);
    m_pTable->setColumnCount(m_iColoumCntX);
    m_pTable->setRowCount(m_iRowCntY);
    QStringList header;
    header<<QObject::trUtf8("name")<<QObject::trUtf8("data")<<QObject::trUtf8("unit");
    m_pTable->setHorizontalHeaderLabels(header);
    QHeaderView * headview= m_pTable->horizontalHeader();
    headview->setDefaultSectionSize(120);
    headview->setSectionResizeMode(1,QHeaderView::Interactive);
    headview->setSectionResizeMode(2,QHeaderView::Interactive);
    headview->setSectionResizeMode(0,QHeaderView::ResizeToContents);


    for(int j=0;j<iRowY;j++)
    {
        Q_ASSERT(pVariant[j]!=0);
        m_pVariant[j]=pVariant[j];
        QString s=pVariant[j]->m_sName;
        s.replace(QString("_"), QString(" "));
        QTableWidgetItem* pitem=new QTableWidgetItem(s+":");
        if(pID)
        {
            if(pID[j])
            {
                pitem->setData(Qt::UserRole,pID[j]|j<<24);
                pitem->setText(s+"("+ _SysExt_Instance.m_mapNameList[pID[j]&0xFFFF]+")"+":");
            }
        }
        pitem->setTextAlignment(Qt::AlignRight|Qt::AlignVCenter);

        m_pTable->setItem(j,0,pitem);

        pitem=new QTableWidgetItem();
        m_pTable->setItem(j,1,pitem);

        pitem->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);

        QString sUnit;
        sUnit=pVariant[j]->m_sUnit;
        pitem=new QTableWidgetItem(sUnit);
        m_pTable->setItem(j,2,pitem);
    }

}

void CCtrlParamList::MTimeFresh()
{

}

void CCtrlParamList::MFresh()
{
    m_pTable->setCurrentCell(-1,-1);
    //   MApplySelect(m_iCurColumn,m_iCurRow);
    //    m_pTable->removeCellWidget(m_iCurRow,m_iCurColumn);
    for(int j=0;j<m_iRowCntY;j++)
    {
        QTableWidgetItem* pitem=m_pTable->item(j,1);
        Q_ASSERT(pitem);
        Variant* pVariant=m_pVariant[j];
        QVariant& var=pVariant->m_vVar;
        pitem->setData(Qt::UserRole,var);
        if(var.type()!=QVariant::UInt)
        {
            if(var.type()==QVariant::Bool)
            {
                if(var.toBool())
                {
                    pitem->setText(QObject::trUtf8("yes"));
                }
                else
                {
                    pitem->setText(QObject::trUtf8("no"));
                }
            }
            else if(var.type()==QVariant::Double)
            {
                pitem->setText(QString::number(var.toDouble()));
            }
            else
            {
                pitem->setText(var.toString());
            }
        }
        else
        {
            if(pVariant->m_slRange.size())
            {
                pitem->setText(pVariant->m_slRange[var.toUInt()]);
            }
        }
    }
}

void CCtrlParamList::MApply()
{
    m_pTable->setCurrentCell(-1,-1);
    for(int j=0;j<m_iRowCntY;j++)
    {
        Variant* pVariant=m_pVariant[j];
        QTableWidgetItem* pitem=m_pTable->item(j,1);
        QVariant& var=pVariant->m_vVar;
        pVariant->m_sUnit = m_pTable->item(j, 2)->text();
        QVariant varNew = pitem->data(Qt::UserRole);
        if (var != varNew)
        {
            __LOGINSTANCE__.AddRecord(fmt::format("Param:{} ID:{} change from: {} to {}", pVariant->m_sName.toLocal8Bit().data(), pVariant->m_iID, var.toString().toLocal8Bit().data(), varNew.toString().toLocal8Bit().data()), "ParamChanged");
        }

        var.setValue(varNew);
    }
}

bool CCtrlParamList::ExportParas()
{
	QString strPath = QFileDialog::getSaveFileName(this, tr("Open File"), CMakePath::make_config_path(""), tr("CSV File (*.csv"));
	if (!strPath.isEmpty()) {
		QFile file(strPath);
		if(!file.open(QIODevice::ReadWrite))
		{
			//LOG(ERROR)<<ERR_TITTLE()<<(QObject::trUtf8("Open file failed")+  QObject::trUtf8("open path %1 failed").arg(strPath)).toStdString().c_str();
			return false;
		}
		QTextStream stream(&file);
		for(int i=0;i<m_iRowCntY;i++){
			if(m_pVariant[i] == nullptr)
				continue;
			QVariant& var = m_pVariant[i]->m_vVar;
			QString sValue = "";
			if(var.type()!=QVariant::UInt)
			{
				if(var.type()==QVariant::Bool)
				{
					if(var.toBool())
					{
						sValue = QObject::trUtf8("yes");
					}
					else
					{
						sValue = QObject::trUtf8("no");
					}
				}
				else if(var.type()==QVariant::Double)
				{
					sValue = QString::number(var.toDouble());
				}
				else
				{
					sValue = var.toString();
				}
			}


			stream<<m_pVariant[i]->m_iID<<","<<sValue<<","<<m_pVariant[i]->m_sName<<endl;
		}
	}
	return true;
}

void CCtrlParamList::ListCellChanged(int currentRow, int currentColumn,
                                     int previousRow, int previousColumn)
{
    if(previousColumn==1)
    {
        QWidget *pWidgetPre=m_pTable->cellWidget(previousRow,previousColumn);
        if(pWidgetPre)
        {
            bool bSetRed=false;
            QTableWidgetItem* pitemPre=m_pTable->item(previousRow, previousColumn);
            QVariant var=pitemPre->data(Qt::UserRole);
            QVariant::Type type=var.type();
            if(type!=QVariant::UInt&&
                    type!=QVariant::Bool)
            {
                CCtrlLineEdit* pLineEdit=(CCtrlLineEdit*)pWidgetPre;
                QString text=pLineEdit->text();
                bSetRed=pLineEdit->m_bSetRed;
                pitemPre->setText(text);

                switch (var.type()) {
                case QVariant::Int:
                    var=text.toInt();
                    break;
                case QVariant::Double:
                    var=text.toDouble();
                    break;
                case QVariant::String:
                    var=text;
                    break;
                default:
                    Q_ASSERT(0);
                    break;
                }
            }
            else if(type==QVariant::Bool)
            {
                CCtrlCombo* pCombo=(CCtrlCombo*)pWidgetPre;
                QString text=pCombo->currentText();
                pitemPre->setText(text);
                var=pCombo->currentIndex()?true:false;
            }
            else
            {
                CCtrlCombo* pCombo=(CCtrlCombo*)pWidgetPre;
                QString text=pCombo->currentText();
                pitemPre->setText(text);
                var=uint(pCombo->currentIndex());
            }
            pitemPre->setData(Qt::UserRole,var);

            if(bSetRed)
            {
                pitemPre->setBackgroundColor(Qt::red);
            }
            else
            {
                pitemPre->setBackgroundColor(Qt::transparent);
            }
        }

    }

    bool bFactory = false;
    CWorker* pWorker = GET_CHDIRECT(M_WORKER, CWorker);
    if (pWorker->m_workLevel >= LEVEL_FACTORAY)
    {
        bFactory = true;
    }

    if (previousColumn == 2)
    {
        QWidget* pWidgetPre = m_pTable->cellWidget(previousRow, previousColumn);
        if (pWidgetPre)
        {
            bool bSetRed = false;
            QTableWidgetItem* pitemPre = m_pTable->item(previousRow, previousColumn);
            CCtrlLineEdit* pLineEdit = (CCtrlLineEdit*)pWidgetPre;

            QString text = pLineEdit->text();
            bSetRed = pLineEdit->m_bSetRed;
            pitemPre->setText(text);
        }
    }
    m_pTable->removeCellWidget(previousRow, previousColumn);

    if(currentColumn==1&&!m_bReadOnly)
    {
        QTableWidgetItem* pitemCur=m_pTable->item(currentRow, currentColumn);
        QVariant var=pitemCur->data(Qt::UserRole);
        QVariant::Type type=var.type();
        if(!m_pVariant[currentRow]->m_bReadOnly)
        {
            if(type==QVariant::Double||
                    type==QVariant::Int)
            {
                int iSize=m_pVariant[currentRow]->m_slRange.size();
                if(iSize>=2)
                {
                    switch(type)
                    {
                    case QVariant::Double:
                    {
                        CCtrlLineEdit* pLineEdit=new CCtrlLineEdit(pitemCur->text(),m_pTable);
                        pLineEdit->SetRange(m_pVariant[currentRow]->m_slRange.at(0).toDouble(),
                                            m_pVariant[currentRow]->m_slRange.at(1).toDouble(),
                                            true);
                        m_pTable->setCellWidget(currentRow, currentColumn,pLineEdit);
                        break;
                    }
                    case QVariant::Int:
                    {
                        CCtrlLineEdit* pLineEdit=new CCtrlLineEdit(pitemCur->text(),m_pTable);
                        pLineEdit->SetRange(m_pVariant[currentRow]->m_slRange.at(0).toDouble(),
                                            m_pVariant[currentRow]->m_slRange.at(1).toDouble(),
                                            false);
                        m_pTable->setCellWidget(currentRow, currentColumn,pLineEdit);
                        break;
                    }
                    }
                }
            }
            else if(type==QVariant::String)
            {
                CCtrlLineEdit* pLineEdit=new CCtrlLineEdit(pitemCur->text(),m_pTable);
                m_pTable->setCellWidget(currentRow, currentColumn,pLineEdit);
            }
            else if(type==QVariant::Bool)
            {
                CCtrlCombo* pCombo=new CCtrlCombo(this);
                pCombo->addItems(QStringList()<<QObject::trUtf8("no")<<QObject::trUtf8("yes"));
                pCombo->setCurrentIndex(var.toBool()?1:0);
                m_pTable->setCellWidget(currentRow, currentColumn,pCombo);
            }
            else
            {
                CCtrlCombo* pCombo=new CCtrlCombo(this);

                pCombo->addItems(m_pVariant[currentRow]->m_slRange);
                pCombo->setCurrentIndex(var.toUInt());
                m_pTable->setCellWidget(currentRow, currentColumn,pCombo);
            }
        }
    }
    if(currentColumn==0&&m_bHasButton==true)
    {
        QTableWidgetItem* pItem=m_pTable->item(currentRow,currentColumn);
        int idata=pItem->data(Qt::UserRole).toDouble();
        if(idata&0x00FFFFFF)
        {
            CCtrlButtonIDTable* pButton=new CCtrlButtonIDTable(this,idata);
            pButton->setText(pItem->text());
            connect(pButton,
                    SIGNAL(MClick_Signal(int32_t)),
                    this,
                    SLOT(ListNameClicked_Slot(int32_t)));
            m_pTable->setCellWidget(currentRow,currentColumn,pButton);
        }
    }
    if (currentColumn == 2 && bFactory)
    {
        QTableWidgetItem* pitemCur = m_pTable->item(currentRow, currentColumn);
        QVariant var = pitemCur->data(Qt::UserRole);
        CCtrlLineEdit* pLineEdit = new CCtrlLineEdit(pitemCur->text(), m_pTable);
        pLineEdit->m_bNumOnly = false;
        pLineEdit->SetRange(-100000, 10000, true);
        m_pTable->setCellWidget(currentRow, currentColumn, pLineEdit);
    }
}


//void CCtrlParamList::ListCellChanged(int currentRow, int currentColumn,
//                                     int previousRow, int previousColumn)
//{
//    MApplySelect(previousColumn,previousRow);
//    MFreshSelectItem(currentColumn, currentRow);
//    m_iCurColumn=currentColumn;
//    m_iCurRow=currentRow;
//}


void CCtrlParamList::ListNameClicked_Slot(int32_t iID)
{
    double data=m_pTable->item(iID>>24,1)->text()
            .toDouble();

    V_MsgQueue msgqueue;
    if(((iID>>16)&0xFF)==CMotorDriver::ABSMOVE_TYPE)
    {
        _SysExt_Instance.absmove_msg(data,iID&0xFFFF,msgqueue);
        _SysExt_Instance.start_test(SM_MAIN, msgqueue,false);
    }
    else if(((iID>>16)&0xFF)==CMotorDriver::RELMOVE_TYPE)
    {
        _SysExt_Instance.relmove_msg(data,iID&0xFFFF,msgqueue);
        _SysExt_Instance.start_test(SM_MAIN, msgqueue,false);
    }
    //    emit ListNameClicked_Singal(iID);
}

//void CCtrlParamList::MApplyAllSelect()
//{
//    for(int j=0;j<m_iRowCntY;j++)
//    {
//        MApplySelect(1,j);
//    }
//}

//void CCtrlParamList::MFreshSelectItem(int32_t iColoumX, int32_t iRowY)
//{
//    if(!(iRowY>=0&&iRowY<m_iRowCntY)) return;
//    if(iColoumX==1)
//    {
//        Variant* pParam=m_pVariant[ iRowY ];
//        switch(pParam->m_estyle&0xF)
//        {
//        case Variant::PFLOAT:
//        case Variant::PINT:
//        {
//            CCtrlLineEdit* pLineEdit=new CCtrlLineEdit();
//            pLineEdit->setText(m_pTable->item(iRowY,iColoumX)->text());
//            m_pTable->setCellWidget(iRowY,iColoumX,pLineEdit);
//        }
//            break;
//        case Variant::PINDEX:
//        {
//            CCtrlCombo* pComboBox=new CCtrlCombo( ) ;
//            pComboBox->setCurrentText(m_pTable->item(iRowY,iColoumX)->text());

//            QStringList list;
//            pParam->GetParamIndexString( list);
//            pComboBox->addItems(list);
//            pComboBox->setCurrentText(m_pTable->item(iRowY,iColoumX)->text());
//            m_pTable->setCellWidget(iRowY,iColoumX,pComboBox);

//        }
//            break;
//        default:break;
//        }
//    }
//    else if(iColoumX==0&&m_bHasButton==true)
//    {
//        QTableWidgetItem* pItem=m_pTable->item(iRowY,iColoumX);
//        int idata=pItem->data(Qt::UserRole).toDouble();
//        if(idata&0x00FFFFFF)
//        {
//            CCtrlButtonID* pButton=new CCtrlButtonID(this,idata);
//            pButton->setText(pItem->text());
//            connect(pButton,
//                    SIGNAL(MClick_Signal(int32_t)),
//                    this,
//                    SLOT(ListNameClicked_Slot(int32_t)));
//            m_pTable->setCellWidget(iRowY,iColoumX,pButton);
//        }
//    }
//}

//void CCtrlParamList::MApplySelect(int32_t iColoumX, int32_t iRowY)
//{
//    if(!(iRowY>=0&&iRowY<m_iRowCntY)) return;
//    if(iColoumX==1)
//    {

//        QWidget * pwidget=m_pTable->cellWidget(iRowY,iColoumX);
//        if(!pwidget) return;
//        Variant* pParam=m_pVariant[iRowY];
//        switch(pParam->m_estyle&0xF)
//        {
//        case Variant::PFLOAT:
//        case Variant::PINT:
//        {
//            CCtrlLineEdit* pLineEdit=(CCtrlLineEdit*)pwidget;
//            QTableWidgetItem* pitem=new QTableWidgetItem(pLineEdit->text());
//            m_pTable->setItem(iRowY,iColoumX,pitem);
//        }
//            break;
//        case Variant::PINDEX:
//        {
//            CCtrlCombo* pComboBox=(CCtrlCombo*)pwidget;
//            QTableWidgetItem* pitem=new QTableWidgetItem(pComboBox->currentText());
//            m_pTable->setItem(iRowY,iColoumX,pitem);

//        }
//            break;
//        default:break;
//        }
//    }
//    m_pTable->removeCellWidget(iRowY,iColoumX);
//}
