#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 "DTools/configManger.h"
#include "fmPrinter.h"
#include <QDebug>
#include <QThread>

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

    // 初始化成员变量
    m_bShowSelfDeli = false;
    m_prevBtn = NULL;
    m_prevTable = NULL;
    m_raiseIndex = 0;
    m_tableList.append(ui->mainTableOur);
    m_tableList.append(ui->mainTableMake);
    m_tableList.append(ui->mainTableSend);
    m_tableList.append(ui->mainTableRefund);
    m_tableList.append(ui->mainTableFinsh);
    m_tableList.append(ui->mainTableOther);
    m_tableList.append(ui->mainTableNew);
    // 注册信号槽参数
    qRegisterMetaType<CashierObject>("CashierObject");
    qRegisterMetaType< QList<CashierObject> >("QList<CashierObject>");
    qRegisterMetaType<DeliverObject>("DeliverObject");
    qRegisterMetaType< QList<DeliverObject> >("QList<DeliverObject>");
    qRegisterMetaType<DailyStatement>("DailyStatement");

    qRegisterMetaType< QList< DailyStatement > >("QList< DailyStatement >");
    qRegisterMetaType<dishesObject>("dishesObject");
    qRegisterMetaType< QMap< QString, QMap<QString, dishesObject> > >("QMap<QString, QMap<QString, dishesObject>>");

    qRegisterMetaType< QMap<QString, int> >("QMap<QString, int>");

    qRegisterMetaType<AlertForm::Type>("AlertForm::Type");
    // 连接信号槽
    connect(&m_timeTimer, &QTimer::timeout, this, &MainForm::onSetCurrentTime);
    connect(this, &MainForm::flowStart, &FlowControl::GetInstance(), &FlowControl::onFlowStart);
    connect(this, &MainForm::processOrder, &FlowControl::GetInstance(), &FlowControl::onProcessOrder);
    connect(this, &MainForm::getOnDutyCashiers, &FlowControl::GetInstance(), &FlowControl::onGetOnDutyCashiers);
    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::GetDailyStatement, &FlowControl::GetInstance(), &FlowControl::onGetDailyStatement);
    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::changeOrderStatus, this, &MainForm::onChangeOrderStatus);
    connect(&FlowControl::GetInstance(), &FlowControl::showDeliverPickForm, this, &MainForm::onShowDeliverPickForm);
    connect(&FlowControl::GetInstance(), &FlowControl::showCashierPickForm, this, &MainForm::onShowCashierPickForm);
    connect(&FlowControl::GetInstance(), &FlowControl::showOrderDetails, this, &MainForm::onShowOrderDetails);
    // 搜索订单的信号槽
    connect(ui->mainEdtSearch, &ClickedLineEdit::textChanged, &FlowControl::GetInstance(), &FlowControl::onSerachOrder);
    connect(&FlowControl::GetInstance(), &FlowControl::showSearchOrderResult, this, &MainForm::onShowSearchOrderResult);
    // 初始化界面
    _Init();
    // 开启时间定时器
    m_timeTimer.start(1000);
}

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

void MainForm::MyShow()
{
    this->show();
    // 考虑到坐标问题放到这里构建
    m_alertForm = new AlertForm(this);
    m_dailyForm = new DailyForm(this);

    m_pickForm = new PickForm(this);
    connect(m_pickForm, &PickForm::updateCashier, this, &MainForm::onUpdateCashier);

    m_settingForm = new SettingForm(this);

    m_detailForm = new DetailForm(this);

    m_padForm = new PadForm(this);
    m_padForm->move(pos().x()+width()-300, pos().y()+height()-438);
    m_padForm->hide();
    connect(m_padForm, &PadForm::numClicked, this, &MainForm::onNumClicked);
    connect(m_padForm, &PadForm::numDelete, this, &MainForm::onNumDelete);
    connect(m_padForm, &PadForm::numClear, ui->mainEdtSearch, &ClickedLineEdit::clear);
    connect(m_detailForm,&DetailForm::showAlert,this,&MainForm::onShowAlert);
    m_resultForm = new QListWidget(this);
    m_resultForm->setObjectName("mainListWdg0");
    m_resultForm->setFixedSize(240, 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);

    emit flowStart();

    ui->mainEdtSearch->setFocus();
    return;
}

void MainForm::_Init()
{
    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    this->showFullScreen();
    // 显示托盘
    m_tray.show();

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

    // 初始化文字
    ui->mainLabStoreid->setText(UI_STOREID);
    ui->mainLabVersion->setText("1.1.6");
    ui->mainLabCashier->setText(UI_CASHIER);

    // 初始化表
    int scales6[] = {3, 4, 2, 3, 3, 3};
    int scales5[] = {3, 6, 2, 3, 3};
    int tableWidth = this->width() - 75;
    foreach(QTableWidget *table, m_tableList)
    {
        table->hide();
        if(table == ui->mainTableFinsh ||
           table == ui->mainTableOther)
        {
            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->mainTableMake->show();
    ui->mainBtnMake->setChecked(true);
    ui->mainBtnMake->setEnabled(false);
    m_prevBtn = ui->mainBtnMake;
    m_prevTable = ui->mainTableMake;
    m_currentTable = ui->mainTableMake;

    // 门店营业状态详情暂时屏蔽
    // TODO
    ui->mainBtnOpeDetails->hide();

    // TODO(用于鲜丰演示)
    ui->mainSlabLogo0->hide();
    ui->mainSlabLogo1->hide();
    //ui->mainBtnOur->hide();
    //ui->mainTableOur->hide();
    ui->mainSlabCashier->hide();
    ui->mainBtnCashier->hide();
    ui->mainLabCashier->hide();
}

void MainForm::onSetCurrentTime()
{
    if(m_raiseIndex++ > 10)
    {
      raise();
      m_raiseIndex = 0;
    }
    ui->mainSlabTime->setText(QDateTime::currentDateTime().toString("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(), DeliverObject());
}

void MainForm::on_mainBtnCashier_clicked()
{
    emit getOnDutyCashiers();
}

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

void MainForm::on_mainBtnHide_clicked()
{
    hide();
    ui->mainEdtSearch->clear();
    m_padForm->hide();
    showFloatForm();
}

void MainForm::onUpdateCashier(const CashierObject &cashier)
{
    ui->mainLabCashier->setText(cashier.name);
}

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

void MainForm::onShowSearchOrderResult(const QStringList &orderIdList)
{
    if(orderIdList.isEmpty())
    {
        m_resultForm->hide();
        return;
    }
    if(orderIdList.count()==1)
    {
        emit getOrderDetails(orderIdList.at(0));
        m_resultForm->clear();
        m_resultForm->hide();
        m_padForm->hide();
        ui->mainEdtSearch->clear();
    }
    m_resultForm->clear();
    m_resultForm->addItems(orderIdList);
    m_resultForm->show();
}

void MainForm::onshow()
{
    QLOG_INFO()<<"accept the signal of showmainform";
    this->show();
    if(m_bShowSelfDeli)
    {
        m_alertForm->SetContent(AlertForm::ERROR, QString("部分订单没有骑士配送!已转移至自配送栏目"));
        m_alertForm->show();
        ui->mainBtnOur->click();
        m_bShowSelfDeli = false;
    }

    ui->mainEdtSearch->setFocus();
}

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);
    }
}

QPushButton *MainForm::_GetTabBtnByOrderStatus(int orderStatus)
{
    switch(orderStatus)
    {
    case 1:
        return ui->mainBtnNew;
        break;
    case 2:
        return ui->mainBtnMake;
        break;
    case 5:
    case 4:
        return ui->mainBtnSend;
        break;
    case 6:
    case 200:
        return ui->mainBtnFinsh;
        break;
    case 20:
    case 22:
        return ui->mainBtnRefund;
        break;
    default:
        return ui->mainBtnOther;
        break;
    }
}

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

void MainForm::onShowAlert(AlertForm::Type type, const QString &msg)
{
    if(!isHidden())
    {
        m_alertForm->SetContent(type, msg);
        m_alertForm->show();
    }
}

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

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)
    {
        QTableWidget* table = findChild<QTableWidget*>(orderObject->curt_table_btn->property("tableName").toString());

        for(int i=0; i<table->rowCount(); i++)
        {

            if(!table->item(i, 1)->text().compare(orderObject->order_view_id.isEmpty()?orderObject->order_id:orderObject->order_view_id))
            {

                table->removeRow(i);
                QString btnText(orderObject->curt_table_btn->property("name").toString());
                if(table->rowCount() != 0)
                {
                    btnText = QString("%1(%2)").arg(btnText).arg(table->rowCount());
                }
                orderObject->curt_table_btn->setText(btnText);
            }
        }
    }
    // 将数据插入到表中
    if(orderObject->status==2 && orderObject->delivery_status==2)
    {
        tabBtn = ui->mainBtnOur;
    }else
    {
        tabBtn = _GetTabBtnByOrderStatus(orderObject->status);
    }

    orderObject->curt_table_btn = tabBtn;

    table = findChild<QTableWidget*>(tabBtn->property("tableName").toString());
    table->insertRow(0);

    QTableWidgetItem *item0 = new QTableWidgetItem("#"+QString::number(orderObject->order_index)+orderObject->channelName);
    item0->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 0, item0);  // 渠道
    QTableWidgetItem *item1 = new QTableWidgetItem(orderObject->order_view_id.isEmpty()?orderObject->order_id:orderObject->order_view_id);
    item1->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 1, item1);  // 订单ID
    QTableWidgetItem *item2 = new QTableWidgetItem(Penny2Dollar(orderObject->product_fee));
    item2->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 2, item2);  // 金额
    QTableWidgetItem *item3 = new QTableWidgetItem(orderObject->customer);
    item3->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 3, item3);  // 姓名
    QTableWidgetItem *item4 = new QTableWidgetItem(orderObject->phone);
    item4->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 4, item4);  // 联系方式

    if(table == ui->mainTableRefund)
    {
        QTableWidgetItem *item5 = new QTableWidgetItem(orderObject->status==20?"全额退款":"部分退款");
        item5->setTextAlignment(Qt::AlignCenter);
        table->setItem(0, 5, item5);  // 订单状态
    }else
    {
        QTableWidgetItem *item5 = new QTableWidgetItem(QDateTime::fromTime_t(orderObject->create_time).toString("MM-dd hh:mm"));
        item5->setTextAlignment(Qt::AlignCenter);
        table->setItem(0, 5, item5);  // 下单时间
    }

    if(table == ui->mainTableNew||table == ui->mainTableRefund||table==ui->mainTableOur)
    {
        QWidget *pWdg = new QWidget(table);
        QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
        QPushButton * pBtn = new QPushButton(pWdg);
        QPixmap btnImg(":btnCommon_normal.png");
        pBtn->setFixedSize(btnImg.size());
        pBtn->setFocusPolicy(Qt::NoFocus);
        pBtn->setObjectName("mainProcBtn");
        pBtn->setProperty("orderId", orderObject->order_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);

    }

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

    // 检测是否需要提示
    if(!ConfigManger::GetInstance().GetOutConfirm().compare("0") && ui->mainTableNew->rowCount() >0)
    {
        emit startRemind(0);
    }else if(!ConfigManger::GetInstance().GetOutConfirm().compare("1") && ui->mainTableMake->rowCount() > 0)
    {
         emit startRemind(0);
    }else if(ui->mainTableRefund->rowCount() > 0)
    {
        emit startRemind(1);
    }else if(ui->mainTableOur->rowCount() > 0)
    {
        emit startRemind(2);
    }else
    {
        emit stopRemind();
    }

    if(orderObject->status==2 && orderObject->delivery_status==2 && ui->mainTableOur->rowCount() > 0 )
    {

       if(this->isHidden())
       {
           m_bShowSelfDeli = true;
       }else
       {
           m_alertForm->SetContent(AlertForm::ERROR, QString("[%1][%2]号订单[%3]没有骑士配送!已转移至自配送栏目").arg(orderObject->channelName).arg(orderObject->order_index).arg(orderObject->order_id));
           m_alertForm->show();
           ui->mainBtnOur->click();
       }
    }

    _SetTablesSortEnable(true);
}

void MainForm::onShowDeliverPickForm(const QString &orderId, const QList<DeliverObject> &delivers)
{
    m_pickForm->SetDeliversInfo(orderId, delivers);
    m_pickForm->show();
}

void MainForm::onShowCashierPickForm(const QList<CashierObject> &cashiers)
{
    m_pickForm->SetCashiersInfo(cashiers);
    m_pickForm->show();
}

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::on_mainEdtSearch_returnPressed()
{

}

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();
    emit getOrderDetails(item->text());
}

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

void MainForm::on_mainBtnMDGL_clicked()
{
    emit GetBusinessStatus();
}

void MainForm::on_mainBtnRJ_clicked()
{
    emit GetDailyStatement();
}
