#include "detailForm.h"
#include "ui_detailForm.h"
#include "DTools/util.h"
#include "preDefine.h"
#include "DTools/configManger.h"
#include "Control/flowControl.h"
#include "fmPrinter.h"
#include "QsLog.h"

#include "fmPlugin.h"

DetailForm::DetailForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DetailForm)
{
    ui->setupUi(this);
    connect(this, &DetailForm::processOrder, &FlowControl::GetInstance(), &FlowControl::onProcessOrder);
    connect(this, &DetailForm::processRejectOrder, &FlowControl::GetInstance(), &FlowControl::onProcessRejectOrder);

    _Init();
}

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

void DetailForm::InitData(OrderObject *orderObject)
{
    m_orderObject = orderObject;
    // 恢复界面
    ui->detailTable0->clear();
    ui->detailBtn2->show();
    ui->detailBtn3->show();

    // 初始化界面
    ui->detailLab0->setText(QString("[%1][%2][%3]").arg(orderObject->channelName,
                                                        orderObject->status_desc,
                                                        orderObject->order_id));
    ui->detailLab1->setText(QString("[%1]%2").arg(orderObject->pay_type,
                                                  orderObject->remark));
    ui->detailLab2->setText(QString("[姓名]%1 [电话]%2").arg(orderObject->customer,
                                                            orderObject->phone));
    ui->detailLab3->setText(orderObject->address);
    ui->detailLab4->setText(QString("[配送方式]%1 [配送费]%2").arg(orderObject->delivery_party,
                                                                 Penny2Dollar(orderObject->send_fee)));
    ui->detailLab5->setText(orderObject->delivery_time==0? "立即送出" : QDateTime::fromTime_t(orderObject->delivery_time).toString("MM/dd hh:mm"));

    ui->detailLab6->setText(orderObject->courier_name.isEmpty() ? "暂未指定" : QString("[姓名]%1 [电话]%2")
                                                                            .arg(orderObject->courier_name, orderObject->courier_phone));
    ui->detailLab7->setText(!orderObject->pay_type.compare("在线支付") ? "0" : Penny2Dollar(orderObject->shop_fee));
    ui->detailLab8->setText(orderObject->has_invoiced? QString("发票抬头:%1").arg(orderObject->invoice_title) : "不需要发票");
    if(orderObject->order_type==3 || orderObject->order_type==4)
    {
        ui->detailSlab8->setText("提货码");
        ui->detailLab8->setText(orderObject->delivery_code);
    }

    QString topName = "";
    QTreeWidgetItem* topItem = NULL;
    QMultiMap<QString, ProductObject* > map;

    QListIterator<ProductObject*> listIte(orderObject->proList);
    while(listIte.hasNext())
    {
        ProductObject * pObj = listIte.next();
        map.insert(pObj->bsk_num, pObj);
    }

    foreach(QString key, map.uniqueKeys())
    {
        topName = QString("%1号口袋").arg(key);
        topItem = new QTreeWidgetItem(QStringList()<<topName);
        ui->detailTable0->addTopLevelItem(topItem);

        foreach(ProductObject * pObj, map.values(key))
        {
            QTreeWidgetItem *cItem = new QTreeWidgetItem(QStringList()<< pObj->name
                                                        << Penny2Dollar(pObj->price)
                                                        << QString::number(pObj->productAmount));
            cItem->setTextAlignment(0, Qt::AlignCenter);
            cItem->setTextAlignment(1, Qt::AlignCenter);
            cItem->setTextAlignment(2, Qt::AlignCenter);
            topItem->addChild(cItem);
        }

        topItem->setExpanded(true);
    }

    QString records;
    foreach(QString record, orderObject->records)
    {
        records.append(record+"\r\n");
    }
    ui->detailLabRecord->setText(records);

    if(!ConfigManger::GetInstance().GetIsExistReEntryOrder())
    {
        ui->detailBtn0->hide();
    }

    ui->detailBtn2->setText(GetOperNameByStatus(orderObject->status, true));
    ui->detailBtn2->setProperty("operation", GetOperByStatus(orderObject->status, true));
    ui->detailBtn2->setProperty("orderId", orderObject->order_id);
//    if(orderObject->status != 1 && orderObject->status != 20&& orderObject->status != 2&& orderObject->status != 4)
//    {
        ui->detailBtn2->hide();
//    }

    ui->detailBtn3->setText(GetOperNameByStatus(orderObject->status));
    ui->detailBtn3->setProperty("operation", GetOperByStatus(orderObject->status));
    ui->detailBtn3->setProperty("orderId", orderObject->order_id);

    if(!GetOperByStatus(orderObject->status).compare("NULL"))
    {
        ui->detailBtn3->hide();
    }

    if(orderObject->order_type==3 || orderObject->order_type==4)
    {
        ui->detailBtn2->hide();
        ui->detailBtn3->hide();
    }
}

void DetailForm::_Init()
{
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);
    setGeometry(((QWidget*)parent())->geometry());

    int tableWidth = this->width()/2 - 65;
    ui->detailTable0->setColumnWidth(0, tableWidth*5/9);
    ui->detailTable0->setColumnWidth(1, tableWidth*2/9);
    ui->detailTable0->setColumnWidth(2, tableWidth*2/9);
    ui->detailTable0->header()->setDefaultAlignment(Qt::AlignCenter);
    ui->detailTable0->header()->setFixedHeight(25);
    ui->detailTable0->header()->setStretchLastSection(true);
    ui->detailTable0->header()->setSectionResizeMode(QHeaderView::Fixed);

    m_rejectForm = new RejectForm(this);
//    ui->detailTable0->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
}

void DetailForm::onOperaBtnClicked()
{
    hide();
    QPushButton *pBtn = (QPushButton*)sender();
    if(pBtn->text()=="拒单")
    {
        m_rejectForm->show();
        if(m_rejectForm->exec()==QDialog::Accepted)
            {
                emit processRejectOrder( pBtn->property("orderId").toString(),m_rejectForm->GetReasonCode(),0);
            }
    }
    else if(pBtn->text()=="退单")
    {
        m_rejectForm->show();
        if(m_rejectForm->exec()==QDialog::Accepted)
            {
                emit processRejectOrder( pBtn->property("orderId").toString(),m_rejectForm->GetReasonCode(),1);
            }
    }
    else
    {
        emit processOrder(pBtn->property("operation").toString(), pBtn->property("orderId").toString(), DeliverObject());
    }
}

void DetailForm::on_detailBtn1_clicked()
{
    QLOG_INFO() << "re print...............";
    QString error;
    FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetqtPrinterName(), m_orderObject, error);
    QLOG_ERROR() << error;
    FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetlfPrinterName(), m_orderObject, error);
    QLOG_ERROR() << error;
    FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetrcPrinterName(), m_orderObject, error);
    QLOG_ERROR() << error;
    QLOG_INFO() << "end print...............";
}

void DetailForm::on_detailBtn0_clicked()
{
    //写入销售单

    QString error;
    QLOG_INFO() << QString("[---begin entry order [%1]---].").arg(QString(FmPlugin::GetInstance()._GetOrderEntryData(m_orderObject)));

    if(!FmPlugin::GetInstance().DoOrderEntry(m_orderObject, error))
    {
        //while(!FmPlugin::GetInstance().DoOrderEntry(orderObject, error, true))
        //{
            QLOG_INFO() << QString("entry order failed[%1]").arg(error);
        //}
    }
    else
    {
        QLOG_INFO() << QString("[entry order success].");
    }

}
