#include "newdetailform.h"
#include "ui_newdetailform.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"

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

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

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

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

    //"<h2><i>Hello</i><font color=red>Qt!</font></h2>"

    // 初始化界面
    ui->orderInfoLb_dec->setText(QString::fromLocal8Bit("【<font color=red>%1</font>】【%2】").arg(orderObject->channel_name,
                                                        orderObject->order_id));
    ui->orderMemoLb_dec->setText(QString::fromLocal8Bit("【%1】").arg(orderObject->remark));
    ui->customerInfoLb_dec->setText(QString::fromLocal8Bit("【%1】【<font color=red>%2</font>】").arg(orderObject->customer,
                                                                           orderObject->phone));
    ui->addressLb_dec->setText(QString::fromLocal8Bit("【%1】【%2】").arg(orderObject->address,orderObject->address));

    QDateTime dTime = QDateTime::fromTime_t(orderObject->delivery_time);
    QString timeStr = dTime.toString(QString::fromLocal8Bit("yyyy-MM-dd hh:mm"));

    ui->deliveryInfoLb_dec->setText(QString::fromLocal8Bit("【%1】【%2】").arg(orderObject->delivery_party,timeStr));

    QList<DiscountObject *> list = orderObject->disList;
    QString disStr;
    for(int i = 0; i < list.size(); i++) {
        disStr += QString::fromLocal8Bit("【");
        disStr += list.at(i)->name;
        disStr += QString::fromLocal8Bit("】");
    }

    ui->promotionInfoLb_dec->setText(QString(disStr));

    QString checkStr;
    if(orderObject->has_invoiced) {
        checkStr = QString::fromLocal8Bit("【%1】").arg(orderObject->invoice_title);
    } else {
        checkStr = QString::fromLocal8Bit("【不需要发票】");
    }

    ui->checkInfoLb_dec->setText(QString(checkStr));

/*
    ui->orderInfoLb_dec->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->dishTableWidget->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->dishTableWidget->setItem(0, 0, item);  // 商品名
            //setTextColor(QColor(255,0,0)
            ui->dishTableWidget->item(0, 0)->setTextAlignment(Qt::AlignCenter);
            ui->dishTableWidget->setItem(0, 1, new QTableWidgetItem(QString()));  // 价格
            ui->dishTableWidget->item(0, 1)->setTextAlignment(Qt::AlignCenter);
            ui->dishTableWidget->setItem(0, 2, new QTableWidgetItem(QString()));  // 数量
            ui->dishTableWidget->item(0, 2)->setTextAlignment(Qt::AlignCenter);
            ui->dishTableWidget->insertRow(0);
        }
        */

        //商品如果有规格的话，商品的规格显示在单元格的第二行，并且字体颜色都有限制
        if(!property_tags.isEmpty()) {
             QString propStr = property_tags.replace(",", "+");
             name.append(QString::fromLocal8Bit("\r\n").append(QString("<font size =6 color=rgb(150,150,150)>%1</font>").arg(propStr)));
        }


        ui->dishTableWidget->setItem(i, 0, new QTableWidgetItem(name));  // 商品名
        ui->dishTableWidget->item(i, 0)->setTextAlignment(Qt::AlignLeft);
        ui->dishTableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(orderObject->proList.at(i)->price/100.0)));  // 价格
        ui->dishTableWidget->item(i, 2)->setTextAlignment(Qt::AlignCenter);
        ui->dishTableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(orderObject->proList.at(i)->product_amount)));  // 数量
        ui->dishTableWidget->item(i, 1)->setTextAlignment(Qt::AlignCenter);
    }

    //商品汇总信息显示在tablewidget中
//    ui->sumTableWidget->setItem(0, 0, new QTableWidgetItem(QString::number(orderObject->total_amount)));
//    ui->sumTableWidget->item(0, 0)->setTextAlignment(Qt::AlignCenter);
//    ui->sumTableWidget->setItem(0, 1, new QTableWidgetItem(QString::number(orderObject->total_fee/100.0)));
//    ui->sumTableWidget->item(0, 1)->setTextAlignment(Qt::AlignCenter);
//    ui->sumTableWidget->setItem(1, 1, new QTableWidgetItem(QString::number(orderObject->package_fee/100.0)));
//    ui->sumTableWidget->item(1, 1)->setTextAlignment(Qt::AlignCenter);
//    ui->sumTableWidget->setItem(2, 1, new QTableWidgetItem(QString::number(orderObject->send_fee/100.0)));
//    ui->sumTableWidget->item(2, 1)->setTextAlignment(Qt::AlignCenter);

//    int dis_amount = -(orderObject->dis_platform_fee + orderObject->dis_shop_fee)/100.0;

//    ui->sumTableWidget->setItem(3, 1, new QTableWidgetItem(QString::number(dis_amount)));
//    ui->sumTableWidget->item(3, 1)->setTextAlignment(Qt::AlignCenter);

    ui->product_numLb->setText(QString::number(orderObject->total_amount));
    ui->product_price_Lb->setText(QString::number(orderObject->total_fee/100.0));

    ui->package_price_Lb->setText(QString::number(orderObject->package_fee/100.0));
    ui->delivery_price_Lb->setText(QString::number(orderObject->send_fee/100.0));

    int dis_amount = -(orderObject->dis_platform_fee + orderObject->dis_shop_fee)/100.0;
    ui->promotion_price_Lb->setText(QString::number(dis_amount));


    ui->sumLb_dec->setText(QString::fromLocal8Bit("<font color=red>%1</font>").arg(QString::number(orderObject->shop_fee/100.0)));

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

        if(btn3opt == OPERATIONNAME_COMPLETE) {
            ui->detailBtn3->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(255, 43, 42);color:white;font: 9pt \"微软雅黑\";}"));
        } else if(btn3opt == OPERATIONNAME_SENDOUT) {
            ui->detailBtn3->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(0, 109, 171);color:white;font: 9pt \"微软雅黑\";}"));
        } else if(btn3opt == OPERATIONNAME_GETDELIVERS) {
            ui->detailBtn3->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(0, 169, 115);color:white;font: 9pt \"微软雅黑\";}"));
        } else if(btn3opt == OPERATIONNAME_MAKEOVER) {
            ui->detailBtn3->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(0, 109, 171);color:white;font: 9pt \"微软雅黑\";}"));
        } else if(btn3opt == OPERATIONNAME_REFUNDORDER) {
            ui->detailBtn3->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(255, 43, 42);color:white;font: 9pt \"微软雅黑\";}"));
        }
    }
    else
    {
        ui->detailBtn3->hide();
    }

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

        if(btn2opt == OPERATIONNAME_REFUNDNEWORDER) {
            ui->detailBtn2->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(255, 43, 42);color:white;font: 9pt \"微软雅黑\";}"));
        } else if(btn2opt == OPERATIONNAME_REFUSEREFUND) {
            ui->detailBtn2->setStyleSheet(QString::fromLocal8Bit("QPushButton{background-color:rgb(255, 43, 42);color:white;font: 9pt \"微软雅黑\";}"));
        }
    }
    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 NewDetailForm::_Init()
{
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);
    setGeometry(((QWidget*)parent())->geometry());

    ui->dishTableWidget->verticalHeader()->setHidden(true);
    ui->dishTableWidget->setShowGrid(false);
    ui->dishTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->dishTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->dishTableWidget->horizontalHeaderItem(0)->setTextAlignment(Qt::AlignLeft);

    int tableWidth = this->width()/2 - 50;
    ui->dishTableWidget->setColumnWidth(0, tableWidth*5/9);
    ui->dishTableWidget->setColumnWidth(1, tableWidth*2/9);
    ui->dishTableWidget->setColumnWidth(2, tableWidth*2/9);
    ui->dishTableWidget->horizontalHeader()->setFixedHeight(25);
    ui->dishTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    //设置QTableWidget表头样式
    ui->dishTableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{background-color:white;font:11pt '微软雅黑';color: rgb(150,150,150);};");



//    ui->sumTableWidget->setColumnWidth(0, tableWidth*5/9);
//    ui->sumTableWidget->setColumnWidth(1, tableWidth*2/9);
//    ui->sumTableWidget->setColumnWidth(2, tableWidth*2/9);
//    ui->sumTableWidget->horizontalHeader()->setFixedHeight(25);
//    ui->sumTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);

//    ui->sumTableWidget->setShowGrid(false);
//    ui->sumTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    ui->sumTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

//    ui->sumTableWidget->horizontalHeader()->setHidden(true);
//    ui->sumTableWidget->setColumnCount(2);
//    ui->sumTableWidget->setColumnWidth(0, tableWidth*2/9);
//    ui->sumTableWidget->setColumnWidth(1, tableWidth*2/9);
//    ui->sumTableWidget->setRowHeight(0,40);
//    ui->sumTableWidget->setRowHeight(1,40);
//    ui->sumTableWidget->setRowHeight(2,40);
//    ui->sumTableWidget->setRowHeight(3,40);
//    ui->sumTableWidget->verticalHeader()->setFixedWidth(tableWidth*5/9);
//    ui->sumTableWidget->verticalHeader()->setFixedHeight(25);
//    ui->sumTableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);

    //设置QTableWidget表头样式
//    ui->sumTableWidget->verticalHeader()->setStyleSheet("QHeaderView::section{background-color:white;font:11pt '微软雅黑';color: rgb(150,150,150);};");

    //显示商品汇总信息
    ui->productLb->setFixedWidth(tableWidth*5/9);
    ui->productLb->setAlignment(Qt::AlignLeft);
    ui->product_numLb->setFixedWidth(tableWidth*2/9);
    ui->product_numLb->setAlignment(Qt::AlignHCenter);
    ui->product_price_Lb->setFixedWidth(tableWidth*2/9);
    ui->product_price_Lb->setAlignment(Qt::AlignHCenter);

    ui->packageLb->setFixedWidth(tableWidth*5/9);
    ui->packageLb->setAlignment(Qt::AlignLeft);
    ui->package_num_Lb->setFixedWidth(tableWidth*2/9);
    ui->package_num_Lb->setAlignment(Qt::AlignHCenter);
    ui->package_price_Lb->setFixedWidth(tableWidth*2/9);
    ui->package_price_Lb->setAlignment(Qt::AlignHCenter);

    ui->deliveryLb->setFixedWidth(tableWidth*5/9);
    ui->deliveryLb->setAlignment(Qt::AlignLeft);
    ui->delivery_num_Lb->setFixedWidth(tableWidth*2/9);
    ui->delivery_num_Lb->setAlignment(Qt::AlignHCenter);
    ui->delivery_price_Lb->setFixedWidth(tableWidth*2/9);
    ui->delivery_price_Lb->setAlignment(Qt::AlignHCenter);

    ui->promotionLb->setFixedWidth(tableWidth*5/9);
    ui->promotionLb->setAlignment(Qt::AlignLeft);
    ui->promotion_num_Lb->setFixedWidth(tableWidth*2/9);
    ui->promotion_num_Lb->setAlignment(Qt::AlignHCenter);
    ui->promotion_price_Lb->setFixedWidth(tableWidth*2/9);
    ui->promotion_price_Lb->setAlignment(Qt::AlignHCenter);

    ui->sumLb->setFixedWidth(tableWidth*5/9);
    ui->sumLb->setAlignment(Qt::AlignLeft);
    ui->sumLb_dec_1->setFixedWidth(tableWidth*2/9);
    ui->sumLb_dec->setFixedWidth(tableWidth*2/9);
    ui->sumLb_dec->setAlignment(Qt::AlignHCenter);
}

void NewDetailForm::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()==QString::fromLocal8Bit("拒单"))
    {
        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);
}

bool NewDetailForm::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 NewDetailForm::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 NewDetailForm::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 NewDetailForm::on_detailBtn0_clicked()
{

}
