#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 <QApplication>
#include <QFile>
#include "QsLog.h"
#include "DTools/orderstatus.h"


DetailForm::DetailForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DetailForm)
{
    ui->setupUi(this);
    connect(this, &DetailForm::reEntryOrder, &FlowControl::GetInstance(), &FlowControl::onReEntryOrder);
    connect(this, &DetailForm::processOrder, &FlowControl::GetInstance(), &FlowControl::onProcessOrder);
    connect(this, &DetailForm::dorefund, &FlowControl::GetInstance(), &FlowControl::onRefund);
    _Init();
}

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

void DetailForm::InitData(OrderObject *orderObject)
{
    m_orderObject = orderObject;

    // 恢复界面
    ui->detailTable0->clearContents();
    ui->detailTable0->setRowCount(0);
    ui->detailBtn0->show();
    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)));
    QString deliverTime;
    deliverTime = orderObject->delivery_time==0? "立即送出":QDateTime::fromTime_t(orderObject->delivery_time).toString("yyyy-MM-dd hh:mm:ss");
    ui->detailLab5->setText(deliverTime);
    ui->detailLab6->setText(orderObject->courier_name.isEmpty() ? "暂未指定" : QString("[姓名]%1 [电话]%2")
                                                                            .arg(orderObject->courier_name, orderObject->courier_phone));
    ui->detailLab7->setText(Penny2Dollar(orderObject->product_fee));
    ui->detailLab8->setText(orderObject->has_invoiced? QString("发票抬头:%1").arg(orderObject->invoice_title) : "不需要发票");
    ui->detailLab9->setText(QString("-")+Penny2Dollar(orderObject->dis_shop_fee));
    ui->detailLab10->setText(QString("-")+Penny2Dollar(orderObject->service_fee));
    ui->detailLab11->setText(QString("-")+Penny2Dollar(orderObject->dis_shop_fee+orderObject->service_fee));
    int pricecount=0;
    for(int i=0; i<orderObject->proList.count(); i++)
    {
        ui->detailTable0->insertRow(i);
        ui->detailTable0->setItem(i, 0, new QTableWidgetItem(orderObject->proList.at(i)->name));  // 商品名
        ui->detailTable0->item(i, 0)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(i, 1, new QTableWidgetItem(Penny2Dollar(orderObject->proList.at(i)->price)));  // 价格
        ui->detailTable0->item(i, 1)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(i, 2, new QTableWidgetItem(QString::number(orderObject->proList.at(i)->productAmount)));  // 数量
        ui->detailTable0->item(i, 2)->setTextAlignment(Qt::AlignCenter);
        pricecount=pricecount+orderObject->proList.at(i)->price*orderObject->proList.at(i)->productAmount;
    }
    int   count=orderObject->proList.count();
    ui->detailTable0->insertRow(count);
    ui->detailTable0->setItem(count,0,new QTableWidgetItem(QString("商品合计")));
    ui->detailTable0->item(count, 0)->setTextAlignment(Qt::AlignCenter);
    ui->detailTable0->setItem(count, 1, new QTableWidgetItem(Penny2Dollar(pricecount)));  // 商品总价
    ui->detailTable0->item(count, 1)->setTextAlignment(Qt::AlignCenter);
    ui->detailTable0->setItem(count, 2, new QTableWidgetItem(QString::number(orderObject->total_amount)));  // 总数量
    ui->detailTable0->item(count, 2)->setTextAlignment(Qt::AlignCenter);

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

    QFile orderFlag(QString("%1/orders/%2").arg(QApplication::applicationDirPath(), orderObject->order_id));
    if(!orderFlag.exists())
    {
        ui->detailBtn0->hide();
    }

    ui->detailBtn2->setProperty("operation", OPERATION_REFUSE);
    ui->detailBtn2->setProperty("orderId", orderObject->order_id);
    ui->detailBtn2->show();
    if(orderObject->status !=2&&orderObject->status !=4&&orderObject->status !=6&&orderObject->status !=200&&orderObject->status !=20 )
    {
        ui->detailBtn2->hide();
    }
    if(orderObject->status==20||orderObject->status ==6||orderObject->status ==200)
    {
        ui->detailBtn2->setText("同意退款");
    }

    if(orderObject->order_type==3)
    {
         ui->detailBtn3->setText("核销");
    }else
    {
        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();
    }
}

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->horizontalHeader()->setFixedHeight(25);
    ui->detailTable0->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
}

void DetailForm::onOperaBtnClicked()
{
    hide();
    QPushButton *pBtn = (QPushButton*)sender();
    if(pBtn->property("operation")!=OPERATION_REFUSE)
    {
    emit processOrder(pBtn->property("operation").toString(), pBtn->property("orderId").toString(), DeliverObject());
    }
}

void DetailForm::on_detailBtn0_clicked()
{
    hide();
    emit reEntryOrder(m_orderObject->order_id);
}

void DetailForm::on_detailBtn1_clicked()
{
    QLOG_INFO() << QString("begin to reprint");
    if(FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetPrinterName(), m_orderObject))
    {
        QLOG_INFO() << QString("reprint sucessful");
        Orderstatus::getInstance().printupdate(m_orderObject->order_id,1);
    }else
    {
        emit showAlert(AlertForm::ERROR, QString("打印冲突，请稍后手动打印或重启收银程序"));
        QLOG_INFO() << QString("reprint failed");
    }
}

void DetailForm::on_detailBtn2_clicked()
{
    QString refuse_reason;
    if(m_orderObject->delivery_status==2)
    {
        refuse_reason = "8";
        emit dorefund(m_orderObject->order_id,refuse_reason);
    }
    else
    {
        RefuseForm *m_refuseform=new RefuseForm(this);
        m_refuseform->show();
        if(m_refuseform->exec()==QDialog::Accepted)
        {
            refuse_reason = m_refuseform->m_reasonCode;
            emit dorefund(m_orderObject->order_id,refuse_reason);
            delete m_refuseform;
        }
    }
}
