#include "detailForm.h"
#include "ui_detailForm.h"
#include <QDateTime>
#include "preDefine.h"
#include "base/Arithmetic/util.h"
#include "base/Config/configManger.h"
#include "event/fmapplication.h"
#include "event/posevent.h"
#include "model/posorderpool.h"
#include "QsLog.h"

DetailForm::DetailForm(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DetailForm)
{
    ui->setupUi(this);
    ui->detailBtn0->hide();
     m_rejectForm =NULL;
    _Init();
}

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

bool DetailForm::getOrderOptAndName(OrderObject *order, QString &optname, QString &name)
{
    int status;

    if(order->refund_status == ApplicationRefundOrder ||
            order->refund_status == ApplicationPartialRefundOrder ||
            order->refund_status == CompleteRefundOrder)
        status = order->refund_status;
    else
        status = order->status;

    switch (status) {
    case NewOrder:
        optname = OPERATION_GETDELIVERS;
        name = QString::fromLocal8Bit(OPERATIONNAME_GETDELIVERS);
        return true;
    case FirmOrder:
        if(order->order_type == TimelyTakeout || order->order_type == AppointmentTakeout)
        {
            optname =  OPERATION_SENDOUT;
            name = QString::fromLocal8Bit(OPERATIONNAME_SENDOUT);
        }
        else
        {
            optname = OPERATION_MAKEOVER;
            name = QString::fromLocal8Bit(OPERATIONNAME_MAKEOVER);
        }
        return true;
    case CancelOrder:
        return false;
    case DispatchingOrder:
        optname = OPERATION_COMPLETE;
        name = QString::fromLocal8Bit(OPERATIONNAME_COMPLETE);
        return true;
    case InDevelopment:
        optname = OPERATION_COMPLETE;
        name = QString::fromLocal8Bit(OPERATIONNAME_COMPLETE);
        return true;
    case ServiceOrder:
    case CompleteOrder:
        return false;
    case ApplicationRefundOrder:
    case ApplicationPartialRefundOrder:
        optname = OPERATION_REFUNDORDER;
        name = QString::fromLocal8Bit(OPERATIONNAME_REFUNDORDER);
        return true;
    default:
        return false;
    }
}

bool DetailForm::getOtherOrderOptAndName(OrderObject *order, QString &optname, QString &name)
{
    int status;

    if(order->refund_status == ApplicationRefundOrder ||
            order->refund_status == ApplicationPartialRefundOrder ||
            order->refund_status == CompleteRefundOrder)
        status = order->refund_status;
    else
        status = order->status;

    switch (status) {
    case NewOrder:
//        if(QString("saas").compare(order->channel) != 0)
//        {
            optname = OPERATION_REFUSE;
            name = QString::fromLocal8Bit(OPERATIONNAME_REFUNDNEWORDER);
            return true;
//        }
        //return false;
    case FirmOrder:
        return false;
    case CancelOrder:
        return false;
    case DispatchingOrder:
        return false;
    case InDevelopment:
        return false;
    case ServiceOrder:
    case CompleteOrder:
        return false;
    case ApplicationRefundOrder:
    case ApplicationPartialRefundOrder:
        optname = OPERATION_REFUSEREFUND;
        name = QString::fromLocal8Bit(OPERATIONNAME_REFUSEREFUND);
        return true;
    default:
        return false;
    }
}


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

    _orderid = orderObject->order_id;
    // 恢复界面
    ui->detailTable0->clearContents();
    ui->detailTable0->setRowCount(0);
    ui->detailBtn2->show();
    ui->detailBtn3->show();
    //ui->detailBtn1->hide();

    // 初始化界面
    ui->detailLab0->setText(QString::fromLocal8Bit("[%1][%2][%3]").arg(orderObject->channel_name,
                                                        orderObject->status_desc,
                                                        orderObject->order_id));
    ui->detailLab1->setText(QString::fromLocal8Bit("[%1]%2").arg(orderObject->pay_type,
                                                  orderObject->remark));
    ui->detailLab2->setText(QString::fromLocal8Bit("[姓名]%1 [电话]%2").arg(orderObject->customer,
                                                            orderObject->phone));
    ui->detailLab3->setText(orderObject->address);
    ui->detailLab4->setText(QString::fromLocal8Bit("[配送方式]%1 [配送费]%2").arg(orderObject->delivery_party,
                                                                 Penny2Dollar(orderObject->send_fee)));
    if(orderObject->order_type == 1 || orderObject->order_type == 2)
        ui->detailLab5->setText(orderObject->srcdlv_time==0? QString::fromLocal8Bit("立即送出") : QDateTime::fromTime_t(orderObject->srcdlv_time).toString("MM/dd hh:mm"));
    else
        ui->detailLab5->setText(orderObject->srcdlv_time==0? QString::fromLocal8Bit("") : QDateTime::fromTime_t(orderObject->srcdlv_time).toString("MM/dd hh:mm"));
//    ui->detailLab6->setText(orderObject->courier_name.isEmpty() ? QString::fromLocal8Bit("暂未指定") : QString::fromLocal8Bit("[姓名]%1 [电话]%2")
//                                                                            .arg(orderObject->courier_name, orderObject->courier_phone));
    if(orderObject->disList.size() > 0)
        ui->detailLab6->setText(QString::number((orderObject->discount_fee)/100.0, 'f' , 2).append(QString::fromLocal8Bit("(元)")));
    else
        ui->detailLab6->setText("0");

    ui->detailLab7->setText(!orderObject->pay_type.compare("在线支付") ? "0" : Penny2Dollar(orderObject->user_fee));
    ui->detailLab8->setText(orderObject->has_invoiced? QString::fromLocal8Bit("发票抬头:%1").arg(orderObject->invoice_title) : QString::fromLocal8Bit("不需要发票"));
    ui->detailLab8_3->setText(QString::fromLocal8Bit("%1").arg(QString::number(orderObject->package_fee / 100.0, 'f', 2).append(QString::fromLocal8Bit("(元)"))));


    for(int i=0; i<orderObject->proList.count(); i++)
    {
        ProductObject *product = orderObject->proList.at(i);
        ui->detailTable0->insertRow(0);
        QString name = product->name , property_tags=product->property_tags;
        if(!property_tags.isEmpty())
        {
            //<font color='#ff0000'>未登录</font>
            QTableWidgetItem *item = new QTableWidgetItem(property_tags);
            item->setTextColor(QColor(255,0,0));
            //name.append(QString::fromLocal8Bit("\r\n加料：")).append(QString(property_tags.replace(",", "\r\n")));
            ui->detailTable0->setItem(0, 0, item);  // 商品名
            //setTextColor(QColor(255,0,0)
            ui->detailTable0->item(0, 0)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(0, 1, new QTableWidgetItem(QString()));  // 价格
            ui->detailTable0->item(0, 1)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(0, 2, new QTableWidgetItem(QString()));  // 数量
            ui->detailTable0->item(0, 2)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->insertRow(0);
        }
        ui->detailTable0->setItem(0, 0, new QTableWidgetItem(name));  // 商品名
        ui->detailTable0->item(0, 0)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(0, 1, new QTableWidgetItem(QString::number(orderObject->proList.at(i)->price/100.0)));  // 价格
        ui->detailTable0->item(0, 1)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(0, 2, new QTableWidgetItem(QString::number(orderObject->proList.at(i)->product_amount)));  // 数量
        ui->detailTable0->item(0, 2)->setTextAlignment(Qt::AlignCenter);
    }

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

    bool needbtn2 = false;
    bool needbtn3 = false;

    QString btn3opt, btn3name;
    QString btn2opt, btn2name;

    needbtn3 = getOrderOptAndName(orderObject, btn3opt, btn3name);
    needbtn2 = getOtherOrderOptAndName(orderObject, btn2opt, btn2name);

    if(needbtn3)
    {
        ui->detailBtn3->setProperty("orderId", orderObject->order_id);
        ui->detailBtn3->setText(btn3name);
        ui->detailBtn3->setProperty("operation", btn3opt);;
    }
    else
    {
        ui->detailBtn3->hide();
    }

    if(needbtn2)
    {
        ui->detailBtn2->setProperty("orderId", orderObject->order_id);
        ui->detailBtn2->setText(btn2name);
        ui->detailBtn2->setProperty("operation", btn2opt);;
    }
    else
    {
        ui->detailBtn2->hide();
    }

    if(flag)
    {
        ui->detailBtn1->hide();
        ui->detailBtn3->hide();
        ui->detailBtn2->show();
        ui->detailBtn2->setProperty("orderId", orderObject->order_id);
        ui->detailBtn2->setText(QString::fromLocal8Bit(OPERATIONNAME_COMPLETE));
        ui->detailBtn2->setProperty("operation", OPERATION_COMPLETE);
    }
    else
        ui->detailBtn1->show();
}

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("ordertype").toInt() == 1 || pBtn->property("ordertype").toInt() == 2) &&
//            pBtn->property("operation").toString().compare(OPERATION_MAKEOVER, Qt::CaseInsensitive) == 0)
//    {
//        QLOG_DEBUG() << "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&" << "operation : " << pBtn->property("operation").toString() << "; ordertype : " << pBtn->property("ordertype").toInt();
//        return ;
//    }

    //QLOG_INFO() << "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&" << "operation : " << pBtn->property("operation").toString() << "; ordertype : " << pBtn->property("ordertype").toInt();

    if(m_rejectForm==NULL){m_rejectForm = new RejectForm(this);}

//    if(pBtn->text()=="拒单")
//    {
//        m_rejectForm->InitUi(REJECTUITYPE_REFUSEORDER);
//        m_rejectForm->show();
//        if(m_rejectForm->exec()==QDialog::Accepted)
//        {
//            emit processRejectOrder( pBtn->property("orderId").toString(),m_rejectForm->GetReasonCode(),m_rejectForm->GetReason(),REJECTUITYPE_REFUSEORDER);
//        }
//    }
//    else if(pBtn->text()=="退单")
//    {
//        m_rejectForm->InitUi(REJECTUITYPE_CANCLEORDER);
//        m_rejectForm->show();
//        if(m_rejectForm->exec()==QDialog::Accepted)
//        {
//            emit processRejectOrder( pBtn->property("orderId").toString(),m_rejectForm->GetReasonCode(),m_rejectForm->GetReason(),REJECTUITYPE_CANCLEORDER);
//        }
//    }
//    else if(pBtn->text()=="拒绝")
//    {
//        m_rejectForm->InitUi(REJECTUITYPE_REFUSEREFUND);
//        m_rejectForm->show();
//        if(m_rejectForm->exec()==QDialog::Accepted)
//        {
//            emit processRejectOrder( pBtn->property("orderId").toString(),m_rejectForm->GetReasonCode(),m_rejectForm->GetReason(),REJECTUITYPE_REFUSEREFUND);
//        }
//    }
//    else
//    {
//       emit processOrder(pBtn->property("operation").toString(), pBtn->property("orderId").toString(), DeliverObject());
//    }

    QVariantMap value;

    if(pBtn->text()=="拒单")
    {
        m_rejectForm->InitUi(REJECTUITYPE_REFUSEORDER);
        m_rejectForm->show();
        if(m_rejectForm->exec()!=QDialog::Accepted)
            return ;
        value.insert(EVENT_KEY_MSG, m_rejectForm->GetReason());
    }

    if(pBtn->text()==QString::fromLocal8Bit("退单"))
    {
        m_rejectForm->InitUi(REJECTUITYPE_CANCLEORDER);
        m_rejectForm->show();
        if(m_rejectForm->exec()!=QDialog::Accepted)
            return ;
        value.insert(EVENT_KEY_MSG, m_rejectForm->GetReason());
    }



    if(pBtn->text()==QString::fromLocal8Bit("拒绝"))
    {
        m_rejectForm->InitUi(REJECTUITYPE_REFUSEREFUND);
        m_rejectForm->show();
        if(m_rejectForm->exec() != QDialog::Accepted)
            return ;
        value.insert(EVENT_KEY_MSG, m_rejectForm->GetReason());
    }



    value.insert(EVENT_KEY_ORDERID, pBtn->property("orderId").toString());
    value.insert(EVENT_KEY_STATUS, pBtn->property("operation").toString());


    POSTEVENTTYPE(PosEvent::s_opt_order,value,QVariantMap);
}

void DetailForm::on_detailBtn1_clicked()
{
    QVariantMap map;

    map.insert(EVENT_KEY_ORDERID, _orderid);
    map.insert(EVENT_KEY_MSG, DEFAULT_LOCATION_PRINT);

    POSTEVENTTYPE(PosEvent::s_order_location, map, QVariantMap);
}

void DetailForm::on_detailBtn0_clicked()
{
//    QString error,business;
//    if(FmPlugin::GetInstance().DoOrderEntry(m_orderObject,error,business))
//    {
//        Orderstatus::getInstance().putupdate(m_orderObject->order_id,1);
//        emit processReportOrder(m_orderObject->order_id,business,1,error,m_orderObject->product_fee-m_orderObject->package_fee);
//        emit showAlert(AlertForm::SUCCESS, QString("[重新补录销售单成功]."));
//    }
//    else{
//        emit showAlert(AlertForm::ERROR, QString("重新补录销售单失败[%1]").arg(error));
//    }
//    hide();
//    emit doReEntry(m_orderObject);
}
