#include "newmainform.h"
#include "ui_newmainform.h"
#include "model/orderObject.h"
#include "model/posorderpool.h"
#include "model/posprtpool.h"
#include "view/ordertypeform.h"
#include "view/orderoptform.h"

#include "QsLog.h"
#include "base/System/GetPrinters.h"

#include "event/fmapplication.h"
#include "event/posevent.h"
#include "QsLog.h"

#include <QScrollBar>
#include <QJsonDocument>

NewMainForm::NewMainForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NewMainForm)
{
    _prttype = -1;
    _curr_page_num = 1;
    _curr_check_btn = NULL;
    ui->setupUi(this);
    InitClassify();
    InitMainBtn();
    InitPrtSettingWidget();
    InitWidget(MAIN_ORDER);
    ui->newmaintbwgt->setCurrentIndex(0);
    InitTableWidget();
    InitPrtList();
    InitPrtSetting();

    FMApplication::subscibeEvent(this, PosEvent::s_login_status);
    FMApplication::subscibeEvent(this, PosEvent::s_opt_status);
    FMApplication::subscibeEvent(this, PosEvent::s_change_order);
    FMApplication::subscibeEvent(this, PosEvent::s_get_order_status);
    FMApplication::subscibeEvent(this, PosEvent::s_delete_order);
    FMApplication::subscibeEvent(this, PosEvent::s_login_storeinfo);
    FMApplication::subscibeEvent(this, PosEvent::s_show_mainform);
    FMApplication::subscibeEvent(this, PosEvent::s_network_outtime);

    this->show();
    //this->showFullScreen();
    this->hide();

    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    connect(ui->newmainline_serach, &ClickedLineEdit::clicked, this, &NewMainForm::onSerachclicked);

    _alertForm = new AlertForm(this);
    _padForm = new PadForm(this);
    _detailForm = new NewDetailForm(this);
    _prttypeForm = new PrtTypeForm(this);

    connect(_prttypeForm, &PrtTypeForm::BtnClicket, this, &NewMainForm::onPrtTypeChanged);

    connect(ui->newmaintablewidget_order, &QTableWidget::itemClicked, this, &NewMainForm::onMainTableItemClicked);

    connect(_detailForm, &NewDetailForm::showAlert, this, &NewMainForm::onShowAlert);
    _padForm->move(this->pos().x() + 212 ,this->pos().y() + 100);
    _padForm->hide();
    connect(_padForm, &PadForm::numClicked, this, &NewMainForm::onNumClicked);
    connect(_padForm, &PadForm::numDelete, this, &NewMainForm::onNumDelete);
    connect(_padForm, &PadForm::numClear, ui->newmainline_serach, &ClickedLineEdit::clear);
    _resultForm = new QListWidget(this);
    _resultForm->setObjectName("mainListWdg0");
    _resultForm->setFixedSize(340, 200);
    _resultForm->move(454, 100);
    _resultForm->hide();
    connect(_resultForm, &QListWidget::itemClicked, this, &NewMainForm::onSearchResultItemClicked);

    connect(&_timeTimer, &QTimer::timeout, this, &NewMainForm::onSetCurrentTime);

    connect(ui->newmainline_serach, &ClickedLineEdit::textChanged, this, &NewMainForm::onSerachOrder);

    _raiseIndex = 0;

    _timeTimer.start(1000);

    // 显示托盘
    m_tray.show();
}


void NewMainForm::onPrtTypeChanged(int type)
{
    QLOG_DEBUG() << "NewMainForm::onPrtTypeChanged : " << type;

    //清除未保存的打印机
    InitPrtSetting();

    _prttype = type;

    QString name = "";

    QLOG_DEBUG() << "--input--" << "name" << name << "";

    QString strtime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");

    if(_prttype == 0)
        name = QString::fromUtf8("\xE5\xB0\x8F\xE7\xA5\xA8") + strtime;
    else if(_prttype == 1)
        name = QString::fromUtf8("\xE6\x9D\xAF\xE8\xB4\xB4") + strtime;
    else if(_prttype == 2)
        name = QString::fromUtf8("\xE5\x90\x8E\xE5\x8E\xA8") + strtime;
    else
    {
        ui->newmainlabel_errmsg->setText(QString::fromUtf8("\xE6\x97\xA0\xE6\x95\x88\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA\xE7\xB1\xBB\xE5\x9E\x8B"));
        return ;
    }

    QLOG_DEBUG() << "--input--" << "name" << name;

    ui->newmainlabel_errmsg->setText(QString::fromUtf8("\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA\xE6\xB7\xBB\xE5\x8A\xA0\xE6\x88\x90\xE5\x8A\x9F\x2D") + name);

    ui->newmaincombx_prttype->addItem(name);

    ui->newmaincombx_prttype->setCurrentText(name);

    bool notlabprtflag = true;

    if(_prttype != 1)
    {
        notlabprtflag = true;
        ui->newmaincombx_cmd->setEnabled(false);
        ui->newmaincombx_netcmd->setEnabled(false);
        ui->newmainline_bth->hide();
        ui->newmainline_btw->hide();
        ui->newmainline_netbth->hide();
        ui->newmainline_netbtw->hide();
        ui->newlabel_40->hide();
        ui->newlabel_41->hide();
        ui->newlabel_42->hide();
        ui->newlabel_43->hide();
        ui->newmaincombx_dvwidth->setEnabled(true);
        ui->newmaincombx_netwidth->setEnabled(true);
    }
    else
    {
        notlabprtflag = false;
        ui->newmaincombx_cmd->setEnabled(true);
        ui->newmaincombx_netcmd->setEnabled(true);
        ui->newmainline_bth->show();
        ui->newmainline_btw->show();
        ui->newmainline_netbth->show();
        ui->newmainline_netbtw->show();
        ui->newlabel_40->show();
        ui->newlabel_41->show();
        ui->newlabel_42->show();
        ui->newlabel_43->show();
        ui->newmaincombx_dvwidth->setEnabled(false);
        ui->newmaincombx_netwidth->setEnabled(false);
    }

    ui->newmainrdbtn_com->setEnabled(notlabprtflag);
    ui->newmainrdbtn_lpt->setEnabled(notlabprtflag);

    ui->newmainrdbtn_dv->setChecked(true);
    InitSettingWidget(SET_PRT_DV);
}

void NewMainForm::onSerachOrder(const QString &key)
{
    if(key.isEmpty())
    {
        _resultForm->hide();
        return;
    }

    QMap<QString, QString> map;

    _resultForm->clear();
    if(PosOrderPool::GetSearchOrder(key, map))
    {
        QMap<QString,QString>::const_iterator order;
        for(order=map.begin(); order!=map.end(); order++)
        {
            QListWidgetItem* item=new QListWidgetItem();
            item->setText(QString::fromLocal8Bit("订单号:") + order.key() + QString::fromLocal8Bit("  手机号:") + order.value());
            _resultForm->addItem(item);
        }
        _resultForm->show();
    }
}

void NewMainForm::onSearchResultItemClicked(QListWidgetItem *item)
{
    ui->newmainline_serach->clear();
    _padForm->hide();
    _resultForm->hide();
    QString str=item->text();

    QLOG_DEBUG() << "mainForm input 0" << str;

    str=str.mid(4);

    QLOG_DEBUG() << "mainForm input 1" << str;

    QString y = "  ";
    str=str.mid(0,str.indexOf(y));

    QLOG_DEBUG() << "mainForm input 2" << str;

    OrderObject order;
    if(!PosOrderPool::GetOrderObject(str, order))
        return ;

    onHideAlert();
    _detailForm->InitData(&order);
    _detailForm->show();
}

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

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

void NewMainForm::onSerachclicked()
{
    _padForm->show();
}

void NewMainForm::onSetCurrentTime()
{
    if(_raiseIndex++>10)
    {
       _raiseIndex=0;
       raise();
    }
    ui->newmainlabel_time->setText(QDateTime::currentDateTime().toString(QString("MM-dd hh:mm:ss")));
}

void NewMainForm::onShowAlert(AlertForm::Type type, const QString &msg)
{

    if(this->isVisible())
    {
        _alertForm->SetContent(type, msg);
        _alertForm->show();
    }
}

void NewMainForm::FullShow()
{
    this->show();
    //this->showFullScreen();
    InitPageNum();
}

void NewMainForm::InitPageNum()
{
    int num = ui->newmaintablewidget_order->height()/36;

    int page =  _curr_page_num/(num - 1) ;

    if(_curr_page_num %(num - 1) != 0)
        ++ page;

    _curr_page = 1;
    ui->newmaintablewidget_order->verticalScrollBar()->setValue(0);
    ui->newmainlabel_allnum->setText(QString::fromUtf8("\xE5\x85\xB1%1\xE6\x9D\xA1").arg(QString::number(_curr_page_num)));
    if (page != 0)
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(page));
    else
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString("1"));
    ui->newmaintablewidget_order->viewport()->setFixedHeight((num - 1) * 36);
}

void NewMainForm::InitPrtList()
{
    QStringList list;
    GetPrinters::GetPrintersName(list);
    for(int i = 0; i < list.size(); ++ i)
    {
        ui->newmaincombx_name->addItem(list[i]);
    }
    ui->newmainline_name->setText(ui->newmaincombx_name->currentText());
}

bool NewMainForm::ClassifyOrder(QString type)
{
    int tmptype = type.toInt();
    switch (tmptype) {
    case TYPE_NEEDREFUND:
        ClassifyOrderWithOrderStatus(ApplicationRefundOrder);
        break;
    case TYPE_REFUNDED:
        ClassifyOrderWithOrderStatus(CancelOrder);
        break;
    case TYPE_ALL:
        ClassifyOrderWithOrderStatus(DefaultOrder);
        break;
    case TYPE_NEW:
        ClassifyOrderWithOrderStatus(NewOrder);
        break;
    case TYPE_MAKE:
        ClassifyOrderWithOrderStatus(FirmOrder);
        break;
    case TYPE_SEND:
        ClassifyOrderWithOrderStatus(DispatchingOrder);
        break;
    case TYPE_NAKEOVER:
        ClassifyOrderWithOrderStatus(InDevelopment);
        break;
    case TYPE_OVER:
        ClassifyOrderWithOrderStatus(CompleteOrder);
        break;
    case TYPE_FUTURE:
        ClassifyOrderWithOrderType();
        break;
    default:
        return false;
    }
    return true;
}

void NewMainForm::ClassifyOrderWithOrderType()
{
    _curr_page_num = 0;
    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = (OrderTypeForm *)table->cellWidget(i, 1);

        if(pwd->order_type() == AppointmentTakeout ||
                pwd->order_type() == AppointmentDining ||
                pwd->order_type() == AppointmentInvite)
        {
            table->setRowHidden(i, false);
            ++_curr_page_num;
        }
        else
        {
            table->setRowHidden(i, true);
        }
    }
}

void NewMainForm::ClassifyOrderWithOrderStatus(int order_status)
{
    _curr_page_num = 0;

    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = NULL;

        switch (order_status) {
        case DefaultOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == NewOrder || pwd->GetOrderStatus() == FirmOrder ||
                    pwd->GetOrderStatus() == DispatchingOrder || pwd->GetOrderStatus() == DispatchingOrder ||
                    pwd->GetOrderStatus() == InDevelopment || pwd->GetOrderStatus() == CompleteOrder ||
                    pwd->GetOrderStatus() == ServiceOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case NewOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == NewOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case FirmOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1); 
            if(pwd->GetOrderStatus() == FirmOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case DispatchingOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == DispatchingOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case InDevelopment:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == InDevelopment)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case ApplicationRefundOrder:
        case ApplicationPartialRefundOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == ApplicationRefundOrder || pwd->GetOrderStatus() == ApplicationPartialRefundOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case LockOrder:
        case CancelOrder:
        case ApprovalRefundOrder:
        case CompleteRefundOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            //qDebug()<<"-----" << pwd->GetOrderStatus() << ";" << pwd->order_id() << ";" << pwd->refund_status() << ";" << pwd->order_status();
            if(pwd->GetOrderStatus() == ApprovalRefundOrder || pwd->GetOrderStatus() == CompleteRefundOrder
                    || pwd->GetOrderStatus() == LockOrder || pwd->GetOrderStatus() == CancelOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case CompleteOrder:
        case ServiceOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == CompleteOrder || pwd->GetOrderStatus() == ServiceOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        default:
            table->setRowHidden(i, true);
            break;
        }
    }
    //ui->newmainlabel_allnum->setText(QString::fromUtf8("\xE5\x85\xB1%1\xE6\x9D\xA1").arg(QString::number(_curr_page_num)));
    InitPageNum();
}

void NewMainForm::InitMainBtn()
{
    ui->newmainbtn_order->SetText("\xE8\xAE\xA2\xE5\x8D\x95\xE7\xAE\xA1\xE7\x90\x86", MAIN_ORDER);
    ui->newmainbtn_refund->SetText("\xE9\x80\x80\xE5\x8D\x95", MAIN_REFUND);
    ui->newmainbtn_set->SetText("\xE8\xAE\xBE\xE7\xBD\xAE", MAIN_SET);
    ui->newmainbtn_order->setProperty("type", "order");
    ui->newmainbtn_refund->setProperty("type", "refund");
    ui->newmainbtn_set->setProperty("type", "set");
    _main_btn.insert(ui->newmainbtn_order);
    _main_btn.insert(ui->newmainbtn_refund);
    _main_btn.insert(ui->newmainbtn_set);
}

void NewMainForm::SetMainBtnCheck(MainBtn *wgt)
{
    foreach (auto var, _main_btn) {
        if(wgt == var)
            var->setChecked(true);
        else
            var->setChecked(false);

        //qDebug() << "&&&&&&&&&&&&" << var->property("type").toString();
    }
}

void NewMainForm::InitPrtSettingWidget()
{
    _btnGroup.setId(ui->newmainrdbtn_dv, 4);
    _btnGroup.setId(ui->newmainrdbtn_com, 0);
    _btnGroup.setId(ui->newmainrdbtn_lpt, 1);
    _btnGroup.setId(ui->newmainrdbtn_net, 3);
    _prtsetting_widget.insert(ui->newmainwidget_dv);
    _prtsetting_widget.insert(ui->newmainwidget_com);
    _prtsetting_widget.insert(ui->newmainwidget_net);
    _prtsetting_widget.insert(ui->newmainwidget_lpt);
}

void NewMainForm::InitClassify()
{
    _classify_set.insert(ui->newmainbtn_needrefund);
    _classify_set.insert(ui->newmainbtn_refunded);
    _classify_set.insert(ui->newmainbtn_all);
    _classify_set.insert(ui->newmainbtn_new);
    _classify_set.insert(ui->newmainbtn_make);
    _classify_set.insert(ui->newmainbtn_makeover);
    _classify_set.insert(ui->newmainbtn_send);
    _classify_set.insert(ui->newmainbtn_over);
    _classify_set.insert(ui->newmainbtn_future);
}

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

bool NewMainForm::event(QEvent *e)
{
    if(e->type() == PosEvent::s_change_order)
    {
        QString orderid;

        GETEVENTINFO(orderid,e,QString);

        OrderObject order;

        if(!PosOrderPool::GetOrderObject(orderid, order))
            return true;

        Order_Index tmp = {order.status, order.refund_status};
        
        if(_order_indexs.contains(order.order_id))
        {
            _order_indexs.insert(order.order_id, tmp);
            UpdateTableWidget(order);
        }
        else
        {
            _order_indexs.insert(order.order_id, tmp);
            InsertTableWidget(order);
        }

        return true;
    }

    if(e->type() == PosEvent::s_login_storeinfo)
    {
        QVariantMap map;

        GETEVENTINFO(map, e, QVariantMap);

        _storeinfo = map;

        return true;
    }

    if(e->type() == PosEvent::s_show_mainform)
    {
        this->show();
        //this->showFullScreen();
        return true;
    }

    if(e->type() == PosEvent::s_delete_order)
    {
        QVariantMap value;

        GETEVENTINFO(value,e,QVariantMap);

        if(value.contains(EVENT_KEY_ORDERID) && !value[EVENT_KEY_ORDERID].toString().isEmpty() &&
                _order_indexs.contains(value[EVENT_KEY_ORDERID].toString()))
        {
            DeleteTableWidget(value[EVENT_KEY_ORDERID].toString());
            _order_indexs.remove(value[EVENT_KEY_ORDERID].toString());
        }
        return true;
    }

    if(e->type() == PosEvent::s_opt_status)
    {
        QVariantMap value;

        GETEVENTINFO(value,e,QVariantMap);

        if(value.contains(EVENT_KEY_ORDERSTATUS) && value[EVENT_KEY_ORDERSTATUS].toInt() == 0)
        {
            if(!this->isHidden())
                onShowAlert(AlertForm::LOADING, value[EVENT_KEY_MSG].toString());
            return true;
        }

        if(value.contains(EVENT_KEY_STATUS) && value[EVENT_KEY_STATUS].toBool() == false)
        {
            QLOG_INFO() << value[EVENT_KEY_MSG].toString();
            if(!this->isHidden())
                onShowAlert((AlertForm::Type)1, value[EVENT_KEY_MSG].toString());
        }
        else if(value.contains(EVENT_KEY_STATUS) && value[EVENT_KEY_STATUS].toBool() == true)
        {
            if(!this->isHidden())
                onShowAlert(AlertForm::SUCCESS, value[EVENT_KEY_MSG].toString());
        }
        return true;
    }

    if(e->type() == PosEvent::s_login_status)
    {
        QVariantMap value;

        GETEVENTINFO(value,e,QVariantMap);

        if(value.contains(EVENT_KEY_STATUS) && value[EVENT_KEY_STATUS].toBool() == false)
        {
            QLOG_INFO() << value[EVENT_KEY_MSG].toString();
            onSetStoreInfo(QString::fromUtf8("\xE6\x9C\xAA\xE7\x99\xBB\xE5\xBD\x95"));
            onSetCashierInfo(QString::fromUtf8("\xE6\x9C\xAA\xE7\x99\xBB\xE5\xBD\x95"));
        }
        else if(value.contains(EVENT_KEY_STATUS) && value[EVENT_KEY_STATUS].toBool() == true)
        {
            onSetStoreInfo(_storeinfo[JSON_STOREID].toString());
            onSetCashierInfo(_storeinfo[JSON_STATIONID].toString());
            onSetNetStatus(QString::fromUtf8("\xE7\xBD\x91\xE7\xBB\x9C\xE6\xAD\xA3\xE5\xB8\xB8"));
        }
        return true;
    }

    if(e->type() == PosEvent::s_network_outtime)
    {
        QVariantMap value;
        GETEVENTINFO(value,e,QVariantMap);
        if(value.contains(EVENT_KEY_NETWORKSTATUS) && value[EVENT_KEY_NETWORKSTATUS].toBool() == true)
        {
            onSetNetStatus(QString::fromUtf8(""));
        }else{
            QLOG_INFO() << "STATIC: EVENT_KEY_NETWORKSTATUS:false";
            onSetNetStatus(QString("<font color='#ff0000'>%1</font>").arg(QString::fromUtf8("\xE7\xBD\x91\xE7\xBB\x9C\xE5\xBC\x82\xE5\xB8\xB8")));
            onShowAlert((AlertForm::Type)1, QString::fromUtf8("\xE7\xBD\x91\xE7\xBB\x9C\xE5\xBC\x82\xE5\xB8\xB8\x2C\xE8\xAF\xB7\xE6\xA3\x80\xE6\x9F\xA5\xE7\xBD\x91\xE7\xBB\x9C\xE9\x93\xBE\xE6\x8E\xA5\x21"));
        }
        return true;
    }

    return QWidget::event(e);
}

void NewMainForm::onSetNetStatus(const QString &netstatus)
{
    ui->newmainlabel_net->setText(netstatus);
}

void NewMainForm::onMainTableItemClicked(QTableWidgetItem *item)
{
    QTableWidget *table = ui->newmaintablewidget_order;

    OrderTypeForm* pwd = (OrderTypeForm *)table->cellWidget(item->row(), 1);

    QString orderId = pwd->order_id();

    OrderObject order;

    if(!PosOrderPool::GetOrderObject(orderId, order))
        return ;

    onHideAlert();
    _detailForm->InitData(&order);
    _detailForm->show();

}

void NewMainForm::onHideAlert()
{
    _alertForm->hide();
}


void NewMainForm::onSetCashierInfo(const QString &cashierInfo)
{
    QString posno = QString::fromUtf8("\xE6\x94\xB6\xE9\x93\xB6\x3A%1").arg(cashierInfo);

    QLOG_DEBUG() << posno << cashierInfo;

    ui->newmainlabel_posid->setText(posno);
}

void NewMainForm::onSetStoreInfo(const QString &storeId)
{
    QString store_id = QString::fromUtf8("\xE9\x97\xA8\xE5\xBA\x97\x3A%1").arg(storeId);;

    QLOG_DEBUG() << store_id << storeId;

    ui->newmainlabel_store->setText(store_id);
}

void NewMainForm::SetChecked(QPushButton *btn)
{
    foreach (auto var, _classify_set) {
        if(btn == var)
        {
            _curr_check_btn = btn;
            var->setChecked(true);
            ClassifyOrder(_curr_check_btn->property("type").toString());

            //qDebug() << "------" << _curr_page_num;

            InitPageNum();
        }
        else
        {
            var->setChecked(false);
        }
    }
}

void NewMainForm::UpdateTableWidget(OrderObject &orderObject)
{
    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = (OrderTypeForm *)table->cellWidget(i, 1);
        OrderOptForm *opt = (OrderOptForm *)table->cellWidget(i, 6);

        if(orderObject.order_id.compare(pwd->order_id()) == 0)
        {
            pwd->InitShow(orderObject.order_id, orderObject.status, orderObject.refund_status, orderObject.order_type);
            opt->InitShow(orderObject.order_id, orderObject.status, orderObject.refund_status, orderObject.order_type);
            break;
        }
    }

    ClassifyOrder(_curr_check_btn->property("type").toString());
}

void NewMainForm::DeleteTableWidget(QString orderid)
{
    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = (OrderTypeForm *)table->cellWidget(i, 1);

        if(orderid.compare(pwd->order_id()) == 0)
        {
            table->removeRow(i);
            break;
        }
    }

    ClassifyOrder(_curr_check_btn->property("type").toString());
}

void NewMainForm::MyShow()
{
    this->FullShow();
    this->hide();
}

void NewMainForm::OptOrder(QString orderid, QString optname)
{
    QLOG_DEBUG() << "orderid:" << orderid << "optname:" <<  optname;

    QVariantMap value;

    value.insert(EVENT_KEY_ORDERID, orderid);
    value.insert(EVENT_KEY_STATUS, optname);

    POSTEVENTTYPE(PosEvent::s_opt_order,value,QVariantMap);
}


void NewMainForm::InitTableWidget()
{
    ui->newmaintablewidget_order->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->newmaintablewidget_order->horizontalHeader()->setFixedHeight(36);
    ui->newmaintablewidget_order->verticalHeader()->setVisible(false);
}

void NewMainForm::InsertTableWidget(OrderObject &orderObject)
{
    QTableWidget *table = ui->newmaintablewidget_order;
    table->insertRow(0);
    QTableWidgetItem *item = new QTableWidgetItem(QString::number(orderObject.order_index));
    item->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 0, item);  //序号

    OrderTypeForm *pWdg = new OrderTypeForm(table);
    pWdg->InitShow(orderObject.order_id, orderObject.status, orderObject.refund_status, orderObject.order_type);
    //pWdg->InitShow(QString::number(orderObject.order_index), orderObject.status, orderObject.refund_status, orderObject.order_type);

    table->setCellWidget(0, 1, pWdg); //订单状态
    QTableWidgetItem *item0 = new QTableWidgetItem(QString(orderObject.channel_name));
    item0->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 2, item0);  // 渠道
//    QTableWidgetItem *item1 = new QTableWidgetItem(orderObject.order_id);
//    item1->setTextAlignment(Qt::AlignCenter);
//    table->setItem(0, 3, item1);  // 订单ID
    QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(orderObject.shop_fee/100.0));
    item2->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 3, item2);  // 金额
    QTableWidgetItem *item3 = new QTableWidgetItem(orderObject.customer);
    item3->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 4, item3);  // 姓名
    QTableWidgetItem *item4 = new QTableWidgetItem(orderObject.phone);
    item4->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 5, item4);  // 联系方式
//    QTableWidgetItem *item5 = new QTableWidgetItem(QDateTime::fromTime_t(orderObject.create_time).toString("MM-dd hh:mm"));
//    item5->setTextAlignment(Qt::AlignCenter);
//    table->setItem(0, 6, item5);  // 下单时间

    OrderOptForm *form = new OrderOptForm(table);
    form->InitShow(orderObject.order_id, orderObject.status, orderObject.refund_status, orderObject.order_type);
    table->setCellWidget(0, 6, form); //订单操作
    connect(form, &OrderOptForm::OptOrder, this, &NewMainForm::OptOrder);

    //qDebug() << _curr_check_btn->property("type").toString();

    ClassifyOrder(_curr_check_btn->property("type").toString());

    table->setRowHeight(0, 36);
}

void NewMainForm::GetOrderStatus(OrderObject &order, int &order_status)
{
    if(order.refund_status == ApplicationRefundOrder &&
            order.refund_status == ApplicationPartialRefundOrder &&
            order.refund_status == RefusingRefundOrder)
        order_status = order.refund_status;
    else
        order_status = order.status;
}

void NewMainForm::InitOrderWidget(QString type)
{
    if(type.compare(MAIN_ORDER, Qt::CaseInsensitive) == 0)
    {
        ui->newmainbtn_needrefund->hide();
        ui->newmainbtn_refunded->hide();
        ui->newmainbtn_all->show();
        ui->newmainbtn_new->show();
        ui->newmainbtn_make->show();
        ui->newmainbtn_makeover->show();
        ui->newmainbtn_over->show();
        ui->newmainbtn_future->show();
        ui->newmainbtn_send->show();
        SetMainBtnCheck(ui->newmainbtn_order);
        SetChecked(ui->newmainbtn_all);
        _curr_check_btn = ui->newmainbtn_all;
    }
    else if(type.compare(MAIN_REFUND, Qt::CaseInsensitive) == 0)
    {
        ui->newmainbtn_needrefund->show();
        ui->newmainbtn_refunded->show();
        ui->newmainbtn_all->hide();
        ui->newmainbtn_new->hide();
        ui->newmainbtn_make->hide();
        ui->newmainbtn_makeover->hide();
        ui->newmainbtn_over->hide();
        ui->newmainbtn_future->hide();
        ui->newmainbtn_send->hide();
        SetMainBtnCheck(ui->newmainbtn_refund);
        SetChecked(ui->newmainbtn_needrefund);
        _curr_check_btn = ui->newmainbtn_needrefund;
    }

}

void NewMainForm::InitSetWidget()
{
    SetChecked(ui->newmainbtn_needrefund);

    ui->newmaincombx_prttype->setCurrentIndex(0);

    SetMainBtnCheck(ui->newmainbtn_set);

    InitOrderSetting();
}

void NewMainForm::InitWidget(QString type)
{
    if(type.compare(MAIN_SET, Qt::CaseInsensitive) == 0)
    {
        InitSetWidget();
        ui->newmainwgt_order->hide();
        ui->newmainwgt_set->show();
    }
    else
    {
        InitOrderWidget(type);
        ui->newmainwgt_order->show();
        ui->newmainwgt_set->hide();
    }
}

void NewMainForm::on_newmainbtn_clicked()
{
    MainBtn *pBtn = (MainBtn*)sender();

    QString type = pBtn->property("type").toString();

    if(!type.isEmpty())
    {
        InitWidget(type);
        ui->newmainlabel_mgtitile->setText(pBtn->info());
    }
}

void NewMainForm::on_classifybtn_clicked()
{
    QPushButton *pBtn = (QPushButton*)sender();
    SetChecked(pBtn);
}

void NewMainForm::SettingWidgetWithConf(int prttype, QVariantMap &map)
{
    int type = 4;
    int labelcmd = 0;
    bool notlabprtflag = true;

    type = map[PRT_CONF_TYPE].toInt();

    if(prttype != 1)
    {
        notlabprtflag = true;
        ui->newmaincombx_cmd->setEnabled(false);
        ui->newmaincombx_netcmd->setEnabled(false);
        ui->newmainline_bth->hide();
        ui->newmainline_btw->hide();
        ui->newmainline_netbth->hide();
        ui->newmainline_netbtw->hide();
        ui->newlabel_40->hide();
        ui->newlabel_41->hide();
        ui->newlabel_42->hide();
        ui->newlabel_43->hide();
        ui->newmaincombx_dvwidth->setEnabled(true);
        ui->newmaincombx_netwidth->setEnabled(true);
    }
    else
    {
        notlabprtflag = false;
        ui->newmaincombx_cmd->setEnabled(true);
        ui->newmaincombx_netcmd->setEnabled(true);
        ui->newmainline_bth->show();
        ui->newmainline_btw->show();
        ui->newmainline_netbth->show();
        ui->newmainline_netbtw->show();
        ui->newlabel_40->show();
        ui->newlabel_41->show();
        ui->newlabel_42->show();
        ui->newlabel_43->show();
        ui->newmaincombx_dvwidth->setEnabled(false);
        ui->newmaincombx_netwidth->setEnabled(false);
        labelcmd = map[PRT_CONF_LABELPRTTYPE].toInt();
        ui->newmaincombx_cmd->setCurrentIndex(prttype);
    }

    ui->newmainrdbtn_com->setEnabled(notlabprtflag);
    ui->newmainrdbtn_lpt->setEnabled(notlabprtflag);

    switch (type) {
    case 0:
        ui->newmaincombx_com->setCurrentText(map[PRT_CONF_COM].toString());
        ui->newmaincombx_bdl->setCurrentText(map[PRT_CONF_BAUDRATE].toString());
        ui->newmaincombx_control->setCurrentText(map[PRT_CONF_FLOWCONTROL].toString());
        ui->newmaincombx_data->setCurrentText(map[PRT_CONF_DATABITS].toString());
        ui->newmaincombx_jy->setCurrentText(map[PRT_CONF_PARITY].toString());
        ui->newmaincombx_stop->setCurrentText(map[PRT_CONF_STOPBITS].toString());
        ui->newmaincombx_dvwidth->setCurrentText(map[PRT_CONF_PAPERWIDTH].toString());
        ui->newmainrdbtn_com->setChecked(true);
        InitSettingWidget(SET_PRT_COM);
        break;
    case 1:
        ui->newmainline_lpt->setText(map[PRT_CONF_LPTNAME].toString());
        ui->newmaincombx_lptwidth->setCurrentText(map[PRT_CONF_PAPERWIDTH].toString());
        ui->newmainrdbtn_lpt->setChecked(true);
        InitSettingWidget(SET_PRT_LPT);
        break;
    case 3:
        ui->newmainline_ip->setText(map[PRT_CONF_IP].toString());
        if(prttype != 1)
        {
            ui->newmaincombx_dvwidth->setCurrentText(map[PRT_CONF_PAPERWIDTH].toString());
        }
        else
        {
            ui->newmainline_netbth->setText(map[PRT_CONF_HIGH].toString());
            ui->newmainline_netbtw->setText(map[PRT_CONF_WIGTH].toString());
            ui->newmaincombx_netcmd->setCurrentIndex(map[PRT_CONF_LABELPRTTYPE].toInt());
        }
        ui->newmainrdbtn_net->setChecked(true);
        InitSettingWidget(SET_PRT_NET);
        break;
    case 4:
        ui->newmainline_name->setText(map[PRT_CONF_NAME].toString());
        ui->newmaincombx_name->setCurrentText(map[PRT_CONF_NAME].toString());
        if(prttype != 1)
        {
            ui->newmaincombx_dvwidth->setCurrentText(map[PRT_CONF_PAPERWIDTH].toString());
        }
        else
        {
            ui->newmainline_bth->setText(map[PRT_CONF_HIGH].toString());
            ui->newmainline_btw->setText(map[PRT_CONF_WIGTH].toString());
            ui->newmaincombx_cmd->setCurrentIndex(map[PRT_CONF_LABELPRTTYPE].toInt());
        }
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
        break;
    default:
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
        break;
    }
}

void NewMainForm::InitUserSetting()
{

}

void NewMainForm::InitPrtSetting()
{
    QStringList list = PosPrtPool::prtlist();

    ui->newmaincombx_prttype->clear();

    if (list.size() == 0)
    {
        QLOG_WARN() << "Not Found Prts";
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
        return ;
    }

    QString curr = list[0];

    foreach (auto var, list) {
        ui->newmaincombx_prttype->addItem(var);
    }

    DoGetPrtSetting(curr);
}

void NewMainForm::DoGetPrtSetting(QString curr)
{
    ui->newmaincombx_prttype->setCurrentText(curr);

    if(!PosPrtPool::GetPrtType(curr, _prttype))
    {
        QLOG_ERROR() << "NewMainForm::InitPrtSetting::PosPrtPool::GetPrtType failed";
        return ;
    }

    QLOG_INFO() << "_prttype" << _prttype;

    QVariantMap map;

    if(!PosPrtPool::GetPrtConfig(curr, map))
    {
        QLOG_ERROR() << "NewMainForm::InitPrtSetting::PosPrtPool::GetPrtConfig failed";
        return ;
    }

    QLOG_INFO() << "map" << map;

    SettingWidgetWithConf(_prttype, map);

    QString Stallsid;

    if(PosPrtPool::GetPrtStalls(curr, Stallsid))
    {
        //查询档口名称
    }
    else
    {
        QLOG_ERROR() << "NewMainForm::InitPrtSetting::PosPrtPool::GetPrtStalls failed";
    }
}

void NewMainForm::InitOrderSetting()
{
    QString confpath = qApp->applicationDirPath() + "/" + CONFIG_NAME;
    int autoconf = QSettings(confpath, QSettings::IniFormat).value(INI_AUTOCONFIRM,1).toInt();
    int timeout = QSettings(confpath, QSettings::IniFormat).value(INI_DELEORDERTIMER,1).toInt();

    if(autoconf == 1)
        ui->newmainrdbtn_auto->setChecked(true);
    else
        ui->newmainrdbtn_self->setChecked(true);

    ui->newmaincombx_del->setCurrentIndex(timeout/12 - 1);
}

void NewMainForm::InitSettingWidget(QString type)
{
    foreach (auto var, _prtsetting_widget) {
        if(var->property("type").toString().compare(type, Qt::CaseInsensitive) == 0)
            var->show();
        else
            var->hide();
    }
}

void NewMainForm::on_PrtSet_toggled(bool checked)
{
    if(checked)
    {
        QRadioButton *pBtn = (QRadioButton*)sender();
        QString type = pBtn->property("type").toString();
        InitSettingWidget(type);
    }
}

void NewMainForm::on_newmaincombx_prttype_currentIndexChanged(int index)
{
    ui->newmainlabel_errmsg->clear();

    QString prtname = ui->newmaincombx_prttype->currentText();

    DoGetPrtSetting(prtname);

}

void NewMainForm::on_newmaintbwgt_tabBarClicked(int index)
{
    ui->newmainlabel_errmsg->clear();

    if(index == 0)
    {
        InitOrderSetting();
    }
    else if(index == 1)
    {
        InitPrtSetting();
    }
}

bool NewMainForm::GetPrtConfig(QString &prtconfig)
{
    QVariantMap map;

    int type = -1;

    if(ui->newmainrdbtn_dv->isChecked())
        type = 4;
    if(ui->newmainrdbtn_net->isChecked())
        type = 3;
    if(ui->newmainrdbtn_lpt->isChecked())
        type = 1;
    if(ui->newmainrdbtn_com->isChecked())
        type = 0;

    if(type == -1)
    {
        ui->newmainlabel_errmsg->setText(QString::fromUtf8("\xE8\xAF\xB7\xE9\x80\x89\xE6\x8B\xA9\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA\xE7\xB1\xBB\xE5\x9E\x8B"));
        return false;
    }

    ui->newmainlabel_errmsg->clear();


    map[PRT_CONF_TYPE] = type;

    switch (type) {
    case 0:
        map.insert(PRT_CONF_COM, ui->newmaincombx_com->currentText());
        map.insert(PRT_CONF_BAUDRATE, ui->newmaincombx_bdl->currentText());
        map.insert(PRT_CONF_FLOWCONTROL, ui->newmaincombx_control->currentText());
        map.insert(PRT_CONF_DATABITS, ui->newmaincombx_data->currentText());
        map.insert(PRT_CONF_PARITY, ui->newmaincombx_jy->currentText());
        map.insert(PRT_CONF_STOPBITS, ui->newmaincombx_stop->currentText());
        map.insert(PRT_CONF_PAPERWIDTH, ui->newmaincombx_dvwidth->currentText());
        break;
    case 1:
        map.insert(PRT_CONF_PARITY,ui->newmainline_lpt->text());
        map.insert(PRT_CONF_PAPERWIDTH,ui->newmaincombx_lptwidth->currentText());
        break;
    case 3:
        map.insert(PRT_CONF_IP,ui->newmainline_ip->text());
        if(_prttype != 1)
            map.insert(PRT_CONF_PAPERWIDTH,ui->newmaincombx_dvwidth->currentText());
        else
        {
            map.insert(PRT_CONF_HIGH,ui->newmainline_netbth->text());
            map.insert(PRT_CONF_WIGTH,ui->newmainline_netbtw->text());
            map.insert(PRT_CONF_LABELPRTTYPE, ui->newmaincombx_netcmd->currentIndex());
        }
        break;
    case 4:
        map.insert(PRT_CONF_NAME,ui->newmainline_name->text());
        if(_prttype != 1)
            map.insert(PRT_CONF_PAPERWIDTH,ui->newmaincombx_dvwidth->currentText());
        else
        {
            map.insert(PRT_CONF_HIGH,ui->newmainline_bth->text());
            map.insert(PRT_CONF_WIGTH,ui->newmainline_btw->text());
            map.insert(PRT_CONF_LABELPRTTYPE, ui->newmaincombx_cmd->currentIndex());
        }
        break;
    default:
        return false;
    }

    QJsonObject obj = QJsonObject::fromVariantMap(map);

    prtconfig = QString(QJsonDocument(obj).toJson(QJsonDocument::Compact));

    return true;
}

void NewMainForm::on_newmainbtn_prtsave_clicked()
{    
    if(ui->newmaincombx_prttype->count() == 0)
    {
        ui->newmainlabel_errmsg->setText(QString::fromUtf8("\xE8\xAF\xB7\xE5\x85\x88\xE6\xB7\xBB\xE5\x8A\xA0\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA"));
        return ;
    }

    ui->newmainlabel_errmsg->clear();

    QVariantMap map;

    QString prtname = ui->newmaincombx_prttype->currentText();
    QString prtconfig;
    QString stallsname;

    if(_prttype == 2)
        stallsname = ui->newmaincmbox_stalls->currentText();
    else
        stallsname = "";

    if(!GetPrtConfig(prtconfig))
        return ;

    QLOG_DEBUG() << stallsname;

    map.insert(EVENT_KEY_PRTID, prtname);
    map.insert(EVENT_KEY_PRTNAME, prtname);
    map.insert(EVENT_KEY_PRTTYPE, _prttype);
    map.insert(EVENT_KEY_PRTCONFIG, prtconfig);
    map.insert(DEVENT_KEY_PRTSTALLS, stallsname);


    POSTEVENTTYPE(PosEvent::s_change_prt, map, QVariantMap);
}

void NewMainForm::on_newmainbtn_prtadd_clicked()
{
    _prttype = -1;
    _prttypeForm->show();
}

void NewMainForm::on_newmainbtn_prtdel_clicked()
{
    if(ui->newmaincombx_prttype->count() == 0)
    {
        ui->newmainlabel_errmsg->setText(QString::fromUtf8("\xE8\xAF\xB7\xE5\x85\x88\xE6\xB7\xBB\xE5\x8A\xA0\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA"));
        return ;
    }

    ui->newmainlabel_errmsg->clear();

    QString prtname = ui->newmaincombx_prttype->currentText();

    ui->newmaincombx_prttype->removeItem(ui->newmaincombx_prttype->currentIndex());

    QLOG_DEBUG() << "prtname" << prtname;

    DEFAULTPOSTEVENT(PosEvent::s_delete_prt, prtname);
}

void NewMainForm::on_newmaincombx_name_currentIndexChanged(int index)
{
    ui->newmainline_name->setText(ui->newmaincombx_name->currentText());
}

void NewMainForm::on_newmainvtn_ordersave_clicked()
{
    int autoconf = 0;

    if(ui->newmainrdbtn_auto->isChecked())
        autoconf = 1;

    NewMainFormDataProcess::SetOrderConfig(QString::number(autoconf), QString::number((ui->newmaincombx_del->currentIndex() + 1)*12));
}

void NewMainForm::on_newmainbtn_down_clicked()
{
    int num = ui->newmaintablewidget_order->height()/36;

    int page =  _curr_page_num/(num - 1) ;

    if(_curr_page_num%(num - 1) != 0)
        ++ page;

    if(_curr_page < page)
    {  
        if(_curr_page == page - 1 && _curr_page_num%(num - 1) != 0)
        {
            ui->newmaintablewidget_order->viewport()->setFixedHeight(_curr_page_num%(num - 1) * 36);
        }
        ui->newmaintablewidget_order->verticalScrollBar()->setValue(_curr_page*(num - 1));
        ++ _curr_page;
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(page));
    }
}

void NewMainForm::on_newmainbtn_up_clicked()
{
    int num = ui->newmaintablewidget_order->height()/36;

    int page =  _curr_page_num/(num - 1) ;

    if(_curr_page_num%(num - 1) != 0)
        ++ page;

    if(_curr_page > 1)
    {
        -- _curr_page;
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(page));
        ui->newmaintablewidget_order->verticalScrollBar()->setValue((_curr_page - 1)*(num - 1));
        ui->newmaintablewidget_order->viewport()->setFixedHeight((num - 1) * 36);
    }
}

void NewMainForm::on_newmainbtn_jump_clicked()
{
    int num = ui->newmaintablewidget_order->height()/36;
    int page = ui->newmainline_page->text().toInt();

    int tmppage =  _curr_page_num/(num - 1) ;

    if(_curr_page_num%(num - 1) != 0)
        ++ tmppage;

    if(page > 0 && page <= tmppage && page != _curr_page)
    {
        if(page == tmppage && _curr_page_num%(num - 1) != 0)
        {
            ui->newmaintablewidget_order->viewport()->setFixedHeight(_curr_page_num%(num - 1) * 36);
        }
        else
        {
            ui->newmaintablewidget_order->viewport()->setFixedHeight((num - 1) * 36);
        }
        _curr_page = page;
        ui->newmaintablewidget_order->verticalScrollBar()->setValue((_curr_page-1)*(num - 1));
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(tmppage));
    }
}

void NewMainForm::on_newmainbtn_hide_clicked()
{
    hide();
    ui->newmainline_serach->clear();
    _padForm->hide();
    DEFAULTPOSTEVENT(PosEvent::s_show_float, "");
}

void NewMainForm::on_newmainbtn_findclean_clicked()
{
    _padForm->hide();
    _resultForm->hide();
    ui->newmainline_serach->setText("");
}
