#include "mainForm.h"
#include "QsLog.h"
#include "ui_mainForm.h"
#include "preDefine.h"
#include "Control/flowControl.h"
#include "QsLog.h"
#include <QScrollBar>
#include "DTools/util.h"
#include <QList>
#include <QMap>
#include <QProcess>
#include <QThread>

extern QThread  workThread;

MainForm::MainForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainForm)
{
    ui->setupUi(this);

    // 初始化成员变量
    m_prevBtn = nullptr;
    m_prevTable = nullptr;
    m_tableList.append(ui->mainTableNew);
    m_tableList.append(ui->mainTableMake);
    m_tableList.append(ui->mainTableSend);
    m_tableList.append(ui->mainTableUnusual);
    m_tableList.append(ui->mainTableFinsh);
    m_tableList.append(ui->mainTableReserve);

    // 注册信号槽参数
    qRegisterMetaType<AlertForm::Type>("AlertForm::Type");
    qRegisterMetaType<dishesObject>("dishesObject");
    qRegisterMetaType< QMap< QString, QMultiMap<QString, dishesObject> > >("QMap<QString, QMultiMap<QString, dishesObject>>");
    qRegisterMetaType< QMap<QString, int> >("QMap<QString, int>");
    qRegisterMetaType< QMap<QString, QString> >("QMap<QString, QString>");

    // 连接信号槽
    connect(&m_timeTimer, &QTimer::timeout, this, &MainForm::onSetCurrentTime);
    connect(this, &MainForm::processOrder, &FlowControl::GetInstance(), &FlowControl::onProcessOrder);
    connect(this, &MainForm::getOrderDetails, &FlowControl::GetInstance(), &FlowControl::onGetOrderDetails);
    connect(this, &MainForm::getEcMopOrderDetails, &FlowControl::GetInstance(), &FlowControl::onGetEcMopOrderDetails);
    connect(this, &MainForm::PullDishes, &FlowControl::GetInstance(), &FlowControl::onPullDishes);
    connect(this, &MainForm::GetBusinessStatus, &FlowControl::GetInstance(), &FlowControl::onGetBusinessStatus);
    connect(this, &MainForm::GetOMSAllOrders, &FlowControl::GetInstance(), &FlowControl::onGetOMSAllOrders);
    connect(this, &MainForm::getDayReport, &FlowControl::GetInstance(), &FlowControl::onDailyReport);
    connect(this, &MainForm::sendSelfCheck, &FlowControl::GetInstance(), &FlowControl::onSendSelfCheck);
    connect(&FlowControl::GetInstance(), &FlowControl::showDailyReportData, this, &MainForm::onSetDailyReportData);
    connect(&FlowControl::GetInstance(), &FlowControl::hideAlert, this, &MainForm::onHideAlert,Qt::QueuedConnection);
    //转移到Main.cpp中进行绑定;
    //connect(&FlowControl::GetInstance(), &FlowControl::showAlert, this, &MainForm::onShowAlert,Qt::QueuedConnection);
    //connect(&FlowControl::GetInstance(), &FlowControl::setStoreInfo, this, &MainForm::onSetStoreInfo,Qt::QueuedConnection);
    //connect(&FlowControl::GetInstance(), &FlowControl::setCashierInfo, this, &MainForm::onSetCashierInfo,Qt::QueuedConnection);
    connect(&FlowControl::GetInstance(), &FlowControl::setOpeStatus, this, &MainForm::onSetOpeStatus,Qt::QueuedConnection);
    connect(&FlowControl::GetInstance(), &FlowControl::setNetStatus, this, &MainForm::onSetNetStatus,Qt::QueuedConnection);
    connect(&FlowControl::GetInstance(), &FlowControl::changeOrderStatus, this, &MainForm::onChangeOrderStatus,Qt::QueuedConnection);
    connect(&FlowControl::GetInstance(), &FlowControl::showOrderDetails, this, &MainForm::onShowOrderDetails);
    connect(&FlowControl::GetInstance(), &FlowControl::clearorder, this, &MainForm::onOrderClear);
    // 搜索订单的信号槽
    connect(ui->mainEdtSearch, &ClickedLineEdit::textChanged, &FlowControl::GetInstance(), &FlowControl::onSerachOrder);
    connect(&FlowControl::GetInstance(), &FlowControl::showSearchOrderResult, this, &MainForm::onShowSearchOrderResult);

    // 初始化界面
    _Init();

    // 开启时间定时器
    m_raiseIndex = 0;
    m_timeTimer.start(1000);
}

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

void MainForm::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons()==Qt::LeftButton) && m_bMousePress)
    {
        QPoint moveAmount = event->globalPos() - m_lastMousePos;
        m_absMove += moveAmount;
        move(pos() + moveAmount);
        m_lastMousePos = event->globalPos();
        m_bMouseMove = true;
    }
}

void MainForm::mousePressEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton) {
        m_bMousePress = true;
        m_lastMousePos = event->globalPos();
        m_absMove = QPoint(0,0);
    }
    /*
    if(event->button()==Qt::RightButton) {
        sInfoThread.terminate();
        workThread.terminate();
        qApp->exit(-1);
        QProcess::startDetached(qApp->applicationFilePath(), QStringList(qApp->applicationFilePath()));
    }
    */
}

void MainForm::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton)
    {
        m_bMousePress = false;
    }
    m_bMouseMove = false;
    int x = m_absMove.x();
    int y = m_absMove.y();
    int form_width_x = this->width();
    int from_height_y = this->height();

    QPoint point = this->pos();
    QLOG_INFO()<<QString("MainForm current Position(x:%1,y:%2) absMove: m_x=%3,m_y=%4").arg( point.x() ).arg( point.y() ).arg(x).arg(y);
    int nWidth = GetSystemMetrics(SM_CXSCREEN);
    int nHeight = GetSystemMetrics(SM_CYSCREEN);
    QLOG_INFO()<<QString::fromLocal8Bit("MainForm active_Range(x: 0~%1,y: 0~%2)").arg( nWidth - form_width_x ).arg( nHeight -from_height_y );

    if( (point.x() + form_width_x/3) < 0 || (point.x() + form_width_x) > (nWidth - 40)
            || (point.y() + from_height_y/3) < 0 || (point.y() + from_height_y) > (nHeight - 60) ) {
        int reset_x = point.x() - x;
        int reset_y = point.y() - y;
        QLOG_INFO()<<QString::fromLocal8Bit("MainForm OutRange, Reset Position Before Move (x:%1,y:%2)").arg( reset_x ).arg( reset_y );
        this->move( QPoint( reset_x, reset_y ) );
    } else {
        // this->move( QPoint( point.x()+x, point.y()+y ) ); // No Need Move, mouseMoveEvent Trigger Move;
    }
}


void MainForm::MyShow()
{
#ifdef QT_DEBUG
    this->show();
#else
    this->show();
    //this->showFullScreen();
#endif

    // 考虑到坐标问题放到这里构建
    m_alertForm = new AlertForm(this);
    // m_noticeForm = new NoticeForm(this);
    m_settingForm = new SettingForm(this);
    m_detailForm = new DetailForm(this);
    m_padForm = new PadForm(this);

    m_padForm->move(pos().x()+width()-300, pos().y()+height()-438);
    m_padForm->hide();
    connect(m_padForm, &PadForm::numClicked, this, &MainForm::onNumClicked);
    connect(m_padForm, &PadForm::numDelete, this, &MainForm::onNumDelete);
    connect(m_padForm, &PadForm::numClear, ui->mainEdtSearch, &ClickedLineEdit::clear);
    connect(m_padForm, &PadForm::getEcMopOrder, this, &MainForm::onDisplayEcMopOrder);

    m_resultForm = new QListWidget(this);
    m_resultForm->setObjectName("mainListWdg0");
    m_resultForm->setFixedSize(520, 200);
    m_resultForm->move(10, ui->mainFrmSearch->pos().y()-190);
    m_resultForm->hide();
    connect(m_resultForm, &QListWidget::itemClicked, this, &MainForm::onSearchResultItemClicked);

    m_dishesForm = new dishesForm(this);
    m_bunisStatusForm = new BStatusForm(this);
    m_dailyReportForm =new DailyReportForm(this);
    //变更此 "日结" 按钮 为"自测" 按钮；
    //ui->mainBtnDayReport->hide();
    ui->mainBtnSelfCheck->show();
    //变更此 "门店管理" 按钮 为 "同步" 按钮；
    ui->mainBtnSyncOrder->show();
#ifdef TODO
    ui->mainBtnDishManager->hide();
#endif
    //emit flowStart();
    return;
}

void MainForm::_Init()
{
    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    QLOG_INFO()<<QString::fromLocal8Bit("MainForm _Init Size(width:%1,height:%2)").arg( this->width() ).arg( this->height() );
    // 显示托盘
    m_tray.show();

    // 设置任务栏图标和标题
    setWindowIcon(QIcon(":fm.ico"));

    // 初始化文字
    ui->mainLabStoreid->setText(QString::fromLocal8Bit(UI_STOREID));
    ui->mainLabVersion->setText(APP_VERSION);

    // 初始化表
    int scales6[] = {3, 4, 2, 3, 3, 3};
    int scales5[] = {3, 6, 2, 3, 3};
    int tableWidth = this->width() - 75;
    qDebug() << "width" << this->width();
    foreach(QTableWidget *table, m_tableList)
    {
        table->hide();
        if( table == ui->mainTableFinsh )
        {
            for(int i=0; i<5; i++)
            {
                table->setColumnWidth(i, tableWidth*scales5[i]/21);
            }
        }else
        {
            for(int i=0; i<6; i++)
            {
                table->setColumnWidth(i, tableWidth*scales6[i]/21);
            }
        }
        table->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
        table->horizontalHeader()->setFixedHeight(30);
    }

    // 默认选中【新订单】
    ui->mainTableNew->show();
    ui->mainBtnNew->setChecked(true);
    ui->mainBtnNew->setEnabled(false);
    m_prevBtn = ui->mainBtnNew;
    m_prevTable = ui->mainTableNew;
    m_currentTable = ui->mainTableNew;
    ui->mainBtnSet->hide();

    // 特别处理点击表中排序问题;
    _TableWidgetHeaderClickConnect();
}

void MainForm::_TableWidgetHeaderClickConnect(){
    foreach(QTableWidget *table, m_tableList) {
        connect(table->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(_onTableWidgetHeaderClick(int)));
    }
}

void MainForm::_onTableWidgetHeaderClick(int index){
    QLOG_INFO() << QString("[<<<<---MainForm::_onTableWidgetHeaderClick: head index:%1 --->>>>]").arg(index);
    m_currentTable->verticalScrollBar()->setValue(0);
}

void MainForm::onSetCurrentTime()
{
    if(m_raiseIndex++>10){
       m_raiseIndex=0;
       //当点击Windows系统 底部应用任务logo时,会触发将应用最小化动作;故需要将该程序恢复正常状态显示;
       if (windowState() == Qt::WindowMinimized) {
           QLOG_INFO() << QString("[<<<<---MainForm::onSetCurrentTime: windowState: --->>>>]")<<windowState();
           setWindowState(Qt::WindowNoState);
       }
       raise();
    }
    ui->mainSlabTime->setText(QDateTime::currentDateTime().toString(QString::fromLocal8Bit("yyyy年MM月dd日 hh:mm:ss")));
}

void MainForm::onMainTabBtnClicked()
{
    _RevertBtnTable();
    QPushButton *btn = (QPushButton*)sender();
    m_currentTable = findChild<QTableWidget*>(btn->property("tableName").toString());
    m_currentTable->show();
    btn->setChecked(true);
    btn->setEnabled(false);
    m_prevBtn = btn;
    m_prevTable = m_currentTable;
}

void MainForm::onMainProcBtnClicked()
{
    QPushButton *pBtn = (QPushButton*)sender();
    emit processOrder(pBtn->property("operation").toString(), pBtn->property("orderId").toString());
}

void MainForm::on_mainBtnSet_clicked()
{
    m_settingForm->show();
}

void MainForm::on_mainBtnHide_clicked()
{
    hide();
    ui->mainEdtSearch->clear();
    m_padForm->hide();
    if(m_detailForm && m_detailForm->isVisible() ) {
        QLOG_INFO() << QString("[<<<<---MainForm::on_mainBtnHide_clicked:  m_detailForm=--->>>>]")<< m_detailForm;
        m_detailForm->hideDetailAllFrom();
    }

    if (m_alertForm) {
        m_alertForm->hide();
    }

    /*
    if ( m_noticeForm ) {
        m_noticeForm->hide();
    }
    */

    emit showFloatForm();
}


void MainForm::onShowOrderDetails(OrderObject *orderObject)
{
    m_detailForm->InitData(orderObject);
    m_detailForm->show();
}

void MainForm::onShowSearchOrderResult(const QMap<QString,QString>& orderIdList)
{
    QLOG_INFO() << QString("[<<<<---MainForm::onShowSearchOrderResult: orderIdList.length:%1 --->>>>]").arg(orderIdList.count());
    if(orderIdList.isEmpty()) {
        m_resultForm->hide();
        return;
    }
    m_resultForm->clear();
    QMap<QString,QString>::const_iterator order;
    for(order=orderIdList.begin(); order!=orderIdList.end(); order++)
    {
        QListWidgetItem* item=new QListWidgetItem();
        item->setText(order.key()+"  "+order.value());
        m_resultForm->addItem(item);
    }
    m_resultForm->show();
}

void MainForm::onOrderClear(const QString &orderId, const int &oldstatus)
{
    _SetTablesSortEnable(false);
    QTableWidget *table;
    QPushButton *tabBtn;
    tabBtn = _GetTabBtnByOrderStatus(oldstatus);
    table = findChild<QTableWidget*>(tabBtn->property("tableName").toString());
    for(int i=0; i<table->rowCount(); i++)
    {
        // 过期订单数据,主界面需要清除界面上订单记录 [订单号添加换行符用于比对查找];
        int tempOrderIdLen = orderId.length();
        QString tempOrderId = orderId.left( tempOrderIdLen -5 ).append( "\r\n" ).append( orderId.right(5) );

        if(!table->item(i, 1)->text().compare(tempOrderId))
        {
            QLOG_INFO() << QString("[<<<<---MainForm::onOrderClear: Find orderId:%1, tempOrderId:%2 Then Clear Ui Item --->>>>]").arg(orderId).arg(tempOrderId);
            table->removeRow(i);
            QString btnText(tabBtn->property("name").toString());
            btnText = QString("%1\n%2").arg(table->rowCount()).arg(btnText);
            tabBtn->setText(btnText);
        }
    }
    _SetTablesSortEnable(true);
}

void MainForm::onSetDailyReportData(QJsonObject json)
{
    m_dailyReportForm->Initdata(json);
    m_dailyReportForm->show();
}

void MainForm::_RevertBtnTable()
{
    m_prevBtn->setChecked(false);
    m_prevBtn->setEnabled(true);
    m_prevTable->hide();
}

void MainForm::_SetTablesSortEnable(bool bEnable)
{
    foreach (QTableWidget *table, m_tableList)
    {
        table->setSortingEnabled(bEnable);
        // 默认按 第六列的订单创建时间降序;
        table->sortByColumn(5,Qt::DescendingOrder);
    }
}

QPushButton *MainForm::_GetTabBtnByOrderStatus(int orderStatus)
{
    switch(orderStatus)
    {
    case OrderObject::NewOrder:
        return ui->mainBtnNew;
        break;
    case OrderObject::Confirmed:
        return ui->mainBtnMake;
        break;
    /*
    case OrderObject::Cancled:
        return ui->mainBtnUnusual;
        break;
    */
    case OrderObject::Refunded:
        return ui->mainBtnUnusual;
        break;
    case OrderObject::Sendout:
        return ui->mainBtnSend;
        break;
    case OrderObject::Finished:
        return ui->mainBtnFinsh;
        break;
    case OrderObject::RequestRefund:
        return ui->mainBtnUnusual;
        break;
    default:
        return ui->mainBtnUnusual;
        break;
    }
}

void MainForm::onHideAlert()
{
    m_alertForm->hide();
}

void MainForm::onShowAlert(AlertForm::Type type, const QString &msg)
{
    if(this->isVisible())
    {
        m_alertForm->SetContent(type, msg);
        m_alertForm->show();
    }else if ( AlertForm::WARNNING ==type || AlertForm::ACK_MSG ==type ) {
        emit hideFloatForm();
        this->show();
        m_alertForm->SetContent(type, msg);
        m_alertForm->show();
    }
}

void MainForm::onSetStoreInfo(const QString &storeId)
{
    QLOG_INFO() << QString("[<<<<---MainForm::onSetStoreInfo: storeId:%1 --->>>>]").arg(storeId);
    ui->mainLabStoreid->setText(storeId);
}

void MainForm::onSetCashierInfo(const QString &cashierInfo)
{
    QLOG_INFO() << QString("[<<<<---MainForm::onSetCashierInfo: cashierName:%1 --->>>>]").arg(cashierInfo);
    ui->mainLabCashier->setText(cashierInfo);
}

void MainForm::onSetOpeStatus(const QString &status)
{
    ui->mainLabOpeStatus->setText(status);
}

void MainForm::onSetNetStatus(const QString &status)
{
    ui->mainLabNetStatus->setText(status);
}

void MainForm::onChangeOrderStatus(OrderObject *orderObject, int oldStatus)
{
    _SetTablesSortEnable(false);
    QTableWidget *table;
    QPushButton *tabBtn;
    // 非首次收到的订单需要现在原先表中删除
    if(oldStatus != -100)
    {
        tabBtn = _GetTabBtnByOrderStatus(oldStatus);
        table = findChild<QTableWidget*>(tabBtn->property("tableName").toString());

        for(int i=0; i<table->rowCount(); i++)
        {
            // 订单状态改变,主界面需要先移除Old Item后, 再添加New Item; [订单号添加换行符用于比对查找];
            int tempOrderIdLen = orderObject->id.length();
            QString tempOrderId = orderObject->id.left( tempOrderIdLen -5 ).append( "\r\n" ).append( orderObject->id.right(5) );
            if( !table->item(i, 1)->text().compare(tempOrderId) )
            {
                QLOG_INFO() << QString("[<<<<---MainForm::onChangeOrderStatus:Find/RemoveItem: orderId:%1, tempOrderId:%2 --->>>>]").arg(orderObject->id).arg(tempOrderId);
                table->removeRow(i);
                QString btnText(tabBtn->property("name").toString());
                btnText = QString("%1\n%2").arg(table->rowCount()).arg(btnText);
                tabBtn->setText(btnText);
            }
        }
    }
    // 将数据插入到表中
    tabBtn = _GetTabBtnByOrderStatus(orderObject->orderStatus);
    table = findChild<QTableWidget*>(tabBtn->property("tableName").toString());

    table->insertRow(0);
    QTableWidgetItem *item0 = new QTableWidgetItem(orderObject->getChannelName());
    item0->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 0, item0);  // 渠道

    // 订单状态变更,插件主界面刷新主界面显示 [订单号添加换行符];
    int tempOrderIdLen = orderObject->id.length();
    QString tempOrderId = orderObject->id.left( tempOrderIdLen -5 ).append( "\r\n" ).append( orderObject->id.right(5) );
    // QLOG_INFO() << QString("[<<<<---MainForm::onChangeOrderStatus:AddItem orderId:%1, tempOrderId:%2 --->>>>]").arg(orderObject->id).arg(tempOrderId);
    QTableWidgetItem *item1 = new QTableWidgetItem(tempOrderId);
    item1->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 1, item1);  // 订单ID

    //QTableWidgetItem *item2 = new QTableWidgetItem(Penny2Dollar(orderObject->totalPrice));
    QTableWidgetItem *item2 = new QTableWidgetItem();
    item2->setData(Qt::DisplayRole, Penny2Dollar2Double(orderObject->totalPrice));

    item2->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 2, item2);  // 金额

    table->item(0,2)->setFlags(table->item(0,2)->flags() & (~Qt::ItemIsEditable));

    //QTableWidgetItem *item3 = new QTableWidgetItem(orderObject->customerName);
    QTableWidgetItem *item3 = new QTableWidgetItem(orderObject->consigneeName);
    item3->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 3, item3);  // 姓名
    //QTableWidgetItem *item4 = new QTableWidgetItem(orderObject->phone);
    QTableWidgetItem *item4 = new QTableWidgetItem(orderObject->consigneePhone);
    item4->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 4, item4);  // 联系方式
    QTableWidgetItem *item5 = new QTableWidgetItem(orderObject->createTime);
    item5->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 5, item5);  // 下单时间
    if(table != ui->mainTableFinsh)
    {
        // 订单已经支付待接单的订单;
        if(OrderObject::NewOrder==orderObject->orderStatus)
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(70, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(table->property("operationName").toString());
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }

        //已经接单的订单;
        if(OrderObject::Confirmed==orderObject->orderStatus )
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(90, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            if ( "MOP" == orderObject->channel || "MT-MOP" == orderObject->channel || "EC-MOP" == orderObject->channel || "EC_WECHAT_MOP" == orderObject->channel ) {
                pBtn->setText(QString::fromLocal8Bit("请扫码通知"));
            }else{
                pBtn->setText(QString::fromLocal8Bit("请扫码配送"));
            }
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }

        // 已经配送的订单不能点击完成;
        if(OrderObject::Sendout==orderObject->orderStatus )
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(90, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(QString::fromLocal8Bit("等待配送完成"));
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }
        // 已经取消的订单 + 商家已经退款的订单;
        if(OrderObject::Refunded == orderObject->orderStatus)
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(70, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(QString::fromLocal8Bit("已退款"));
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }
        // 商家拒绝退款的订单;
        if(OrderObject::RefuseRefund == orderObject->orderStatus)
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(70, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(QString::fromLocal8Bit("拒绝退款"));
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }

        // SIM录外卖订单出现异常的订单(正向销售单);
        if(OrderObject::SimExceptSale == orderObject->orderStatus)
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(120, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(QString::fromLocal8Bit("录单失败,未退款"));
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }

        // SIM录退货:外卖订单出现异常的订单(已退单);
        if(OrderObject::SimExceptRefund == orderObject->orderStatus)
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(120, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(QString::fromLocal8Bit("录单失败,已退款"));
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }
        // 已下单待支付;
        if(1==orderObject->orderStatus)
        {
            qDebug()<<table->objectName()<<"------";
            QWidget *pWdg = new QWidget(table);
            QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
            QPushButton * pBtn = new QPushButton(pWdg);
            pBtn->setFixedSize(70, 30);
            pBtn->setFocusPolicy(Qt::NoFocus);
            pBtn->setObjectName("mainProcBtn");
            pBtn->setProperty("orderId", orderObject->id);
            //pBtn->setProperty("operation", table->property("operation").toString());
            pBtn->setText(QString::fromLocal8Bit("待支付"));
            pBtn->setDisabled(true);
            hLayout->addWidget(pBtn);
            hLayout->setMargin(0);
            pWdg->setLayout(hLayout);
            table->setCellWidget(0, 6, pWdg);   // 操作按钮
            //connect(pBtn, &QPushButton::clicked, this, &MainForm::onMainProcBtnClicked);
        }
    }

    QString btnText = QString("%1\n%2").arg(table->rowCount()).arg(tabBtn->property("name").toString());
    tabBtn->setText(btnText);

    // 检测是否需要提示
    _SetTablesSortEnable(true);
}


void MainForm::on_mainBtnUp_clicked()
{
    m_currentTable->scrollToTop();
}


void MainForm::on_mainBtnDown_clicked()
{
    m_currentTable->scrollToBottom();
}

void MainForm::onMainTableItemClicked(QTableWidgetItem *item)
{    
    // 插件主界面点击 Item行，进入订单详情界面展示 [订单号摘除换行符];
    QString uiItemOrderId = ((QTableWidget*)sender())->item(item->row(), 1)->text();
    QString originOrderId = uiItemOrderId;
    int bpos = originOrderId.indexOf("\r");
    originOrderId = originOrderId.mid(0,bpos) + originOrderId.mid( bpos + 2 );
    QLOG_INFO() << QString("[<<<<---MainForm::onMainTableItemClicked: uiItemOrderId:%1, OrderId:%2 Then Entry Detail Ui--->>>>]").arg(uiItemOrderId).arg(originOrderId);
    emit getOrderDetails(originOrderId);
}

/*
void MainForm::onMainNoticeItemClicked(QTableWidgetItem *item)
{
    // 插件主界面点击 Item行，进入门店通告详情界面展示;
    QString uiItemNoticeTitle = ( ( QTableWidget* )sender() )->item( item->row(), 0 )->text();
    QString uiItemNoticeContent = ( ( QTableWidget* )sender() )->item( item->row(), 1 )->text();
    int uiItemNoticeAckStatus = ( ( QTableWidget* )sender() )->item( item->row(), 2 )->text().toInt();
    QString uiItemNoticeCreateDatetime = ( ( QTableWidget* )sender() )->item( item->row(), 3 )->text();
    int uiItemNoticeInsertIdIndex = ( ( QTableWidget* )sender() )->item( item->row(), 4 )->text().toInt();
    QLOG_INFO() << QString("[<<<<---MainForm::onMainNoticeItemClicked: title:%1, ackStatus:%2, CreateDatetime:%3, InsertIdIndex:%4 Then Entry Detail Ui--->>>>]")
                   .arg(uiItemNoticeTitle).arg(uiItemNoticeAckStatus).arg(uiItemNoticeCreateDatetime).arg(uiItemNoticeInsertIdIndex);
    onShowNotice(NoticeForm::ACK_MSG, uiItemNoticeTitle, uiItemNoticeContent, uiItemNoticeInsertIdIndex);
}
*/

void MainForm::on_mainEdtSearch_clicked()
{
    m_padForm->show();
}

void MainForm::onNumClicked(const QString &num)
{
    ui->mainEdtSearch->setText(ui->mainEdtSearch->text().append(num));
}

void MainForm::onNumDelete()
{
    QString text = ui->mainEdtSearch->text();
    ui->mainEdtSearch->setText(text.left(text.length()-1));
}


void MainForm::onDisplayEcMopOrder()
{
    QString orderId  = ui->mainEdtSearch->text();
    ui->mainEdtSearch->clear();
    QLOG_INFO() << QString("[<<<<---MainForm::onDisplayEcMopOrder: orderId:%1--->>>>]").arg(orderId);
    onShowAlert(AlertForm::BRIEF_TIPS, QString::fromLocal8Bit("获取 EC-MOP 订单数据......"));
    emit getEcMopOrderDetails(orderId, "EC-MOP");
}


void MainForm::onSearchResultItemClicked(QListWidgetItem *item)
{
    ui->mainEdtSearch->clear();
    m_padForm->hide();
    m_resultForm->hide();
    QString str=item->text();

    str=str.mid(4);
    QString y = "  ";
    str=str.mid(0,str.indexOf(y));
    emit getOrderDetails(str);
}

void MainForm::on_mainBtnDishManager_clicked()
{
    emit PullDishes();
}

void MainForm::on_mainBtnSyncOrder_clicked()
{
    emit GetOMSAllOrders();
}

void MainForm::on_mainBtnSelfCheck_clicked()
{
    emit   sendSelfCheck();
}
