#include "MainForm.h"
#include "ui_MainForm.h"

#include <QTimer>
#include <QPrinterInfo>

#include "QsLog/QsLog.h"
#include "NotifyForm.h"
#include "NetWork/UdpNotifier.h"
#include "../../fmTakeaway_db/FmTakeaway_db.h"
#include "Util/BillsManger.h"
#include "Util/IniDataManger.h"
#include "PreDefined.h"
#include "OperaForm.h"
#include "DetailsForm.h"
#include "Util/Tools.h"
#include "DeliversForm.h"
#include "../fmTakeaway_printer/Fmtakeaway_printer.h"
#include "Util/IniDataManger.h"
#include <QDesktopWidget>
#include <QVariant>
#include "XCBOperate.h"
#include "DClasses/Database.h"

MainForm::MainForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainForm),
    m_refundCnt(0),
    m_unmateCnt(0)
{
    uint a = 0xb5416260;
    QLOG_INFO() << a << QString::number(a, 16) << "=======-------";
    ui->setupUi(this);
    _InitUI();
    _InitData();

    /*connect(&UdpNotifier::Instance(), &UdpNotifier::beSlave, this, &MainForm::onBeSlave);*/
    connect(OBJPTR(BillsManger), SIGNAL(error(QString,BillsManger::ErrorType)),
            this, SLOT(onError(QString,BillsManger::ErrorType)));
    connect(OBJPTR(BillsManger), SIGNAL(pullOrdersError(QString,BillsManger::ErrorType)),
            this, SLOT(onError(QString,BillsManger::ErrorType)));
    connect(OBJPTR(BillsManger), SIGNAL(sucessful(QString, QString)), this, SLOT(onSucessful(QString, QString)));
    connect(OBJPTR(BillsManger), SIGNAL(OrderTableChanged(int,int,OrderObject*)),
            this, SLOT(onOrderTableChanged(int,int,OrderObject*)));
    connect(OBJPTR(BillsManger), SIGNAL(CLearTable()),this, SLOT(on_ClearTable()));
    connect(ui->btnNew, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));
    connect(ui->btnMake, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));
    connect(ui->btnSend, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));
    connect(ui->btnFinsh, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));
    connect(ui->btnOther, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));
    connect(ui->btnBook, SIGNAL(clicked()), this, SLOT(onTableBtnClicked()));
    connect(ui->tableNew, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onTableItemClicked(QTableWidgetItem*)));
    connect(ui->tableMake, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onTableItemClicked(QTableWidgetItem*)));
    connect(ui->tableSend, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onTableItemClicked(QTableWidgetItem*)));
    connect(ui->tableFinsh, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onTableItemClicked(QTableWidgetItem*)));
    connect(ui->tableOther, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onTableItemClicked(QTableWidgetItem*)));
    connect(ui->tableBook, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(onTableItemClicked(QTableWidgetItem*)));
    connect(&m_timeTimer, SIGNAL(timeout()), this, SLOT(onTimeTimerOut()));
    connect(OBJPTR(BillsManger), SIGNAL(ChangeUiStatus(QString)), this, SLOT(onChangeStatus(QString)));

    connect(this, SIGNAL(operatorChanged(FmTakeaway_db::OperatorInfo)),
            OBJPTR(BillsManger), SLOT(onOperatorChanged(FmTakeaway_db::OperatorInfo)));
    qRegisterMetaType<FmTakeaway_db::OperatorInfo>("FmTakeaway_db::OperatorInfo");

    // 登录
    //OBJREF(BillsManger).Login();
    QDesktopWidget w;
    QRect rc = w.availableGeometry();
    setGeometry((rc.width() - width()) / 2, (rc.height() - height()) / 2, width(), height());
}

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

void MainForm::onBeSlave()
{
    QLOG_TRACE() << QString("%1::%2").arg("MainForm").arg(__FUNCTION__);
    //ui->btnMsState->setText(STATEBTN_NAME_NUSE);
    //ui->btnMsState->setChecked(false);
}

void MainForm::onError(const QString &msg, BillsManger::ErrorType type)
{
    QLOG_TRACE() << QString("%1::%2").arg("MainForm").arg(__FUNCTION__);
    if(m_bexistDetailsForm)
    {
        return;
    }

    emit ntFormClose();
    QString err = OBJREF(BillsManger).LastError();
    if (!err.isEmpty()) {
        err = "," + err;
    }
    NotifyForm ntForm(msg + err, NotifyForm::ERROR, this);
    XCBOperate oper;
    oper.update(ntForm.winId());
    ntForm.exec();
    m_bLoading = false;

    // 网络错误
    if(BillsManger::SOCKET==type)
    {
        qApp->quit();
    }

    return;
}

void MainForm::onPullOrdersError(const QString &msg, BillsManger::ErrorType type)
{
    QLOG_TRACE() << QString("%1::%2").arg("MainForm").arg(__FUNCTION__);
    if(m_bexistDetailsForm || m_bLoading)
    {
        return;
    }

    OBJREF(BillsManger).StopPullOrder();
    NotifyForm ntForm(msg, NotifyForm::ERROR, this);
    XCBOperate oper;
    oper.update(ntForm.winId());
    ntForm.exec();
    qApp->quit();
}

void MainForm::onSucessful(const QString &msg, const QString &extra)
{
    QLOG_TRACE() << QString("%1::%2").arg("MainForm").arg(__FUNCTION__);
    if(m_bexistDetailsForm)
    {
        return;
    }
    emit ntFormClose();
    NotifyForm ntForm(msg, NotifyForm::OK, this);
    if (!extra.isEmpty()) {
        ntForm.SetExtraInfo(extra);
    }
//    ntForm.SetAutoClose(OBJREF(IniDataManger).GetNotifyAcceptTimer());
    XCBOperate oper;
    oper.update(ntForm.winId());
    ntForm.exec();
    m_bLoading = false;
}

void MainForm::onOrderTableChanged(int last, int curr, OrderObject *orderObj)
{
    QLOG_TRACE() << QString("%1::%2").arg("MainForm").arg(__FUNCTION__);

    _SetTablesSortingEnable(false);
    QTableWidget *table;
    // 旧订单需要在原表中先删除
    table = _GetTableByVID(last);

    if (table) {
        for(int i=0; i<table->rowCount(); i++) {
            if(!table->item(i, 1)->text().compare(orderObj->order_id)) {
                qDebug()<<table->objectName()<<"222222";
                table->removeRow(i);
                QRichButton *btn = _GetTableBtnByVID(last);
                QString text;
                if(0==table->rowCount()) {
                    text = QString("%1").arg(btn->property("name").toString());
                    // 新订单栏目里为空
                    if (last == TABLE_VID_SHIPSELF || last == TABLE_VID_CONFIRM_MATE || table == ui->tableOther) {
                        emit floatStopBlink();
                        btn->setCounter(0);
                        btn->setEnableRich(false);
                    }
                }
                else {
                    text = QString("%1(%2)").arg(btn->property("name").toString()).arg(table->rowCount());
                    if (isVisible()) {
                        emit floatStopBlink();
                    }
                }
                btn->setText(text);
                btn->setCounter(table->rowCount());
                QLOG_INFO() << QString("delete order[%1] from table[%2]!").arg(orderObj->order_id).arg(table->objectName());
            }
        }
    }
    else {
        if (TABLE_VID_NO_DRIVER != last) {
            QLOG_INFO() << "unknonwn order status: " << orderObj->order_id;
        }
    }

    table = _GetTableByVID(curr);

    if (TABLE_VID_NO_DRIVER != curr && !table) {
        QLOG_INFO() << "unknonwn order status: " << orderObj->order_id;
        return;
    }

    int crtIndex = 0;
    table->insertRow(crtIndex);

    QLabel *channelWidget = new QLabel(orderObj->channelName + QString("(#%1)").arg(orderObj->order_index));
    channelWidget->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    QString channelColor = OBJREF(IniDataManger).GetChannelColor(orderObj->channel);
    channelWidget->setStyleSheet("QLabel {color:" + channelColor + "; font-size: 10pt; font-weight: bold;}");
    table->setCellWidget(crtIndex, 0, channelWidget);

    QTableWidgetItem *item0 = new QTableWidgetItem();
    item0->setCheckState(Qt::Checked);
    table->setItem(crtIndex, 0, item0);  // 渠道
    QTableWidgetItem *item1 = new QTableWidgetItem(orderObj->order_id);
    item1->setTextAlignment(Qt::AlignCenter);
    table->setItem(crtIndex, 1, item1);  // 订单ID
    QTableWidgetItem *item2 = new QTableWidgetItem(UnitConver(orderObj->shop_fee));
    item2->setTextAlignment(Qt::AlignCenter);
    table->setItem(crtIndex, 2, item2);  // 金额
    QTableWidgetItem *item3 = new QTableWidgetItem(orderObj->customer);
    item3->setTextAlignment(Qt::AlignCenter);
    table->setItem(crtIndex, 3, item3);  // 姓名
    QTableWidgetItem *item4 = new QTableWidgetItem(orderObj->phone);
    item4->setTextAlignment(Qt::AlignCenter);
    table->setItem(crtIndex, 4, item4);  // 联系方式

    if (curr == TABLE_VID_RESERVATION) {
        QTableWidgetItem *item5 = new QTableWidgetItem(QDateTime::fromTime_t(orderObj->delivery_time).toString("MM-dd hh:mm"));
        item5->setTextAlignment(Qt::AlignCenter);
        table->setItem(crtIndex, 5, item5);  // Deliver time
    }
    else {
        QTableWidgetItem *item5 = new QTableWidgetItem(QDateTime::fromTime_t(orderObj->create_time).toString("MM-dd hh:mm"));
        item5->setTextAlignment(Qt::AlignCenter);
        table->setItem(crtIndex, 5, item5);  // 下单时间
    }
    int indexStatus=6;
    switch(curr) {
    case TABLE_VID_RESERVATION:
    case TABLE_VID_SHIPSELF:
    case TABLE_VID_MAKING:
    case TABLE_VID_SELF_MAKING:
    case TABLE_VID_CONFIRM_MATE:
    case TABLE_VID_SHIPING:
    case TABLE_VID_SELF_SHIPING: {
        QWidget *pWdg = new QWidget(table);
        QHBoxLayout *hly = new QHBoxLayout(pWdg);
        QPushButton * pBtn = new QPushButton();
        QPixmap btnMap(":/images/btnTable_normal.png");
        pBtn->setFixedSize(btnMap.size());
        pBtn->setFocusPolicy(Qt::NoFocus);
        pBtn->setObjectName("tmpBtn");
        pBtn->setText(GetOperaBtnNameByVID(curr));
        QString qss = GetOperaBtnStyleByVID(curr, orderObj->channel);
        pBtn->setStyleSheet(qss);
        pBtn->setProperty(OPERABTN_PROPERTY_NAME, orderObj->order_id);
//        pBtn->setProperty("item", item1);
        connect(pBtn, SIGNAL(clicked()), this, SLOT(onOperaBtnClicked()));
        hly->addWidget(pBtn);
        hly->setMargin(0);
        pWdg->setLayout(hly);
        table->setCellWidget(crtIndex,6,pWdg); // 操作

        if((ORDERSTATUS_SHIPPING == orderObj->status) && !OBJREF(IniDataManger).GetIsExistBtnComplete())
        {
            pBtn->setEnabled(false);
        }
        indexStatus=7;
    }
        break;
    case TABLE_VID_REFUND:
    case TABLE_VID_SELF_REFUND:
    case TABLE_VID_PENDING:
    case TABLE_VID_SELF_PENDING: {
        QTableWidgetItem *item7 = new QTableWidgetItem(orderObj->status_desc);
        item7->setTextAlignment(Qt::AlignCenter);
        table->setItem(crtIndex, 6, item7);  // Order status description
        indexStatus=7;
        break;
    }
    default: break;
    }

    //判断订单是否成功写入POS，失败显示提示图标
    if(!Database::getInstance().isPosWriteOK(orderObj->order_id)){
        QLabel *label = new QLabel();
        label->setPixmap(QPixmap(":/images/write_failed.png"));
        label->setAlignment(Qt::AlignCenter);
        table->setCellWidget(crtIndex, indexStatus, label);
    }


    //! Tab button
    QRichButton *btn = _GetTableBtnByVID(curr);
    QString text = QString("%1(%2)").arg(btn->property("name").toString()).arg(table->rowCount());
    btn->setText(text);

    if ((last == TABLE_VID_REFUND || last == TABLE_VID_SELF_REFUND)
            && (curr != TABLE_VID_REFUND && curr != TABLE_VID_REFUND)
            && orderObj->status != ORDERSTATUS_REFUND) {
        --m_refundCnt;
    }

    if (last == TABLE_VID_CONFIRM_MATE && curr != last) {
        --m_unmateCnt;
    }
    else if (curr == TABLE_VID_CONFIRM_MATE) {
        ++m_unmateCnt;
    }

    if (TABLE_VID_SHIPSELF == curr || TABLE_VID_REFUND == curr || TABLE_VID_SELF_REFUND == curr) {
        if (curr != TABLE_VID_SHIPSELF && orderObj->status == ORDERSTATUS_REFUND) {
            ++m_refundCnt;
        }
        else {
            btn->setEnableRich(true);
        }
    }

    btn->setCounter(table->rowCount());

    if (m_refundCnt > 0) {
        ui->btnOther->setEnableRich(true);
        emit floatStartBlink(TABLE_VID_REFUND);
    }
    else {
        ui->btnOther->setEnableRich(false);
        ui->btnOther->setCounter(0);
        m_refundCnt = 0;
    }

    QLOG_INFO() << QString("insert order[%1] to table[%2]").arg(orderObj->order_id).arg(table->objectName());

    QLOG_INFO() << "currt" << curr;
    if(TABLE_VID_MAKING == curr  || TABLE_VID_SELF_MAKING == curr )
    {
        emit floatStartBlink(curr);
    }

    if(TABLE_VID_MAKING == curr || TABLE_VID_CONFIRM_MATE == curr || TABLE_VID_SHIPSELF == curr) {
        if (TABLE_VID_SHIPSELF == curr && orderObj->channel != CHANNEL_ID_ELE) {
            OBJREF(BillsManger).ProcOrders(OPERABTN_NAME_REJECT,
                                               orderObj->order_id,
                                               ORDERREJECT_NO_SHIP);
            QLOG_WARN() << "order " + orderObj->order_id + " auto rejected.";
        }
        else {
            if (!isVisible() || TABLE_VID_SHIPSELF == curr || TABLE_VID_CONFIRM_MATE == curr) {
                emit floatStartBlink(curr);
            }
        }
    }

    _SetTablesSortingEnable(true);
    return;
}

void MainForm::onFloatMoved(QPoint pos)
{
    m_floatPos = pos;
}

void MainForm::_InitUI()
{
    this->setWindowFlags(windowFlags()/* | Qt::WindowStaysOnTopHint |Qt::FramelessWindowHint*/);
    //this->showFullScreen();
    m_size = this->size();

    m_sysTray.show();

    //ui->btnMsState->setText(STATEBTN_NAME_USE);
//    ui->labMsState->hide();
//    ui->btnMsState->hide();
//    ui->btnChangeMsState->hide();
//    ui->horizontalLayout->removeItem(ui->hsMsState);

//    ui->btnCurOpe->setText(CUROPEBTN_DEFAULT);
//    ui->btnCurOpe->setChecked(false);

    // 初始化打印机选项
    QString iniPrinterName = OBJREF(IniDataManger).GetPrinterName();
    QStringList printerList;
    QList<QPrinterInfo> printers = QPrinterInfo::availablePrinters();
    foreach(QPrinterInfo p, printers) {
        printerList << p.printerName();
    }

    for(int i=0; i<printerList.count(); i++)
    {
        QString name = (QString)printerList.at(i);
        ui->cbxPrinter->insertItem(i, name);
        if(!name.compare(iniPrinterName))
        {
            ui->cbxPrinter->setCurrentIndex(i);
        }
    }

    ui->btnNew->setChecked(false);
//    ui->btnNew->setEnabled(false);
    ui->btnMake->setChecked(true);
    ui->btnMake->setEnabled(false);
    ui->tableNew->hide();
    ui->tableMake->show();
    ui->tableSend->hide();
    ui->tableFinsh->hide();
    ui->tableOther->hide();
    ui->tableBook->hide();

    // 是否有接单员
    if(!OBJREF(IniDataManger).GetIsExistOperator())
    {
//        ui->btnCurOpe->hide();
//        ui->labCurOpe->hide();
//        ui->btnChangeCurOpe->hide();
//        ui->horizontalLayout->removeItem(ui->hsCurOpe);
    }

    //
    //ui->labPrinter->hide();
    //ui->cbxPrinter->hide();
    //ui->btnTestPrint->hide();

    ui->lab_status->setText("<font color='#ff0000'>未登录</font>");

    // 初始化表头
    int tableWidth = this->width() - 50;

    ui->tableBook->setColumnWidth(0, tableWidth*3/21);
    ui->tableBook->setColumnWidth(1, tableWidth*3/21);
    ui->tableBook->setColumnWidth(2, tableWidth*1.5/21);
    ui->tableBook->setColumnWidth(3, tableWidth*3/21);
    ui->tableBook->setColumnWidth(4, tableWidth*2.5/21);
    ui->tableBook->setColumnWidth(5, tableWidth*2.5/21);
    ui->tableBook->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableBook->horizontalHeader()->setFixedHeight(40);
    ui->tableBook->horizontalHeader()->setStretchLastSection(true);

    ui->tableNew->setColumnWidth(0, tableWidth*3/21);
    ui->tableNew->setColumnWidth(1, tableWidth*3/21);
    ui->tableNew->setColumnWidth(2, tableWidth*1.5/21);
    ui->tableNew->setColumnWidth(3, tableWidth*3/21);
    ui->tableNew->setColumnWidth(4, tableWidth*3/21);
    ui->tableNew->setColumnWidth(5, tableWidth*2.5/21);
    ui->tableNew->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableNew->horizontalHeader()->setFixedHeight(40);
    ui->tableNew->horizontalHeader()->setStretchLastSection(true);
    ui->tableMake->setColumnWidth(0, tableWidth*3/21);
    ui->tableMake->setColumnWidth(1, tableWidth*3/21);
    ui->tableMake->setColumnWidth(2, tableWidth*1.5/21);
    ui->tableMake->setColumnWidth(3, tableWidth*3/21);
    ui->tableMake->setColumnWidth(4, tableWidth*3/21);
    ui->tableMake->setColumnWidth(5, tableWidth*2.5/21);
    ui->tableMake->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableMake->horizontalHeader()->setFixedHeight(40);
    ui->tableMake->horizontalHeader()->setStretchLastSection(true);
    ui->tableSend->setColumnWidth(0, tableWidth*3/21);
    ui->tableSend->setColumnWidth(1, tableWidth*3/21);
    ui->tableSend->setColumnWidth(2, tableWidth*1.5/21);
    ui->tableSend->setColumnWidth(3, tableWidth*3/21);
    ui->tableSend->setColumnWidth(4, tableWidth*3/21);
    ui->tableSend->setColumnWidth(5, tableWidth*2.5/21);
    ui->tableSend->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableSend->horizontalHeader()->setFixedHeight(40);
    ui->tableSend->horizontalHeader()->setStretchLastSection(true);
    ui->tableFinsh->setColumnWidth(0, tableWidth*3/21);
    ui->tableFinsh->setColumnWidth(1, tableWidth*4/21);
    ui->tableFinsh->setColumnWidth(2, tableWidth*2/21);
    ui->tableFinsh->setColumnWidth(3, tableWidth*3/21);
    ui->tableFinsh->setColumnWidth(4, tableWidth*3.5/21);
    ui->tableFinsh->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableFinsh->horizontalHeader()->setFixedHeight(40);
    ui->tableFinsh->horizontalHeader()->setStretchLastSection(true);
    ui->tableOther->setColumnWidth(0, tableWidth*3/21);
    ui->tableOther->setColumnWidth(1, tableWidth*3/21);
    ui->tableOther->setColumnWidth(2, tableWidth*1.5/21);
    ui->tableOther->setColumnWidth(3, tableWidth*3/21);
    ui->tableOther->setColumnWidth(4, tableWidth*3/21);
    ui->tableOther->setColumnWidth(5, tableWidth*2.5/21);
    ui->tableOther->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
    ui->tableOther->horizontalHeader()->setFixedHeight(40);
    ui->tableOther->horizontalHeader()->setStretchLastSection(true);
}

void MainForm::_InitData()
{
    m_pos = QPoint(0,0);
    m_anmGeometry = new QPropertyAnimation(this, "geometry");
    m_anmGeometry->setDuration(500);

    m_anmOpacity = new QPropertyAnimation(this, "windowOpacity");
    m_anmOpacity->setDuration(500);

    m_bexistDetailsForm = false;
    m_bLoading = false;
    m_prevTableBtn = ui->btnMake;
    m_prevTable = ui->tableMake;

    m_curtTable = ui->tableMake;

    m_timeTimer.start(1000);
}

void MainForm::_SetTablesSortingEnable(bool bEnable)
{
    QLOG_TRACE() << QString("MainForm::%1").arg(__FUNCTION__);
    ui->tableBook->setSortingEnabled(bEnable);
    ui->tableNew->setSortingEnabled(bEnable);
    ui->tableMake->setSortingEnabled(bEnable);
    ui->tableSend->setSortingEnabled(bEnable);
    ui->tableFinsh->setSortingEnabled(bEnable);
    ui->tableOther->setSortingEnabled(bEnable);
}

QTableWidget *MainForm::_GetTableByVID(int vid)
{
    QTableWidget *table;
    switch(vid)
    {
    case TABLE_VID_RESERVATION:
        table = ui->tableBook;
        break;
    case TABLE_VID_SHIPSELF:
        table = ui->tableNew;
        break;
    case TABLE_VID_MAKING:
    case TABLE_VID_SELF_MAKING:
    case TABLE_VID_CONFIRM_MATE:
        table = ui->tableMake;
        break;
    case TABLE_VID_SHIPING:
    case TABLE_VID_SELF_SHIPING:
        table = ui->tableSend;
        break;
    case TABLE_VID_FINISH:
    case TABLE_VID_SELF_FINISH:
        table = ui->tableFinsh;
        break;
    case TABLE_VID_NO_DRIVER:
        table = 0;
        break;
    default:
        table = ui->tableOther;
        break;
    }
    if (table) {
        QLOG_TRACE() << QString("MainForm::%1[%2->%3]").arg(__FUNCTION__).arg(vid).arg(table->objectName());
    }
    return table;
}

QRichButton *MainForm::_GetTableBtnByVID(int vid)
{
    switch(vid)
    {
    case TABLE_VID_RESERVATION:
        return ui->btnBook;

    case TABLE_VID_SHIPSELF:
        return ui->btnNew;
        break;
    case TABLE_VID_MAKING:
    case TABLE_VID_SELF_MAKING:
    case TABLE_VID_CONFIRM_MATE:
        return ui->btnMake;
        break;
    case TABLE_VID_SHIPING:
    case TABLE_VID_SELF_SHIPING:
        return  ui->btnSend;
        break;
    case TABLE_VID_FINISH:
    case TABLE_VID_SELF_FINISH:
        return  ui->btnFinsh;
        break;
    default:
        return  ui->btnOther;
        break;
    }
}

void MainForm::on_btnHide_clicked()
{
    QLOG_TRACE() << QString("MainForm::%1").arg(__FUNCTION__);

    if(0==m_pos.x())
    {
        m_pos = this->pos();
    }

//    m_anmGeometry->setEasingCurve(QEasingCurve::InQuart);
//    m_anmOpacity->setEasingCurve(QEasingCurve::OutQuart);

//    m_anmGeometry->setStartValue(QRect(m_pos.x(), m_pos.y(), m_size.width(), m_size.height()));
//    m_anmGeometry->setEndValue(QRect(0, 0, 0, 0));
//    m_anmOpacity->setStartValue(1);
//    m_anmOpacity->setEndValue(0);
//    m_anmOpacity->start();
//    m_anmGeometry->start();
//    QEventLoop loop;
//    connect(m_anmGeometry, SIGNAL(finished()), &loop, SLOT(quit()));
//    loop.exec();
    this->hide();

//#ifdef Q_OS_LINUX
//    xcb_connection_t    *c;
//    xcb_intern_atom_reply_t *reply;
//    xcb_atom_t embedAtom;
//    xcb_intern_atom_cookie_t  atom_cookie;
//    char * strAtomName = "_XEMBED_INFO";
//    c = xcb_connect(NULL,NULL);
//    atom_cookie = xcb_intern_atom(c, false, strlen(strAtomName), strAtomName);
//    reply = xcb_intern_atom_reply(c, atom_cookie, 0);
//    embedAtom = reply->atom;
//    free(reply);
//    xcb_delete_property(c, (xcb_window_t)floatWId, embedAtom);
//    xcb_flush(c);
//#endif
    //emit updateXCB(floatWId);
    XCBOperate oper;
    oper.update(floatWId);
    emit floatFormShow();
    return;
}

void MainForm::onShow()
{
    this->show();
//    m_anmGeometry->setEasingCurve(QEasingCurve::OutQuart);
//    m_anmOpacity->setEasingCurve(QEasingCurve::InQuart);
//    m_anmOpacity->setStartValue(0);
//    m_anmOpacity->setEndValue(1);
//    m_anmGeometry->setStartValue(QRect(0, 0, 0, 0));
//    m_anmGeometry->setEndValue(QRect(m_pos.x(), m_pos.y(), m_size.width(), m_size.height()));
//    m_anmOpacity->start();
//    m_anmGeometry->start();
    int self_orders = 0;
    QTableWidget *table = _GetTableByVID(TABLE_VID_SHIPSELF);
    self_orders = table->rowCount();

    if (self_orders == 0 && m_refundCnt == 0 && m_unmateCnt == 0) {
        emit floatStopBlink();
    }
}

void MainForm::onChangeStatus(QString text)
{
    ui->lab_status->setText(text);
}

void MainForm::on_btnChangeCurOpe_clicked()
{
    QLOG_TRACE() << QString("MainForm::%1").arg(__FUNCTION__);
    QList<FmTakeaway_db::OperatorInfo> listOperator;
    FmTakeaway_db::Instance().GetOperatorsInfo(listOperator);
    NotifyForm ntForm(QString("正在查询在班人员..."), NotifyForm::LOADING, this);
    connect(&FmTakeaway_db::Instance(), SIGNAL(successful()), &ntForm, SLOT(accept()));
    connect(&FmTakeaway_db::Instance(), SIGNAL(failed()), &ntForm, SLOT(reject()));
    m_bLoading = true;
    XCBOperate oper;
    oper.update(ntForm.winId());
    if(QDialog::Rejected==ntForm.exec())
    {
        QLOG_WARN() << QString("get operatorsInfo failed.[%1]").arg(FmTakeaway_db::Instance().GetLastError());
        NotifyForm ntForm(QString("数据库连接失败,请重启程序."), NotifyForm::ERROR, this);
        XCBOperate oper;
        oper.update(ntForm.winId());
        ntForm.exec();
        qApp->quit();
        return;
    }

    m_bLoading = false;
    QString strOperators("");
    foreach(FmTakeaway_db::OperatorInfo info, listOperator)
    {
        strOperators.append("["+info.name+"]");
    }
    QLOG_TRACE() << QString("get operatorsInfo sucessful.[%1]").arg(strOperators);

    FmTakeaway_db::OperatorInfo operatorInfo;
    OperaForm operaFrom(listOperator, this);
    if(QDialog::Accepted==operaFrom.exec())
    {
        operatorInfo = operaFrom.GetOperator();
        QLOG_INFO() << QString("selected operator.[%1,%2,%3,%4]").arg(operatorInfo.id).arg(operatorInfo.name).arg(operatorInfo.shiftId).arg(operatorInfo.shiftName);

//        ui->btnCurOpe->setText(operatorInfo.name);
//        ui->btnCurOpe->setChecked(true);
//        ui->btnCurOpe->setProperty(PROPERTY_BTNSELECT_ID, operatorInfo.id);
//        ui->btnCurOpe->setProperty(PROPERTY_BTNSELECT_SHIFTID, operatorInfo.shiftId);
//        ui->btnCurOpe->setProperty(PROPERTY_BTNSELECT_SHIFTNAME, operatorInfo.shiftName);
//        ui->btnCurOpe->adjustSize();

        emit operatorChanged(operatorInfo);
    }
}

void MainForm::on_btnChangeMsState_toggled(bool bChecked)
{
    QLOG_TRACE() << __FUNCTION__ << bChecked;

//    ui->btnMsState->setChecked(bChecked);
    if(bChecked)
    {
//        ui->btnMsState->setText(STATEBTN_NAME_USE);
        UdpNotifier::Instance().NotifyOther();
    }else
    {
//        ui->btnMsState->setText(STATEBTN_NAME_NUSE);
    }
    return;
}

void MainForm::on_btnTestPrint_clicked()
{
    QLOG_TRACE() << __FUNCTION__;
    QString str("这是一个测试页\r\n看到此页说明打印机正常.");
    FmTakeaway_printer::Instance().TestPrint(OBJREF(IniDataManger).GetPrinterName(), str);
}

void MainForm::onTableBtnClicked()
{
    QPushButton *targetBtn = (QPushButton*)this->sender();
    QString tableName = targetBtn->property("tableName").toString();
    QTableWidget *targetTable = this->findChild<QTableWidget*>(tableName);
    m_curtTable = targetTable;

    QLOG_TRACE() << __FUNCTION__ << QString("%1->[enable|disChecked] %2->[hide] %3->[disEnable|checked] %4->[show]")
                    .arg(m_prevTableBtn->objectName()).arg(m_prevTable->objectName())
                    .arg(targetBtn->objectName()).arg(targetTable->objectName());

    m_prevTableBtn->setEnabled(true);
    m_prevTableBtn->setChecked(false);
    m_prevTable->hide();

    targetBtn->setEnabled(false);
    m_prevTableBtn = targetBtn;

    targetTable->show();
    m_prevTable = targetTable;

    return;
}

bool MainForm::_CheckState()
{
//    if(!ui->btnMsState->text().compare(STATEBTN_NAME_NUSE))
//    {
//        NotifyForm ntForm(QString("当前为不可操作状态!"), NotifyForm::ERROR, this);
//        ntForm.exec();
//        return false;
//    }else if(OBJREF(IniDataManger).GetIsExistOperator())
//    {
//        if(!ui->btnCurOpe->text().compare(CUROPEBTN_DEFAULT))
//        {
//            NotifyForm ntForm(QString("请在软件右下角选择收银员!"), NotifyForm::ERROR, this);
//            ntForm.exec();
//            return false;
//        }else
//        {
//            QList<FmTakeaway_db::OperatorInfo> listOperator;
//            FmTakeaway_db::Instance().GetOperatorsInfo(listOperator);
//            NotifyForm ntForm("正在查询在班人员...", NotifyForm::LOADING, this);
//            connect(&FmTakeaway_db::Instance(), SIGNAL(successful()), &ntForm, SLOT(accept()));
//            connect(&FmTakeaway_db::Instance(), SIGNAL(failed()), &ntForm, SLOT(reject()));
//            m_bLoading = true;
//            if(QDialog::Rejected==ntForm.exec())
//            {
//                QLOG_WARN() << QString("get operatorsInfo failed.[%1]").arg(FmTakeaway_db::Instance().GetLastError());
//                NotifyForm ntForm(QString("数据库连接失败,请重启程序."), NotifyForm::ERROR, this);
//                ntForm.exec();
//                qApp->quit();
//                return false;
//            }else
//            {
//                bool bexist = false;
//                foreach(FmTakeaway_db::OperatorInfo info, listOperator)
//                {
//                    if(!info.name.compare(ui->btnCurOpe->text()))
//                    {
//                        emit operatorChanged(info);
//                        bexist = true;
//                        break;
//                    }
//                }
//                if(!bexist)
//                {
//                   QLOG_WARN() << QString("current operator not exist.[%1]").arg(ui->btnCurOpe->text());
//                   NotifyForm ntForm(QString("当前操作员已交班,请重新选择操作员."), NotifyForm::ERROR, this);
//                   ntForm.exec();
//                   return false;
//                }
//            }
//            m_bLoading = false;
//        }
//    }

    return true;
}

void MainForm::onOperaBtnClicked()
{
    QLOG_TRACE() << __FUNCTION__;
    if(!_CheckState()) {
        return;
    }
    QPushButton *targetBtn = (QPushButton*)sender();

    DeliverObject deliverObj;
//    if(!targetBtn->text().compare(OPERABTN_NAME_CONFIRM))
//    {
//        NotifyForm ntForm0(NTFORM_LOADING, NotifyForm::LOADING, this);
//        connect(OBJPTR(BillsManger), SIGNAL(pullDeliversSucessful(QString)), &ntForm0, SLOT(accept()));
//        connect(OBJPTR(BillsManger), SIGNAL(pullDeliversError(QString,BillsManger::ErrorType)),
//                &ntForm0, SLOT(reject()));
//        OBJREF(BillsManger).PullDelivers();
//        if(QDialog::Accepted==ntForm0.exec())
//        {
//            QList<DeliverObject> tmpDelivers;
//            tmpDelivers = OBJREF(BillsManger).GetDelivers();
//            DeliversForm devForm(tmpDelivers, this);
//            if(QDialog::Accepted==devForm.exec())
//            {
//                deliverObj = devForm.GetDeliver();
//            }else
//            {
//                return;
//            }
//        }else
//        {
//            NotifyForm ntForm("获取配送员失败!", NotifyForm::ERROR, this);
//            ntForm.exec();
//            return;
//        }
//    }

    NotifyForm ntForm(NTFORM_LOADING, NotifyForm::LOADING, this);
    connect(this, SIGNAL(ntFormClose()), &ntForm, SLOT(accept()));
    if(!targetBtn->text().compare(OPERABTN_NAME_CONFIRM)) {
        QString order_id = targetBtn->property(OPERABTN_PROPERTY_NAME).toString();
        OBJREF(BillsManger).ProcOrders(targetBtn->text(),
                                           order_id,
                                           -1,
                                           deliverObj);
        OrderObject * order = OBJREF(BillsManger).GetOrderObjByOrderId(order_id);
        if ( order && order->has_mate && !order->mate_assigned) {
            return;
        }
    }
    else if (!targetBtn->text().compare(OPERABTN_NAME_MAKE)) {
        OBJREF(BillsManger).ProcOrders(targetBtn->text(),
                                       targetBtn->property(OPERABTN_PROPERTY_NAME).toString());

        return;
    }
    else if (!targetBtn->text().compare(OPERABTN_NAME_CONFIRM_MATE)) {
        QPoint pos = ui->tableMake->mapFromGlobal(QCursor::pos());
        pos.setX(10);
        pos.setY(pos.y() - 40);
        onTableItemClicked(ui->tableMake->itemAt(pos));
        return;
    }
    else {
        OBJREF(BillsManger).ProcOrders(targetBtn->text(),
                                       targetBtn->property(OPERABTN_PROPERTY_NAME).toString());
    }

    m_bLoading = true;
    XCBOperate oper;
    oper.update(ntForm.winId());
    ntForm.exec();
    m_bLoading = false;
}

void MainForm::onTimeTimerOut()
{
    ui->labTime->setText(QDateTime::currentDateTime().toString("yyyy年MM月dd日 hh:mm:ss"));
    return;
}

void MainForm::onTableItemClicked(QTableWidgetItem *item)
{
    if(!_CheckState())
    {
        return;
    }
    QTableWidget *targetTable = item->tableWidget();
    targetTable->setCurrentItem(item);
    QString orderId = targetTable->item(item->row(), 1)->text();

    m_bexistDetailsForm = true;
    DetailsForm deatilsForm(OBJREF(BillsManger).GetOrderObjByOrderId(orderId),this);
    connect(&deatilsForm, SIGNAL(orderMateChanged(QString)), SLOT(onOrderMateChanged(QString)));
    XCBOperate oper;
    oper.update(deatilsForm.winId());
    deatilsForm.exec();
    m_bexistDetailsForm = false;
}

void MainForm::on_btnScroUp_clicked()
{
    m_curtTable->scrollToTop();
}

void MainForm::on_btnScroDown_clicked()
{
    m_curtTable->scrollToBottom();
}


void MainForm::on_cbxPrinter_currentIndexChanged(const QString &text)
{
    QLOG_TRACE() << __FUNCTION__ << text;
    OBJREF(IniDataManger).SetPrinterName(text);
}

void MainForm::onOrderMateChanged(const QString &order_id)
{
    if (m_curtTable->currentRow() == -1) {
        return;
    }
    QString target_order_id = m_curtTable->item(m_curtTable->currentRow(), 1)->text();
    if (order_id == target_order_id) {
        OrderObject *order = OBJREF(BillsManger).GetOrderObjByOrderId(order_id);
        int vid = OBJREF(BillsManger).GetTableVID(order);
        QWidget *btn_widget = m_curtTable->cellWidget(m_curtTable->currentRow(), 6);
        QPushButton *pBtn = (QPushButton*)btn_widget->layout()->itemAt(0)->widget();
        pBtn->setText(GetOperaBtnNameByVID(vid));
        QString qss = GetOperaBtnStyleByVID(vid, order->channel);
        pBtn->setStyleSheet(qss);
        pBtn->setProperty(OPERABTN_PROPERTY_NAME, order->order_id);
        QLOG_INFO() << "Changing button " << pBtn;
    }
    else {
        QLOG_WARN() << "inconsistent order id: " << order_id << " - " << target_order_id;
    }
}

void MainForm::on_ClearTable()
{
    //清除订单列表里的数据
    QTableWidget *table;
    foreach (table, this->findChildren<QTableWidget*>()) {
        table->setRowCount(0);
        table->clearContents();

        qDebug()<<table->objectName()<<"rowcount"<<table->rowCount();
    }
    QPushButton *btn;
    foreach (btn, this->findChildren<QPushButton*>()) {
        QVariant value=btn->property("name");
        if(value.isValid())
        {
            btn->setText(value.toString());
        }
    }
}

void MainForm::setFloatWId(WId id)
{
    floatWId=id;
}
