#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"

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

    // 初始化成员变量
    m_prevBtn = NULL;
    m_prevTable = NULL;
    m_raiseIndex = 0;
    m_tableList.append(ui->mainTableNew);
    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);
    // 注册信号槽参数
    qRegisterMetaType<CashierObject>("CashierObject");
    qRegisterMetaType< QList<CashierObject> >("QList<CashierObject>");
    qRegisterMetaType<DeliverObject>("DeliverObject");
    qRegisterMetaType< QList<DeliverObject> >("QList<DeliverObject>");
    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(&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_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);

    emit flowStart();
    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(APP_VERSION);
    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->mainBtnNew->hide();
    ui->mainTableNew->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;
    }
    m_resultForm->clear();
    m_resultForm->addItems(orderIdList);
    m_resultForm->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);
    }
}

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:
        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)
    {
        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->order_id))
            {
                table->removeRow(i);
                QString btnText(tabBtn->property("name").toString());
                if(table->rowCount() != 0)
                {
                    btnText = QString("%1(%2)").arg(btnText).arg(table->rowCount());
                }
                tabBtn->setText(btnText);
            }
        }
    }
    // 将数据插入到表中
    tabBtn = _GetTabBtnByOrderStatus(orderObject->status);
    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_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);  // 联系方式
    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->mainTableRefund )
        //if(table != ui->mainTableFinsh && table != ui->mainTableOther)
    {
        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(ui->mainTableRefund->rowCount() > 0)
    {
        emit startRemind(1);
    }else
    {
        emit stopRemind();
    }
    _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::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());
}
