#include "newmainform.h"
#include "ui_newmainform.h"
#include "model/orderObject.h"
#include "model/posorderpool.h"
#include "view/ordertypeform.h"
#include "view/orderoptform.h"

#include "QsLog.h"
#include "base/System/GetPrinters.h"

#include "event/fmapplication.h"
#include "event/posevent.h"

#include <QDebug>
#include <QScrollBar>

NewMainForm::NewMainForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NewMainForm)
{
    _curr_page_num = 1;
    _curr_check_btn = NULL;
    ui->setupUi(this);
    InitClassify();
    InitMainBtn();
    InitPrtSettingWidget();
    InitPrtConfig();
    InitWidget(MAIN_ORDER);
    ui->newmaintbwgt->setCurrentIndex(0);
    InitPrtList();
    InitTableWidget();

#ifdef FM_ORDER_TEST

//    //订单原始状态(推了一个订单号时使用)
//    DefaultOrder = -100,
//    //锁定订单
//    LockOrder = -1,
//    //新订单
//    NewOrder = 1,
//    //确认订单
//    FirmOrder =2,
//    //取消订单
//    CancelOrder=3,
//    //配送中
//    DispatchingOrder = 4,
//    //制作完成
//    InDevelopment = 5,
//    //已送达
//    ServiceOrder = 6,
//    //申请退款
//    ApplicationRefundOrder = 20,
//    //申请部分退款
//    ApplicationPartialRefundOrder = 22,
//    //同意退款
//    ApprovalRefundOrder = 30,
//    //不同意退款
//    RefusingRefundOrder = 40,
//    //退款完成
//    CompleteRefundOrder = 100,
//    //完成订单
//    CompleteOrder = 200,

    //------------------------------------------test
    OrderObject order;
    order.status = NewOrder;
    order.refund_status = DefaultOrder;
    order.order_id = "0";
    order.order_index = 0;
    order.channel_name = "hungry";
    order.phone = "66666666";
    order.customer = "ldd";
    order.shop_fee = 688;
    InsertTableWidget(order);
    OrderObject order1;
    order1.status = FirmOrder;
    order1.refund_status = DefaultOrder;
    order1.order_index = 1;
    InsertTableWidget(order1);
    OrderObject order2;
    order2.status = FirmOrder;
    order2.refund_status = ApplicationRefundOrder;
    order2.order_index = 2;
    InsertTableWidget(order2);
    OrderObject order3;
    order3.status = InDevelopment;
    order3.refund_status = DefaultOrder;
    order3.order_index = 3;
    InsertTableWidget(order3);
    OrderObject order4;
    order4.status = InDevelopment;
    order4.refund_status = DefaultOrder;
    order4.order_index = 4;
    InsertTableWidget(order4);
    OrderObject order5;
    order5.status = InDevelopment;
    order5.refund_status = DefaultOrder;
    order5.order_index = 5;
    InsertTableWidget(order5);
    OrderObject order6;
    order6.status = InDevelopment;
    order6.refund_status = DefaultOrder;
    order6.order_index = 6;
    InsertTableWidget(order6);
    OrderObject order7;
    order7.status = InDevelopment;
    order7.refund_status = DefaultOrder;
    order7.order_index = 7;
    InsertTableWidget(order7);
    OrderObject order8;
    order8.status = InDevelopment;
    order8.refund_status = DefaultOrder;
    order8.order_index = 8;
    InsertTableWidget(order8);
    OrderObject order9;
    order9.status = InDevelopment;
    order9.refund_status = DefaultOrder;
    order9.order_index = 9;
    InsertTableWidget(order9);
    OrderObject order10;
    order10.status = InDevelopment;
    order10.refund_status = DefaultOrder;
    order10.order_index = 10;
    InsertTableWidget(order10);
    OrderObject order11;
    order11.status = InDevelopment;
    order11.refund_status = DefaultOrder;
    order11.order_index = 11;
    InsertTableWidget(order11);
    OrderObject order12;
    order12.status = InDevelopment;
    order12.refund_status = DefaultOrder;
    order12.order_index = 12;
    InsertTableWidget(order12);
    OrderObject order13;
    order13.status = InDevelopment;
    order13.refund_status = DefaultOrder;
    order13.order_index = 13;
    InsertTableWidget(order13);
    OrderObject order14;
    order14.status = InDevelopment;
    order14.refund_status = DefaultOrder;
    order14.order_index = 14;
    InsertTableWidget(order14);
    OrderObject order15;
    order15.status = InDevelopment;
    order15.refund_status = DefaultOrder;
    order15.order_index = 15;
    InsertTableWidget(order15);
    OrderObject order16;
    order16.status = InDevelopment;
    order16.refund_status = DefaultOrder;
    order16.order_index = 16;
    order16.order_type = AppointmentTakeout;
    InsertTableWidget(order16);
    OrderObject order17;
    order17.status = InDevelopment;
    order17.refund_status = DefaultOrder;
    order17.order_index = 17;
    order17.order_type = LockOrder;
    order17.status = CompleteOrder;
    InsertTableWidget(order17);
    OrderObject order18;
    order18.status = InDevelopment;
    order18.refund_status = DefaultOrder;
    order18.order_index = 18;
    order18.order_type = AppointmentTakeout;
    order18.status = DispatchingOrder;
    InsertTableWidget(order18);
    OrderObject order19;
    order19.status = InDevelopment;
    order19.refund_status = DefaultOrder;
    order19.order_index = 19;
    order19.order_type = AppointmentTakeout;
    order19.status = FirmOrder;
    InsertTableWidget(order19);
    OrderObject order20;
    order20.order_type = AppointmentTakeout;
    order20.status = InDevelopment;
    order20.refund_status = DefaultOrder;
    order20.order_index = 20;
    order20.order_type = AppointmentTakeout;
    order20.status = NewOrder;
    InsertTableWidget(order20);

    OrderObject order21;
    order21.order_type = AppointmentTakeout;
    order21.status = InDevelopment;
    order21.refund_status = DefaultOrder;
    order21.order_index = 21;
    order21.order_type = AppointmentTakeout;
    order21.status = NewOrder;
    InsertTableWidget(order21);

    OrderObject order22;
    order22.order_type = AppointmentTakeout;
    order22.status = InDevelopment;
    order22.refund_status = CompleteRefundOrder;
    order22.order_index = 22;
    order22.order_id = "22";
    order22.order_type = AppointmentTakeout;
    order22.status = NewOrder;
    InsertTableWidget(order22);

    OrderObject order23;
    order23.order_type = AppointmentTakeout;
    order23.status = InDevelopment;
    order23.refund_status = DefaultOrder;
    order23.order_index = 23;
    order23.order_id = "23";
    order23.order_type = AppointmentTakeout;
    order23.status = NewOrder;
    InsertTableWidget(order23); 
    //------------------------------------------test
#endif




    FMApplication::subscibeEvent(this, PosEvent::s_login_status);
    FMApplication::subscibeEvent(this, PosEvent::s_opt_status);
    FMApplication::subscibeEvent(this, PosEvent::s_change_order);
    FMApplication::subscibeEvent(this, PosEvent::s_get_order_status);
    FMApplication::subscibeEvent(this, PosEvent::s_delete_order);
    FMApplication::subscibeEvent(this, PosEvent::s_login_storeinfo);
    FMApplication::subscibeEvent(this, PosEvent::s_show_mainform);
    FMApplication::subscibeEvent(this, PosEvent::s_network_outtime);

    this->show();
}

void NewMainForm::FullShow()
{
    this->show();
    InitPageNum();
}

void NewMainForm::InitPageNum()
{
    int num = ui->newmaintablewidget_order->height()/36;

    int page =  _curr_page_num/(num - 1) ;

    if(_curr_page_num %(num - 1) != 0)
        ++ page;

    //qDebug() << "+++++++" << num << ";" << "page" << page << ";" << _curr_page_num;

    _curr_page = 1;
    ui->newmaintablewidget_order->verticalScrollBar()->setValue(0);
    ui->newmainlabel_allnum->setText(QString::fromUtf8("\xE5\x85\xB1%1\xE6\x9D\xA1").arg(QString::number(_curr_page_num)));
    if (page != 0)
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(page));
    else
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString("1"));
    ui->newmaintablewidget_order->viewport()->setFixedHeight((num - 1) * 36);
}

void NewMainForm::InitPrtList()
{
    QStringList list;
    GetPrinters::HasPrintersName(list);
    for(int i = 0; i < list.size(); ++ i)
    {
        ui->newmaincombx_name->addItem(list[i]);
    }
    ui->newmainline_name->setText(ui->newmaincombx_name->currentText());
}

void NewMainForm::InitPrtConfig()
{
    QString needprtpath = qApp->applicationDirPath() + "/" + PREINTER_NEED;
    _other_prt_num = QSettings(needprtpath, QSettings::IniFormat).value(INI_NEEDPTRNUM,0).toInt();
    int labelnumber = QSettings(needprtpath, QSettings::IniFormat).value(INI_NEEDLABEL,0).toInt();

    //兼容旧版本
    if(_other_prt_num == 0 && QSettings(needprtpath, QSettings::IniFormat).value(INI_NEEDPTR,0).toInt() != 0)
    {
        _other_prt_num = 1;
        NewMainFormDataProcess::SetOtherPrintNum(_other_prt_num);
    }

    QString section = "Printer";
    QString comsection = "COMDEF";

    NewMainFormDataProcess::GetPrintIni(section, comsection, _main_prt_configs);

    if (labelnumber != 0)
    {
        NewMainFormDataProcess::GetPrintIni(section, comsection, _label_prt_configs);
    }

    for(int i = 0; i < _other_prt_num; ++i)
    {
        QString section = "OtherPrinter";
        QString comsection = "OTHERCOMDEF";
        QMap<QString,QString> tmpmap;

        if(i == 0)
        {
            NewMainFormDataProcess::GetPrintIni(section, comsection, tmpmap);
        }
        else
        {
            section += QString::number(i+1);
            comsection += QString::number(i+1);
            NewMainFormDataProcess::GetPrintIni(section, comsection, tmpmap);

        }
        QString prtlist = QString::fromUtf8("\xE5\x90\x8E\xE5\x8E\xA8\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA") + QString::number(i+1);
        ui->newmaincombx_prttype->addItem(prtlist);
        _other_prt_configs.append(tmpmap);
    } 
}

bool NewMainForm::ClassifyOrder(QString type)
{
    int tmptype = type.toInt();
    switch (tmptype) {
    case TYPE_NEEDREFUND:
        ClassifyOrderWithOrderStatus(ApplicationRefundOrder);
        break;
    case TYPE_REFUNDED:
        ClassifyOrderWithOrderStatus(CancelOrder);
        break;
    case TYPE_ALL:
        ClassifyOrderWithOrderStatus(DefaultOrder);
        break;
    case TYPE_NEW:
        ClassifyOrderWithOrderStatus(NewOrder);
        break;
    case TYPE_MAKE:
        ClassifyOrderWithOrderStatus(FirmOrder);
        break;
    case TYPE_SEND:
        ClassifyOrderWithOrderStatus(DispatchingOrder);
        break;
    case TYPE_NAKEOVER:
        ClassifyOrderWithOrderStatus(InDevelopment);
        break;
    case TYPE_OVER:
        ClassifyOrderWithOrderStatus(CompleteOrder);
        break;
    case TYPE_FUTURE:
        ClassifyOrderWithOrderType();
        break;
    default:
        return false;
    }
    return true;
}

void NewMainForm::ClassifyOrderWithOrderType()
{
    _curr_page_num = 0;
    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = (OrderTypeForm *)table->cellWidget(i, 1);

        if(pwd->order_type() == AppointmentTakeout ||
                pwd->order_type() == AppointmentDining ||
                pwd->order_type() == AppointmentInvite)
        {
            table->setRowHidden(i, false);
            ++_curr_page_num;
        }
        else
        {
            table->setRowHidden(i, true);
        }
    }
}

void NewMainForm::ClassifyOrderWithOrderStatus(int order_status)
{
    _curr_page_num = 0;

    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = NULL;

        switch (order_status) {
        case DefaultOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == NewOrder || pwd->GetOrderStatus() == FirmOrder ||
                    pwd->GetOrderStatus() == DispatchingOrder || pwd->GetOrderStatus() == DispatchingOrder ||
                    pwd->GetOrderStatus() == InDevelopment || pwd->GetOrderStatus() == CompleteOrder ||
                    pwd->GetOrderStatus() == ServiceOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case NewOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == NewOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case FirmOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1); 
            if(pwd->GetOrderStatus() == FirmOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case DispatchingOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == DispatchingOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case InDevelopment:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == InDevelopment)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case ApplicationRefundOrder:
        case ApplicationPartialRefundOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == ApplicationRefundOrder || pwd->GetOrderStatus() == ApplicationPartialRefundOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case LockOrder:
        case CancelOrder:
        case ApprovalRefundOrder:
        case CompleteRefundOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            //qDebug()<<"-----" << pwd->GetOrderStatus() << ";" << pwd->order_id() << ";" << pwd->refund_status() << ";" << pwd->order_status();
            if(pwd->GetOrderStatus() == ApprovalRefundOrder || pwd->GetOrderStatus() == CompleteRefundOrder
                    || pwd->GetOrderStatus() == LockOrder || pwd->GetOrderStatus() == CancelOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        case CompleteOrder:
        case ServiceOrder:
            pwd = (OrderTypeForm *)table->cellWidget(i, 1);
            if(pwd->GetOrderStatus() == CompleteOrder || pwd->GetOrderStatus() == ServiceOrder)
            {
                table->setRowHidden(i, false);
                ++_curr_page_num;
            }
            else
                table->setRowHidden(i, true);
            break;
        default:
            table->setRowHidden(i, true);
            break;
        }
    }
}

void NewMainForm::InitMainBtn()
{
    ui->newmainbtn_order->SetText("\xE8\xAE\xA2\xE5\x8D\x95\xE7\xAE\xA1\xE7\x90\x86", MAIN_ORDER);
    ui->newmainbtn_refund->SetText("\xE9\x80\x80\xE5\x8D\x95", MAIN_REFUND);
    ui->newmainbtn_set->SetText("\xE8\xAE\xBE\xE7\xBD\xAE", MAIN_SET);
    ui->newmainbtn_order->setProperty("type", "order");
    ui->newmainbtn_refund->setProperty("type", "refund");
    ui->newmainbtn_set->setProperty("type", "set");
    _main_btn.insert(ui->newmainbtn_order);
    _main_btn.insert(ui->newmainbtn_refund);
    _main_btn.insert(ui->newmainbtn_set);
}

void NewMainForm::SetMainBtnCheck(MainBtn *wgt)
{
    foreach (auto var, _main_btn) {
        if(wgt == var)
            var->setChecked(true);
        else
            var->setChecked(false);

        //qDebug() << "&&&&&&&&&&&&" << var->property("type").toString();
    }
}

void NewMainForm::InitPrtSettingWidget()
{
    _prtsetting_widget.insert(ui->newmainwidget_dv);
    _prtsetting_widget.insert(ui->newmainwidget_com);
    _prtsetting_widget.insert(ui->newmainwidget_net);
    _prtsetting_widget.insert(ui->newmainwidget_lpt);
}

void NewMainForm::InitClassify()
{
    _classify_set.insert(ui->newmainbtn_needrefund);
    _classify_set.insert(ui->newmainbtn_refunded);
    _classify_set.insert(ui->newmainbtn_all);
    _classify_set.insert(ui->newmainbtn_new);
    _classify_set.insert(ui->newmainbtn_make);
    _classify_set.insert(ui->newmainbtn_makeover);
    _classify_set.insert(ui->newmainbtn_send);
    _classify_set.insert(ui->newmainbtn_over);
    _classify_set.insert(ui->newmainbtn_future);
}

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

bool NewMainForm::event(QEvent *e)
{
    if(e->type() == PosEvent::s_change_order)
    {
        QString orderid;

        GETEVENTINFO(orderid,e,QString);

        OrderObject order;

        if(!PosOrderPool::GetOrderObject(orderid, order))
            return true;

        Order_Index tmp = {order.status, order.refund_status};
        
        if(_order_indexs.contains(order.order_id))
        {
            _order_indexs.insert(order.order_id, tmp);
            UpdateTableWidget(order);
        }
        else
        {
            _order_indexs.insert(order.order_id, tmp);
            InsertTableWidget(order);
        }

        return true;
    }

    if(e->type() == PosEvent::s_login_storeinfo)
    {
        QVariantMap map;

        GETEVENTINFO(map, e, QVariantMap);

        _storeinfo = map;

        return true;
    }

    if(e->type() == PosEvent::s_show_mainform)
    {
        this->showFullScreen();
        return true;
    }

    if(e->type() == PosEvent::s_delete_order)
    {
        QVariantMap value;

        GETEVENTINFO(value,e,QVariantMap);

        if(value.contains(EVENT_KEY_ORDERID) && !value[EVENT_KEY_ORDERID].toString().isEmpty() &&
                _order_indexs.contains(value[EVENT_KEY_ORDERID].toString()))
        {
            DeleteTableWidget(value[EVENT_KEY_ORDERID].toString());
            _order_indexs.remove(value[EVENT_KEY_ORDERID].toString());
        }
        return true;
    }
    return QWidget::event(e);
}

void NewMainForm::SetChecked(QPushButton *btn)
{
    foreach (auto var, _classify_set) {
        if(btn == var)
        {
            _curr_check_btn = btn;
            var->setChecked(true);
            ClassifyOrder(_curr_check_btn->property("type").toString());

            //qDebug() << "------" << _curr_page_num;

            InitPageNum();
        }
        else
        {
            var->setChecked(false);
        }
    }
}

void NewMainForm::UpdateTableWidget(OrderObject &orderObject)
{
    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = (OrderTypeForm *)table->cellWidget(i, 1);

        if(orderObject.order_id.compare(pwd->order_id()) == 0)
        {
            pwd->InitShow(orderObject.order_id, orderObject.status, orderObject.refund_status, orderObject.order_type);
            break;
        }
    }

    ClassifyOrder(_curr_check_btn->property("type").toString());
}

void NewMainForm::DeleteTableWidget(QString orderid)
{
    QTableWidget *table = ui->newmaintablewidget_order;
    for(int i=0; i<table->rowCount(); i++)
    {
        OrderTypeForm *pwd = (OrderTypeForm *)table->cellWidget(i, 1);

        if(orderid.compare(pwd->order_id()) == 0)
        {
            table->removeRow(i);
            break;
        }
    }

    ClassifyOrder(_curr_check_btn->property("type").toString());
}

void NewMainForm::InitTableWidget()
{
    ui->newmaintablewidget_order->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->newmaintablewidget_order->horizontalHeader()->setFixedHeight(36);
    ui->newmaintablewidget_order->verticalHeader()->setVisible(false);
}

void NewMainForm::InsertTableWidget(OrderObject &orderObject)
{
    QTableWidget *table = ui->newmaintablewidget_order;
    table->insertRow(0);
    QTableWidgetItem *item = new QTableWidgetItem(QString::number(orderObject.order_index));

    table->setItem(0, 0, item);  //序号
    OrderTypeForm *pWdg = new OrderTypeForm(table);
    pWdg->InitShow(orderObject.order_id, orderObject.status, orderObject.refund_status, orderObject.order_type);
    //pWdg->InitShow(QString::number(orderObject.order_index), orderObject.status, orderObject.refund_status, orderObject.order_type);

    table->setCellWidget(0, 1, pWdg); //订单状态
    QTableWidgetItem *item0 = new QTableWidgetItem(QString::number(orderObject.order_index));
    item0->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 2, item0);  // 渠道
//    QTableWidgetItem *item1 = new QTableWidgetItem(orderObject.order_id);
//    item1->setTextAlignment(Qt::AlignCenter);
//    table->setItem(0, 3, item1);  // 订单ID
    QTableWidgetItem *item2 = new QTableWidgetItem(QString::number(orderObject.shop_fee/100.0));
    item2->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 3, item2);  // 金额
    QTableWidgetItem *item3 = new QTableWidgetItem(orderObject.customer);
    item3->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 4, item3);  // 姓名
    QTableWidgetItem *item4 = new QTableWidgetItem(orderObject.phone);
    item4->setTextAlignment(Qt::AlignCenter);
    table->setItem(0, 5, item4);  // 联系方式
//    QTableWidgetItem *item5 = new QTableWidgetItem(QDateTime::fromTime_t(orderObject.create_time).toString("MM-dd hh:mm"));
//    item5->setTextAlignment(Qt::AlignCenter);
//    table->setItem(0, 6, item5);  // 下单时间

    OrderOptForm *form = new OrderOptForm(table);
    table->setCellWidget(0, 6, form); //订单操作

    //qDebug() << _curr_check_btn->property("type").toString();

    ClassifyOrder(_curr_check_btn->property("type").toString());

    table->setRowHeight(0, 36);
}

void NewMainForm::GetOrderStatus(OrderObject &order, int &order_status)
{
    if(order.refund_status == ApplicationRefundOrder &&
            order.refund_status == ApplicationPartialRefundOrder &&
            order.refund_status == RefusingRefundOrder)
        order_status = order.refund_status;
    else
        order_status = order.status;
}

void NewMainForm::InitOrderWidget(QString type)
{
    if(type.compare(MAIN_ORDER, Qt::CaseInsensitive) == 0)
    {
        ui->newmainbtn_needrefund->hide();
        ui->newmainbtn_refunded->hide();
        ui->newmainbtn_all->show();
        ui->newmainbtn_new->show();
        ui->newmainbtn_make->show();
        ui->newmainbtn_makeover->show();
        ui->newmainbtn_over->show();
        ui->newmainbtn_future->show();
        ui->newmainbtn_send->show();
        SetMainBtnCheck(ui->newmainbtn_order);
        SetChecked(ui->newmainbtn_all);
        _curr_check_btn = ui->newmainbtn_all;
    }
    else if(type.compare(MAIN_REFUND, Qt::CaseInsensitive) == 0)
    {
        ui->newmainbtn_needrefund->show();
        ui->newmainbtn_refunded->show();
        ui->newmainbtn_all->hide();
        ui->newmainbtn_new->hide();
        ui->newmainbtn_make->hide();
        ui->newmainbtn_makeover->hide();
        ui->newmainbtn_over->hide();
        ui->newmainbtn_future->hide();
        ui->newmainbtn_send->hide();
        SetMainBtnCheck(ui->newmainbtn_refund);
        SetChecked(ui->newmainbtn_needrefund);
        _curr_check_btn = ui->newmainbtn_needrefund;
    }

}

void NewMainForm::InitSetWidget()
{
    SetChecked(ui->newmainbtn_needrefund);

    ui->newmaincombx_prttype->setCurrentIndex(0);

    SetMainBtnCheck(ui->newmainbtn_set);

    InitOrderSetting();

    LoadMainPrtSetting();
}

void NewMainForm::InitWidget(QString type)
{
    if(type.compare(MAIN_SET, Qt::CaseInsensitive) == 0)
    {
        InitSetWidget();
        ui->newmainwgt_order->hide();
        ui->newmainwgt_set->show();
    }
    else
    {
        InitOrderWidget(type);
        ui->newmainwgt_order->show();
        ui->newmainwgt_set->hide();
    }
}

void NewMainForm::on_newmainbtn_clicked()
{
    MainBtn *pBtn = (MainBtn*)sender();

    QString type = pBtn->property("type").toString();

    if(!type.isEmpty())
    {
        InitWidget(type);
    }
}

void NewMainForm::on_classifybtn_clicked()
{
    QPushButton *pBtn = (QPushButton*)sender();
    SetChecked(pBtn);
}

void NewMainForm::LoadMainPrtSetting()
{
    ui->newmainrdbtn_com->setCheckable(true);
    ui->newmainrdbtn_lpt->setCheckable(true);
    //qDebug() << _main_prt_configs;

    if(_main_prt_configs.isEmpty())
    {
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
    }
    else
    {
        SettingWidgetWithConf(0, _main_prt_configs);
    }
}

void NewMainForm::SettingWidgetWithConf(int index, QMap<QString, QString> &map)
{
    int type = 4;

    if(index != 1)
    {
        ui->newmaincombx_cmd->hide();
        ui->newmainlabel_cmd->hide();
        type = map["type"].toInt();
    }
    else
    {
        ui->newmaincombx_cmd->show();
        ui->newmainlabel_cmd->show();
        type = map["labelprttype"].toInt();
    }

    switch (type) {
    case 0:
        ui->newmaincombx_com->setCurrentText(map["com"]);
        ui->newmaincombx_bdl->setCurrentText(map["Baudrate"]);
        ui->newmaincombx_control->setCurrentText(map["FlowControl"]);
        ui->newmaincombx_data->setCurrentText(map["DataBits"]);
        ui->newmaincombx_jy->setCurrentText(map["Parity"]);
        ui->newmaincombx_stop->setCurrentText(map["StopBits"]);
        ui->newmaincombx_dvwidth->setCurrentText(map["PaperWidth"]);
        ui->newmainrdbtn_com->setChecked(true);
        InitSettingWidget(SET_PRT_COM);
        break;
    case 1:
        ui->newmainline_lpt->setText(map["parallel"]);
        ui->newmaincombx_lptwidth->setCurrentText(map["PaperWidth"]);
        ui->newmainrdbtn_lpt->setChecked(true);
        InitSettingWidget(SET_PRT_LPT);
        break;
    case 3:
        ui->newmainline_ip->setText(map["IP"]);
        ui->newmaincombx_netwidth->setCurrentText(map["PaperWidth"]);
        ui->newmainrdbtn_net->setChecked(true);
        InitSettingWidget(SET_PRT_NET);
        break;
    case 4:
        ui->newmainline_name->setText(map["Name"]);
        ui->newmaincombx_dvwidth->setCurrentText(map["PaperWidth"]);
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
        break;
    default:
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
        break;
    }
}

void NewMainForm::LoadLabelPrtSetting()
{
    ui->newmainrdbtn_com->setCheckable(false);
    ui->newmainrdbtn_lpt->setCheckable(false);
    if(_label_prt_configs.isEmpty())
    {
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
    }
    else
    {
        SettingWidgetWithConf(1, _main_prt_configs);
    }
}

void NewMainForm::LoadOtherPrtSetting(int index)
{
    ui->newmainrdbtn_com->setCheckable(true);
    ui->newmainrdbtn_lpt->setCheckable(true);

    if(index > _other_prt_configs.size())
    {
        ui->newmainrdbtn_dv->setChecked(true);
        InitSettingWidget(SET_PRT_DV);
        return ;
    }

    SettingWidgetWithConf(index + 1, _other_prt_configs[index - 1]);
    return ;

}

void NewMainForm::InitUserSetting()
{

}

void NewMainForm::InitPrtSetting()
{
    LoadMainPrtSetting();
    on_newmaincombx_prttype_currentIndexChanged(0);
}

void NewMainForm::InitOrderSetting()
{
    QString confpath = qApp->applicationDirPath() + "/" + CONFIG_NAME;
    int autoconf = QSettings(confpath, QSettings::IniFormat).value(INI_AUTOCONFIRM,1).toInt();
    int timeout = QSettings(confpath, QSettings::IniFormat).value(INI_DELEORDERTIMER,1).toInt();

    if(autoconf == 1)
        ui->newmainrdbtn_auto->setChecked(true);
    else
        ui->newmainrdbtn_self->setChecked(true);

    ui->newmaincombx_del->setCurrentIndex(timeout/12 - 1);
}

void NewMainForm::InitSettingWidget(QString type)
{
    foreach (auto var, _prtsetting_widget) {
        if(var->property("type").toString().compare(type, Qt::CaseInsensitive) == 0)
            var->show();
        else
            var->hide();
    }
}

void NewMainForm::on_PrtSet_toggled(bool checked)
{
    if(checked)
    {
        QRadioButton *pBtn = (QRadioButton*)sender();
        QString type = pBtn->property("type").toString();
        InitSettingWidget(type);
    }
}

void NewMainForm::on_newmaincombx_prttype_currentIndexChanged(int index)
{
    ui->newmainlabel_errmsg->hide();

    if(index == 0)
        LoadMainPrtSetting();
    else if(index == 1)  
        LoadLabelPrtSetting();
    else   
        LoadOtherPrtSetting(index - 1);

    if((ui->newmaincombx_prttype->count() == 2 && index == 0) ||
        (ui->newmaincombx_prttype->count() > 2 && index == ui->newmaincombx_prttype->count() - 1))
        ui->newmainbtn_prtadd->show();
    else
        ui->newmainbtn_prtadd->hide();

    if(ui->newmaincombx_prttype->count() > 2 && index == ui->newmaincombx_prttype->count() - 1)
       ui->newmainbtn_prtdel->show();
    else
        ui->newmainbtn_prtdel->hide();

    ui->newmainlabel_settitle->setText(ui->newmaincombx_prttype->currentText());
}

void NewMainForm::on_newmaintbwgt_tabBarClicked(int index)
{
    ui->newmainlabel_errmsg->hide();

    if(index == 0)
    {
        InitOrderSetting();
    }
    else if(index == 1)
    {
        InitPrtSetting();
    }
}

bool NewMainForm::GetMapAndSaveSet(int index, QMap<QString, QString> &map)
{
    int type = -1;

    if(ui->newmainrdbtn_dv->isChecked())
        type = 4;
    if(ui->newmainrdbtn_net->isChecked())
        type = 3;
    if(ui->newmainrdbtn_lpt->isChecked())
        type = 1;
    if(ui->newmainrdbtn_com->isChecked())
        type = 0;

    if(type == -1)
    {
        ShowSetErrorMsg(QString::fromUtf8("\xE8\xAF\xB7\xE9\x80\x89\xE6\x8B\xA9\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA\xE7\xB1\xBB\xE5\x9E\x8B"));
        return false;
    }

    map["type"] = QString::number(type);

    switch (type) {
    case 0:
        map.insert("com", ui->newmaincombx_com->currentText());
        map.insert("Baudrate", ui->newmaincombx_bdl->currentText());
        map.insert("FlowControl", ui->newmaincombx_control->currentText());
        map.insert("DataBits", ui->newmaincombx_data->currentText());
        map.insert("Parity", ui->newmaincombx_jy->currentText());
        map.insert("StopBits", ui->newmaincombx_stop->currentText());
        map.insert("PaperWidth", ui->newmaincombx_dvwidth->currentText());
        break;
    case 1:
        map.insert("parallel",ui->newmainline_lpt->text());
        map.insert("PaperWidth",ui->newmaincombx_lptwidth->currentText());
        break;
    case 3:
        ui->newmainline_ip->setText(map["IP"]);
        ui->newmaincombx_netwidth->setCurrentText(map["PaperWidth"]);
        break;
    case 4:
        map.insert("Name",ui->newmainline_name->text());
        map.insert("PaperWidth",ui->newmaincombx_dvwidth->currentText());
        break;
    default:
        return false;
    }

    NewMainFormDataProcess::SetPrintIniWithInde(index, map);

    return true;
}

void NewMainForm::ShowSetErrorMsg(QString str)
{
    ui->newmainlabel_errmsg->setText(str);
    ui->newmainlabel_errmsg->show();
}


void NewMainForm::on_newmainbtn_prtsave_clicked()
{
    ui->newmainlabel_errmsg->hide();

    int index = ui->newmaincombx_prttype->currentIndex();

    if(index == 0)
    {
        GetMapAndSaveSet(index, _main_prt_configs);
    }
    else if(index == 1)
    {
        GetMapAndSaveSet(index, _label_prt_configs);
    }
    else
    {
        QMap<QString, QString> map;
        if(GetMapAndSaveSet(index, map))
        {
            if(_other_prt_configs.size() > index - 2)
                _other_prt_configs[index - 2] = map;
            else
            {
                ++_other_prt_num;
                NewMainFormDataProcess::SetOtherPrintNum(_other_prt_num);
                _other_prt_configs.push_back(map);
            }
        }
    }
}

void NewMainForm::on_newmainbtn_prtadd_clicked()
{
    ui->newmainlabel_errmsg->hide();

    int index = _other_prt_configs.size() + 1;

    if(ui->newmaincombx_prttype->currentIndex() == index || ui->newmaincombx_prttype->count() == 2)
    {
        ui->newmaincombx_prttype->addItem(QString::fromUtf8("\xE5\x90\x8E\xE5\x8E\xA8\xE6\x89\x93\xE5\x8D\xB0\xE6\x9C\xBA") + QString::number(index));
        ui->newmaincombx_prttype->setCurrentIndex(index + 1);
    }
    else
    {
        ShowSetErrorMsg(QString::fromUtf8("\xE8\xAF\xB7\xE5\x85\x88\xE4\xBF\x9D\xE5\xAD\x98\xE5\xBD\x93\xE5\x89\x8D\xE6\x89\x93\xE5\x8D\xB0\xE9\x85\x8D\xE7\xBD\xAE\xE5\x86\x8D\xE6\xB7\xBB\xE5\x8A\xA0\xE6\x96\xB0\xE6\x9C\xBA\xE5\x99\xA8"));
    }
}

void NewMainForm::on_newmainbtn_prtdel_clicked()
{
    ui->newmainlabel_errmsg->hide();

    if(ui->newmaincombx_prttype->count() > 2)
    {
        if(ui->newmaincombx_prttype->count() - 2 == _other_prt_configs.size())
        {
            -- _other_prt_num;
            NewMainFormDataProcess::SetOtherPrintNum(_other_prt_num);
            _other_prt_configs.pop_back();
        }
        ui->newmaincombx_prttype->removeItem(ui->newmaincombx_prttype->count() - 1);
        ui->newmaincombx_prttype->setCurrentIndex(ui->newmaincombx_prttype->count() - 1);
    }
}

void NewMainForm::on_newmaincombx_name_currentIndexChanged(int index)
{
    ui->newmainline_name->setText(ui->newmaincombx_name->currentText());
}

void NewMainForm::on_newmainvtn_ordersave_clicked()
{
    int autoconf = 0;

    if(ui->newmainrdbtn_auto->isChecked())
        autoconf = 1;

    NewMainFormDataProcess::SetOrderConfig(QString::number(autoconf), QString::number((ui->newmaincombx_del->currentIndex() + 1)*12));
}

void NewMainForm::on_newmainbtn_down_clicked()
{
    int num = ui->newmaintablewidget_order->height()/36;

    int page =  _curr_page_num/(num - 1) ;

    if(_curr_page_num%(num - 1) != 0)
        ++ page;

    if(_curr_page < page)
    {  
        if(_curr_page == page - 1 && _curr_page_num%(num - 1) != 0)
        {
            ui->newmaintablewidget_order->viewport()->setFixedHeight(_curr_page_num%(num - 1) * 36);
        }
        ui->newmaintablewidget_order->verticalScrollBar()->setValue(_curr_page*(num - 1));
        ++ _curr_page;
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(page));
    }
}

void NewMainForm::on_newmainbtn_up_clicked()
{
    int num = ui->newmaintablewidget_order->height()/36;

    int page =  _curr_page_num/(num - 1) ;

    if(_curr_page_num%(num - 1) != 0)
        ++ page;

    if(_curr_page > 1)
    {
        -- _curr_page;
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(page));
        ui->newmaintablewidget_order->verticalScrollBar()->setValue((_curr_page - 1)*(num - 1));
        ui->newmaintablewidget_order->viewport()->setFixedHeight((num - 1) * 36);
    }
}

void NewMainForm::on_newmainbtn_close_clicked()
{
    FMApplication::exit(0);
}

void NewMainForm::on_newmainbtn_jump_clicked()
{
    int num = ui->newmaintablewidget_order->height()/36;
    int page = ui->newmainline_page->text().toInt();

    int tmppage =  _curr_page_num/(num - 1) ;

    if(_curr_page_num%(num - 1) != 0)
        ++ tmppage;

    if(page > 0 && page <= tmppage && page != _curr_page)
    {
        if(page == tmppage && _curr_page_num%(num - 1) != 0)
        {
            ui->newmaintablewidget_order->viewport()->setFixedHeight(_curr_page_num%(num - 1) * 36);
        }
        else
        {
            ui->newmaintablewidget_order->viewport()->setFixedHeight((num - 1) * 36);
        }
        _curr_page = page;
        ui->newmaintablewidget_order->verticalScrollBar()->setValue((_curr_page-1)*(num - 1));
        ui->newmainlabel_page->setText(QString::number(_curr_page)+ "/" + QString::number(tmppage));
    }
}
