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

extern QThread tcpThread;
extern QThread  workThread;

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

    // 初始化成员变量
    m_prevBtn = NULL;
    m_prevTable = NULL;
    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::PullDishes, &FlowControl::GetInstance(), &FlowControl::onPullDishes);
    connect(this, &MainForm::GetBusinessStatus, &FlowControl::GetInstance(), &FlowControl::onGetBusinessStatus);
    connect(this, &MainForm::getDayReport, &FlowControl::GetInstance(), &FlowControl::onDailyReport);
    connect(&FlowControl::GetInstance(), &FlowControl::showDailyReportData, this, &MainForm::onSetDailyReportData);
    connect(&FlowControl::GetInstance(), &FlowControl::hideAlert, this, &MainForm::onHideAlert);
    connect(&FlowControl::GetInstance(), &FlowControl::showAlert, this, &MainForm::onShowAlert);
    connect(&FlowControl::GetInstance(), &FlowControl::setOpeStatus, this, &MainForm::onSetOpeStatus);
    connect(&FlowControl::GetInstance(), &FlowControl::setNetStatus, this, &MainForm::onSetNetStatus);
    connect(&FlowControl::GetInstance(), &FlowControl::setStoreInfo, this, &MainForm::onSetStoreInfo);
    connect(&FlowControl::GetInstance(), &FlowControl::setCashierInfo, this, &MainForm::onSetCashierInfo);
    connect(&FlowControl::GetInstance(), &FlowControl::changeOrderStatus, this, &MainForm::onChangeOrderStatus/*,Qt::BlockingQueuedConnection*/);
    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::MyShow()
{
#ifdef QT_DEBUG
    this->show();
#else
    this->show();
    //this->showFullScreen();
#endif

    // 考虑到坐标问题放到这里构建
    m_alertForm = new AlertForm(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);

    m_resultForm = new QListWidget(this);
    m_resultForm->setObjectName("mainListWdg0");
    m_resultForm->setFixedSize(420, 200);
    m_resultForm->move(70, 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->mainBtnStoreManager->hide();
#ifdef TODO
    ui->mainBtnDishManager->hide();
#endif
    //emit flowStart();
    return;
}

void MainForm::_Init()
{
    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    //this->showFullScreen();
    // 显示托盘
    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 /*||
           table == ui->mainTableReserve*/)
        {
            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();
}

void MainForm::onSetCurrentTime()
{
    if(m_raiseIndex++>10)
    {
       m_raiseIndex=0;
       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();
    showFloatForm();
}

/*
void MainForm::on_mainBtnHideAndLockForm()
{
    on_mainBtnHide_clicked();
    emit lockFloatForm();
}
*/

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++)
    {
        if(!table->item(i, 1)->text().compare(orderId))
        {
            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();
    }
}

void MainForm::onSetStoreInfo(const QString &storeId)
{
    ui->mainLabStoreid->setText(storeId);
}

void MainForm::onSetCashierInfo(const QString &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)
    {
        //TODO
//        if(/*2==orderObject->order_type&&*/(1==oldStatus||2==oldStatus))
//        {
//            table=ui->mainTableReserve;
//            tabBtn = ui->mainBtnReserve;
//        }
        //else{

            tabBtn = _GetTabBtnByOrderStatus(oldStatus);
            table = findChild<QTableWidget*>(tabBtn->property("tableName").toString());
        //}
        for(int i=0; i<table->rowCount(); i++)
        {
            if(!table->item(i, 1)->text().compare(orderObject->id))
            {
                table->removeRow(i);
                QString btnText(tabBtn->property("name").toString());
                btnText = QString("%1\n%2").arg(table->rowCount()).arg(btnText);
                tabBtn->setText(btnText);
            }
        }
    }
    // 将数据插入到表中
    //TODO
//    if(/*2==orderObject->order_type&&*/(1==orderObject->orderStatus||2==orderObject->orderStatus))
//    {
//        table = ui->mainTableReserve;
//        tabBtn = ui->mainBtnReserve;
//    }
    //else{
        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);  // 渠道
    QTableWidgetItem *item1 = new QTableWidgetItem(orderObject->id);
    item1->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 1, item1);  // 订单ID
    QTableWidgetItem *item2 = new QTableWidgetItem(Penny2Dollar(orderObject->totalPrice));
    item2->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 2, item2);  // 金额
    //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());
            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::SimExcept == 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("POS录单失败"));
            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)
{
    emit getOrderDetails(((QTableWidget*)sender())->item(item->row(), 1)->text());
}

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::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_mainBtnStoreManager_clicked()
{
    emit GetBusinessStatus();
}

void MainForm::on_mainBtnDayReport_clicked()
{
    emit getDayReport();
}
