#include "detailForm.h"
#include "ui_detailForm.h"
#include "DTools/util.h"
#include "preDefine.h"
#include "DTools/configManger.h"
#include "Control/flowControl.h"
#include "QsLog.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);
    connect(this, &DetailForm::processRepealOrder, &FlowControl::GetInstance(), &FlowControl::onProcessRepealOrder);
    connect(this, &DetailForm::processRetryInputOrder, &FlowControl::GetInstance(), &FlowControl::onProcessRetryInputOrder);

    m_rejectForm=NULL;
    m_refuseForm=NULL;
    _Init();
}

DetailForm::~DetailForm()
{
    QLOG_INFO() << QString("[<<<<---DetailForm::~DetailForm: begin--->>>>]");
    delete ui;
    // New 时指定了父类对象指针;
    QLOG_INFO() << QString("[<<<<---DetailForm::~DetailForm: end--->>>>]");
}

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

    ui->detailBtn3->show();
    ui->detailBtn1->hide();
    ui->detailBtn0->hide();
    // 初始化界面
    ui->detailLab0->setText(QString("[%1 # %2][%3][%4]").arg(QString::number(orderObject->orderIndex),orderObject->getChannelName(),
                                                        orderObject->getOrderStatusDec(),
                                                        orderObject->id));
    QLOG_INFO() << QString("[<<<<---DetailForm::InitData   ui->detailLab0->setText --->>>>]");
    ui->detailLab1->setText(QString("[ %1 ]:[ %2 ]:[%3:%4]").arg(orderObject->consigneeName,orderObject->consigneePhone,
                                                             QString::fromLocal8Bit("暗号"),orderObject->secretSignal));

    //订单完成后,送达时间需要更新为 finishTime
    QString deliveryFinishTime = "";

    if (OrderObject::Finished == orderObject->orderStatus) {
        deliveryFinishTime = (orderObject->finishTime.isEmpty() || 0==orderObject->finishTime.length() )? QString::fromLocal8Bit("已经送达") : orderObject->finishTime;
    } else if (OrderObject::Refunded == orderObject->orderStatus) {
        deliveryFinishTime = "                            ";
    } else {
        deliveryFinishTime = orderObject->deliveryTime;
    }

    if (7 == orderObject->orderType  || 11 == orderObject->orderType )  {
        deliveryFinishTime = deliveryFinishTime + QString::fromLocal8Bit(" 预约时间: ") + orderObject->expectDate;
    }

    ui->detailLab2->setText(deliveryFinishTime);

    QLOG_INFO() << QString("[<<<<---DetailForm::InitData   ui->detailLab2->setText --->>>>]");

    ui->detailLab3->setText(orderObject->riderName.isEmpty() ? QString::fromLocal8Bit("暂未指定") : QString::fromLocal8Bit("[姓名]%1 [电话]%2")
                                                                            .arg(orderObject->riderName, orderObject->riderPhone));
//TODO
    ui->detailLab4->setText(Penny2Dollar(orderObject->totalPrice));

    //先隐藏发票信息
    //ui->detailLab6->setText(orderObject->needInvoice? orderObject->invoiceTitle : QString::fromLocal8Bit("不需要发票"));
    ui->detailSlab6->setText(QString::fromLocal8Bit("三方订单号"));
    ui->detailLab6->setText(orderObject->thirdPartyOrderId);
    QLOG_INFO() << QString("[<<<<---DetailForm::InitData   ui->detailSlab6 --->>>>]");

    ui->detailLab7->setText(orderObject->msr_no.length()? orderObject->msr_no : orderObject->customerId);  // MSR_NO
    ui->detailLab5->setText( QString("[%1 | %2 ]").arg( orderObject->memo).arg(orderObject->consumerRemark) );
    int i = 0, pNum = 0, coupNum = 0;
    /*********************************** 遍历 商品列表：商品信息展示 begin ***************************************************/
    for(; i<orderObject->proList.count(); i++,pNum++)
    {
        ui->detailTable0->insertRow(pNum);
        ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(GetProductName(orderObject->proList.at(i))));  // 商品名
        ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignCenter);
        //客诉单商品价格需要显示为 0；
        if("MOD" == orderObject->channel && 3 == orderObject->orderType){
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem(QString("0")));
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
        }else{
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem(Penny2Dollar(orderObject->proList.at(i)->price)));  // 价格
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
        }
        QLOG_INFO() << QString("[<<<<---DetailForm::InitData   ui->detailTable0 --->>>>]");
        //ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem(Penny2Dollar(orderObject->proList.at(i)->price)));  // 价格
        //ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);

        ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(orderObject->proList.at(i)->qty)));  // 数量
        ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignCenter);

        // 选项太多,不便于显示;
        /******************* 遍历 配料列表：配料信息展示 begin ***********************/
        int j = 0;
        dishesObject* tempDishObj = orderObject->proList[i];
        for(; j<tempDishObj->sub_products.count(); j++)
        {
            if(tempDishObj->sub_products.at(j)->price > 0){
                pNum++;
                ui->detailTable0->insertRow(pNum);
                ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(QString("( ") + GetProductName(tempDishObj->sub_products.at(j)) ));  // 商品名
                ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignRight);
                ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem(Penny2Dollar(tempDishObj->sub_products.at(j)->price)));  // 价格
                ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
                ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(tempDishObj->sub_products.at(j)->qty) +QString(" )") ));  // 数量
                ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignLeft);
            }
        } 
        /******************* 遍历 配料列表：配料信息展示 end *************************/
        // 新增展示优惠活动的优惠项
        if(tempDishObj->promotionSku.length()){
            pNum++;
            ui->detailTable0->insertRow(pNum);
            ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(QString("( ") + tempDishObj->promotionName + QString(":")  + tempDishObj->promotionSku));  // 商品名
            ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignRight);
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( QString("-") + Penny2Dollar(tempDishObj->promotionPrice)));  // 价格
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(tempDishObj->promotionQty) +QString(" )") ));  // 数量
            ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignLeft);
        }

        // 新增展示 星星优惠活动 的优惠项
        if(tempDishObj->starPromotionSku.length()){
            pNum++;
            ui->detailTable0->insertRow(pNum);
            ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(QString("( ") + tempDishObj->starPromotionName + QString(":") +tempDishObj->starPromotionSku ));  // 商品名
            ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignRight);
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( QString("-") + Penny2Dollar(tempDishObj->starPromotionPrice)));  // 价格
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(tempDishObj->starPromotionQty) +QString(" )") ));  // 数量
            ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignLeft);
        }

    }
    /*********************************** 遍历 商品列表：商品信息展示 end ***************************************************************/
    /*********************************** 遍历 预约实物 券列表：券信息展示 begin *********************************************************/
    for(; coupNum<orderObject->coupList.count(); coupNum++,pNum++)
    {
        CouponsObject* tempCouponObj = orderObject->coupList[coupNum];
        ui->detailTable0->insertRow(pNum);
        QString tempName = tempCouponObj->name.length()?tempCouponObj->name:QString::fromLocal8Bit("券");
        tempName.append("\r\n");
        tempName.append(tempCouponObj->code);
        ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(tempName));  // 券名+券号码
        ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem(QString('-')));  // 券价格
        ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(1)));  // 券数量
        ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignCenter);
        // 新增展示券号码;
        if(tempCouponObj->code.length()){
            pNum++;
            ui->detailTable0->insertRow(pNum);
            ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(tempCouponObj->code));  // 券号码
            ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignRight);
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( QString("-")));
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString("-") ));
            ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignLeft);
        }
        // 新增展示券优惠项;
        if(tempCouponObj->discount.length()){
            pNum++;
            ui->detailTable0->insertRow(pNum);
            ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem( QString::fromLocal8Bit("券折扣:") ));  // 券号折扣
            ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignRight);
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( Penny2Dollar(tempCouponObj->consumeDiscountAmount) ));
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString("1") ));
            ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignLeft);
        }
    }
    /*********************************** 遍历 预约实物 券列表：券信息展示 end *********************************************************/

    // 打包费
    if ( !orderObject->packageFeeAtProduct ) {
        ui->detailTable0->insertRow(pNum);
        ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(QString::fromLocal8Bit("包装费:") + QString("6000201") ));  // 包装费
        ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem(Penny2Dollar(orderObject->packageFee)));  // 价格
        ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(1)));  // 数量
        ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignCenter);
        pNum = pNum + 1;
        // 新增展示打包费折扣项显示;
        if (orderObject->packDiscount> 0 && orderObject->packDiscount<10000){
            ui->detailTable0->insertRow(pNum);
            ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem( QString("( ") + QString::fromLocal8Bit("包装费折扣")));  // 包装费折扣
            ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignRight);
            ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( QString("-") + Penny2Dollar(orderObject->packDiscount)));  // 价格
            ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
            ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(1) +QString(" )" )));  // 数量
            ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignLeft);
            pNum = pNum + 1;
        }
    }

    // 新增展示整单折扣项显示;
    if (orderObject->orderDiscount> 0){
        ui->detailTable0->insertRow(pNum);
        ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(QString::fromLocal8Bit("整单折扣")));
        ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( QString("-") + Penny2Dollar(orderObject->orderDiscount)));  // 价格
        ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(1)));  // 数量
        ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignCenter);
        pNum = pNum + 1;
    }

    // 新增展示平台折扣项显示;
    if (abs(orderObject->disPlateformFee) > 0){
        ui->detailTable0->insertRow(pNum);
        ui->detailTable0->setItem(pNum, 0, new QTableWidgetItem(QString::fromLocal8Bit("平台折扣")));
        ui->detailTable0->item(pNum, 0)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 1, new QTableWidgetItem( QString("-") + Penny2Dollar(abs(orderObject->disPlateformFee))));
        ui->detailTable0->item(pNum, 1)->setTextAlignment(Qt::AlignCenter);
        ui->detailTable0->setItem(pNum, 2, new QTableWidgetItem(QString::number(1)));  // 数量
        ui->detailTable0->item(pNum, 2)->setTextAlignment(Qt::AlignCenter);
        pNum = pNum + 1;
    }

    //设置行高根据文字进行自适应;用来重复显示主商品的配料信息;
    ui->detailTable0->resizeRowsToContents();

    ui->detailBtn2->setText(GetOperNameByStatus(orderObject->orderStatus, true));
    ui->detailBtn2->setProperty("operation", GetOperByStatus(orderObject->orderStatus, true));
    ui->detailBtn2->setProperty("orderId", orderObject->id);
    if(orderObject->orderStatus != 1 && orderObject->orderStatus != 20 && orderObject->orderStatus != 2 && orderObject->orderStatus != 3 && orderObject->orderStatus != OrderObject::SimExceptSale)
    {
        ui->detailBtn2->hide();
    }
    //星巴克:客诉单/MOP渠道/ORS渠道，不能显示退单按钮；
    if(3 == orderObject->getOrderType() || "MOP" == orderObject->channel || "MT-MOP" == orderObject->channel || "ORS" == orderObject->channel) {
        ui->detailBtn2->hide();
    }

    //星巴克:电商-MOP 需要显示退单按钮(便于 当日退 / 跨日退)；
    if ( ( "EC-MOP" == orderObject->channel || "EC_WECHAT_MOP" == orderObject->channel )  && OrderObject::Refunded != orderObject->orderStatus ) {
        ui->detailBtn2->show();
    }

    //订单入机失败 [销售单 / 退货单] 需要显示 重新录单 按钮 方便店员再次触发录单；
    if(OrderObject::SimExceptSale == orderObject->orderStatus || OrderObject::SimExceptRefund == orderObject->orderStatus) {
       ui->detailBtn0->show();
    }

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

    if(!GetOperByStatus(orderObject->orderStatus).compare("NULL"))
    {
        ui->detailBtn3->hide();
    }
    if(m_rejectForm==NULL)
        m_rejectForm = new RejectForm(this);
    if(m_refuseForm==NULL)
        m_refuseForm = new RefuseForm(this);
#ifdef TODO
    ui->detailBtn3->hide();
#endif
}

void DetailForm::_Init()
{
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);

    setGeometry(((QWidget*)parent())->geometry());

    int tableWidth = this->width()/2 - 65;
    ui->detailTable0->setColumnWidth(0, tableWidth*12/15);
    ui->detailTable0->setColumnWidth(1, tableWidth*2/15);
    ui->detailTable0->setColumnWidth(2, tableWidth*1/15);
    ui->detailTable0->horizontalHeader()->setFixedHeight(25);
    ui->detailTable0->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);
}

QString DetailForm::GetProductName(dishesObject *dish)
{
    QString name;
    QString propertyTags;
    name.append(dish->name).append("\r\n");
    propertyTags=dish->code;
    if(!propertyTags.isEmpty())
    {
        name.append(QString("(%1)").arg(propertyTags));
        name.append("\r\n");
    }

    if(!dish->sub_products.isEmpty())
    {
        foreach(auto value,dish->sub_products)
        {
            name.append("| ");
            name.append(value->name);
            if ( !( value->code.contains("Default",Qt::CaseInsensitive) ) ) {
                name.append(':').append(value->code);
            }
            name.append(" |").append("\r\n");

        }
    }
    name.remove((name.length()-1),1);
    return name;
}

void DetailForm::onOperaBtnClicked()
{
    QLOG_INFO() << QString("[<<<<---DetailForm::onOperaBtnClicked: begin:--->>>>]");
    //hide(); //隐藏详情界面将会产生一种BUG: 在选择退货原因时，详情页面+主界面都隐藏了，即使不退货，点击取消，主程序也会崩溃(无dump文件)；
    //hide(); //为了友好用户的使用体验感，hide() 还是需要在接受完取消订单原因后，再隐藏；
    QPushButton *pBtn = (QPushButton*)sender();
    if(pBtn->text()==QString::fromLocal8Bit("拒单")||pBtn->text()==QString::fromLocal8Bit("退单"))
    {
        m_refuseForm->SetOrderInfo(m_orderObject);
        m_refuseForm->show();
        QLOG_INFO() << QString("[<<<<---DetailForm::onOperaBtnClicked: QPushButton:--->>>>]")<<pBtn->text();
        if(m_refuseForm->exec()==QDialog::Accepted)
        {
            QLOG_INFO() << QString("[<<<<---DetailForm::onOperaBtnClicked: m_refuseForm->exec()==QDialog::Accepted--->>>>]");
            QLOG_INFO() << QString("[<<<<---DetailForm::onOperaBtnClicked: --->>>>]")<<m_refuseForm->m_reasonCode<<m_refuseForm->m_reasonStr<<m_refuseForm->m_refundDishesListString;
            emit processRepealOrder( pBtn->property("orderId").toString(),m_refuseForm->m_reasonCode,m_refuseForm->m_reasonStr,m_refuseForm->m_refundDishesListString);
            hide(); //为了友好用户的使用体验感，hide() 还是需要在接受完取消订单原因后，再隐藏；
        }
    } else {
        emit processOrder(pBtn->property("operation").toString(), pBtn->property("orderId").toString());
    }

}

void DetailForm::on_detailBtn1_clicked()
{
}

void DetailForm::on_detailBtn0_clicked()
{
    QLOG_INFO()<<QString("[<<<<---DetailForm::on_detailBtn0_clicked: begin:--->>>>]")<<QString("重新录单")<< m_orderObject->id;
    if(m_orderObject) {
        emit processRetryInputOrder(m_orderObject->id);
        this->hide();
    } else {
        QLOG_ERROR()<<QString("[<<<<---DetailForm::on_detailBtn0_clicked: m_orderObject point is NULL--->>>>]");
    }
}


void DetailForm::hideDetailAllFrom()
{
    QLOG_INFO()<<QString("[<<<<---DetailForm::hideDetailAllFrom: begin:--->>>>]");

    if ( m_refuseForm && m_refuseForm->isVisible() ) {
        //delete m_refuseForm;
        //m_refuseForm = NULL;
        m_refuseForm->hideSelectProductFrom();
        m_refuseForm->reject();
    }

    /*
    if ( m_printTicketSelectForm && m_printTicketSelectForm->isVisible() ) {
        m_printTicketSelectForm->reject();
        m_printTicketSelectForm->hide();
    }
    */

    QLOG_INFO()<<QString("[<<<<---DetailForm::hideDetailAllFrom: middle:--->>>>]");

     this->hide();

    QLOG_INFO()<<QString("[<<<<---DetailForm::hideDetailAllFrom: Finished:--->>>>]");
}
