#include "hostwidget.h"
#include "ui_hostwidget.h"
#include "QKeyEvent"
#include "QsLog.h"
#include "fmtool.h"
#include "labelstimer.h"

#include <QMovie>
#include <QDateTime>
#include <QJsonArray>

HostWidget::HostWidget(QWidget *parent) :
    FMPWindow(parent),
    ui(new Ui::HostWidget)
{
    ui->setupUi(this);

    _need_exit = false;

    _runing = false;

    _widgetlist.append(ui->pay);
    _widgetlist.append(ui->find);
    _widgetlist.append(ui->Manager);
    _widgetlist.append(ui->sign);

    _curr_show_widget = NULL;

    //ui->btn_mananger_print->setEnabled(false);
    //ui->btn_mananger_check->setEnabled(false);

    InitWidget();

    connect(&_intertime, &QTimer::timeout, this, [this](){
        if(!_need_exit)
        {
            ui->label_pay_title->setText(QString::fromLocal8Bit("支付中/等待用户输入密码"));
            ui->btn_pay_exitint->show();
        }
    });

    _label_pay_timer = new LabelsTimer(ui->label_pay_time, 60, QString::fromLocal8Bit("%1 秒"));

    _label_find_timer = new LabelsTimer(ui->label_check_timer, 60, QString::fromLocal8Bit("%1 秒"));



    connect(_label_pay_timer, &LabelsTimer::timeout, this, &HostWidget::on_TimeOut);
    connect(_label_find_timer, &LabelsTimer::timeout, this, &HostWidget::on_TimeOut);


    _label_pay_movie = new QMovie(":res/loading.gif");
    _label_pay_movie->start();
    ui->label_pay_time_load->setMovie(_label_pay_movie);
    ui->label_logo->setMovie(_label_pay_movie);

    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    //ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(45);
}

void HostWidget::ShowWidget(QWidget *showwidget)
{

    if(showwidget == ui->pay)
    {
        ui->lineEdit_pay_code->clear();
        ui->btn_pay_exitint->hide();
        ui->lineEdit_pay_code->setWindowOpacity(0);
        ui->lineEdit_pay_code->setFocus();
        ui->label_pay_msg_time->setVisible(false);

        _label_pay_timer->start(60, QString::fromLocal8Bit("%1 秒"));
    }

    for(int i = 0; i < _widgetlist.size(); ++i)
    {
        if(showwidget == _widgetlist.at(i))
        {
            if(showwidget->isHidden())
                showwidget->show();
            continue;
        }
        _widgetlist.at(i)->hide();
    }


    //this->show();
    //this->move(1200, 500);
    this->showFullScreen();
}

void HostWidget::InitWidget()
{
    for(int i = 0; i < _widgetlist.size(); ++i)
    {
        _widgetlist.at(i)->hide();
    }
}

void HostWidget::setRuning(bool runing)
{
    _runing = runing;
}

HostWidget::~HostWidget()
{
    delete ui;
    if(_label_pay_timer != NULL) {
        delete _label_pay_timer;
        _label_pay_timer = NULL;
    }
}

void HostWidget::keyPressEvent(QKeyEvent *ke)
{

    if (ke->key() == Qt::Key_Return && _curr_show_widget == ui->pay)
    {
        if(!_need_exit && _runing == false)
        {
            _runing = true;
            ui->btn_pay_exit->hide();
            ui->label_pay_money->hide();

            _label_pay_timer->start(60, QString::fromLocal8Bit("%1 秒"));

            QStringList list;
            list.append(ui->lineEdit_pay_code->text());
            QLOG_INFO() << list;

            if(_type == pay)
            {
                ui->label_pay_title->setText(QString::fromLocal8Bit("支付宝支付中..."));
                _intertime.start(2*1000);
                emit RequestWithType(pay, list);
            }
            else
            {
//                ui->label_pay_title->setText(QString::fromLocal8Bit("支付宝退款中..."));
//                emit RequestWithType(refund, list);
            }

        }/*else
            emit Exits();*/
    }
    else
    {
        FMPWindow::keyPressEvent(ke);
    }
}

void HostWidget::ShowWithRequest(AlipayRequest request)
{ 
    QString reqtype;
    _data = request;

    reqtype.append(request.TransType[0]).append(request.TransType[1]);

    if(reqtype.compare("10") == 0)
    {
        ShowWidget(ui->Manager);
        _curr_show_widget = ui->Manager;
        QString storeId = FMTool::GetString(_data.StoreNo, 20);
        ui->label_find_title->setText(QString::fromLocal8Bit("门店%1交易流水查询").arg(storeId));
    }

    if(reqtype.compare("30") == 0)
    {
        _type = pay;
        ShowWidget(ui->pay);
        _curr_show_widget = ui->pay;
        double Amount = FMTool::GetString(_data.Amount, 12).toInt()/100.0;
        ui->label_pay_title->setText(QString::fromLocal8Bit("请扫描支付宝二维码"));
        ui->btn_pay_exit->setText(QString::fromLocal8Bit("取消支付"));
        ui->label_pay_money->setText(QString::fromLocal8Bit("需收取 ￥ %1").arg(Amount));
    }

    if(reqtype.compare("40") == 0)
    {
        _type = refund;
        ShowWidget(ui->pay);
        _curr_show_widget = ui->pay;
//        double Amount = FMTool::GetString(_data.Amount, 12).toInt()/100.0;
//        ui->label_pay_title->setText(QString::fromLocal8Bit("请扫描退款凭证号"));
//        ui->btn_pay_exit->setText(QString::fromLocal8Bit("取消退款"));
//        ui->label_pay_money->setText(QString::fromLocal8Bit("退款 ￥ %1").arg(Amount));
        ui->btn_pay_exit->hide();
        ui->label_pay_money->hide();

        //_refundamout = FMTool::GetString(_data.Amount, 12).toInt();

        _label_pay_timer->start(60, QString::fromLocal8Bit("%1 秒"));

        QStringList list;

        list.append(FMTool::GetString(request.OriginTrace, 64));

        ui->label_pay_title->setText(QString::fromLocal8Bit("支付宝退款中..."));
        emit RequestWithType(refund, list);
    }

    if(reqtype.compare("80") == 0)
    {
        _type = finds;
        ui->label_find_msg->clear();
        ui->dateEdit_find_begin->setDate(QDate::currentDate());
        ui->dateEdit_find_end->setDate(QDate::currentDate());
        ui->tableWidget->hide();
        ui->frame->hide();
        ui->widget_check_load->hide();
        ShowWidget(ui->find);
        _curr_show_widget = ui->find;
        ui->label_find_page->setText("1");
        QString storeId = FMTool::GetString(_data.StoreNo, 20);
        ui->label_find_title->setText(QString::fromLocal8Bit("门店%1交易流水查询").arg(storeId));
    }
}

void HostWidget::ShowWiteJson(bool flag, QJsonObject object, QString error)
{
    ui->widget_check_load->hide();
    ui->btn_find_check->show();
    _label_find_timer->stop();


    QLOG_INFO() << object;

    if(!flag)
    {
        ui->label_find_msg->setText(QString::fromLocal8Bit("查询失败(%1)").arg(error));
    }
    else
    {


        if((object.contains(JSON_KEY_TOTALNUM) && object[JSON_KEY_TOTALNUM].toInt() == 0) || !object.contains(JSON_KEY_QUERYINFO))
        {
            ui->label_find_msg->setText(QString::fromLocal8Bit("无交易记录"));
        }
        else
        {
            ui->frame->show();
            ui->label_find_msg->setText(QString::fromLocal8Bit("%1到%2的账单流水").arg(ui->dateEdit_find_begin->text(), ui->dateEdit_find_end->text()));

            if(ui->label_find_page->text().compare("1") == 0)
            {
                _line = object[JSON_KEY_TOTALNUM].toInt()/10;

                if(object[JSON_KEY_TOTALNUM].toInt()%10 != 0)
                    _line += 1;
            }

            QJsonArray array = object[JSON_KEY_QUERYINFO].toArray();

            foreach(auto val , array)
            {
                QJsonObject tmp = val.toObject();
                ui->tableWidget->insertRow(0);
                QTableWidgetItem *item0 = new QTableWidgetItem(tmp[JSON_KEY_FMID].toString());
                item0->setTextAlignment(Qt::AlignCenter);
                ui->tableWidget->setItem(0, 0, item0);

                QTableWidgetItem *item1 = new QTableWidgetItem(QString::number(tmp[JSON_KEY_TRANSAMOUNT].toInt()/100.0));
                item1->setTextAlignment(Qt::AlignCenter);
                ui->tableWidget->setItem(0, 1, item1);


                QTableWidgetItem *item2 = new QTableWidgetItem(tmp[JSON_KEY_TRANSTIME].toString());
                item2->setTextAlignment(Qt::AlignCenter);
                ui->tableWidget->setItem(0, 2, item2);


                QTableWidgetItem *item3 = new QTableWidgetItem(tmp[JSON_KEY_STATEMSG].toString());
                item3->setTextAlignment(Qt::AlignCenter);
                ui->tableWidget->setItem(0, 3, item3);



                QWidget *pWdg = new QWidget(ui->tableWidget);
                QHBoxLayout *hLayout = new QHBoxLayout(pWdg);
                QPushButton * pBtn = new QPushButton(pWdg);
                pBtn->setFixedSize(70, 30);
                pBtn->setFocusPolicy(Qt::NoFocus);
                pBtn->setProperty("orderId", tmp[JSON_KEY_FMID].toString());

                pBtn->setText(QString::fromLocal8Bit("打印"));
                hLayout->addWidget(pBtn);
                hLayout->setMargin(0);
                pWdg->setLayout(hLayout);
                ui->tableWidget->setCellWidget(0, 4, pWdg);   // 操作按钮
                pBtn->setStyleSheet("border:0px;border-radius:2px;background-color: rgb(0, 179, 238);font: 75 20px \"Microsoft YaHei UI Light\";");

                qDebug() << "********************-----------*******************" << tmp;

                if(tmp[JSON_KEYT_STATE].toString().toInt() != 1)
                {
                    pBtn->setEnabled(false);
                    pBtn->setStyleSheet("border:0px;border-radius:2px;background-color: rgb(208, 208, 208);font: 75 20px \"Microsoft YaHei UI Light\";");
                }

                connect(pBtn, &QPushButton::clicked, this, [this, pBtn]()
                {
                    QStringList list;
                    list.append(pBtn->property("orderId").toString());
                    on_btn_printagain_clicked();
                    emit RequestWithType(againprint, list);
                });

            }
            ui->tableWidget->sortByColumn(2, Qt::DescendingOrder);
            ui->tableWidget->show();
        }
    }
}

void HostWidget::ShowWiteMGS(ReqType type, bool flag, QString message)
{
    if(type == sign)
    {
        _need_exit = true;
        if(flag)
            ui->label_sign_title->setText(QString::fromLocal8Bit("获取签名成功"));
        else
            ui->label_sign_title->setText(QString::fromLocal8Bit("获取签名失败"));

        ui->label_sign_msg->setText(message);

        ui->btn_sign_sign->show();
        ShowWidget(ui->sign);
        return ;
    }
    if(type == pay && _curr_show_widget == ui->pay)
    {
        _need_exit = true;
        _label_pay_timer->stop();
        ui->btn_pay_exitint->hide();
        ui->label_pay_time_load->setVisible(false);
        ui->label_pay_money->setVisible(true);
        ui->label_pay_money->setText(message);
        ui->btn_pay_exit->setVisible(true);
        ui->btn_pay_exit->setText(QString::fromLocal8Bit("确认"));

        if(flag) {
            ui->label_pay_msg_time->setVisible(true);
            _label_pay_timer->setLabel(ui->label_pay_msg_time);
            _label_pay_timer->start(3);
            ui->label_pay_title->setText(QString::fromLocal8Bit("支付成功"));
            ui->label_pay_time->setPixmap(QPixmap(":res/success.png"));
        } else {
//            ui->label_pay_title->setText(QString::fromLocal8Bit("支付失败"));
//            ui->label_pay_time->setPixmap(QPixmap(":res/warning.png"));
            emit Exits();
        }
        return ;
    }

    if(type == refund && _curr_show_widget == ui->pay)
    {
        _need_exit = true;
        _label_pay_timer->stop();
        ui->label_pay_time_load->setVisible(false);
        ui->label_pay_money->setVisible(true);
        ui->label_pay_money->setText(message);
        ui->btn_pay_exit->setVisible(true);
        ui->btn_pay_exit->setText(QString::fromLocal8Bit("确认"));

        qDebug() << "-----" << flag;

        if(flag) {
            ui->label_pay_msg_time->setVisible(true);
            _label_pay_timer->setLabel(ui->label_pay_msg_time);
            _label_pay_timer->start(3);
            ui->label_pay_title->setText(QString::fromLocal8Bit("退款成功"));
            ui->label_pay_time->setPixmap(QPixmap(":res/success.png"));
        } else {
//            ui->label_pay_title->setText(QString::fromLocal8Bit("退款失败"));
//            ui->label_pay_time->setPixmap(QPixmap(":res/warning.png"));
            emit Exits();
        }
        return ;
    }

    if(type == endday)
    {
        _need_exit = true;
        _label_pay_timer->stop();
        ui->label_pay_time_load->setVisible(false);
        ui->label_pay_money->setVisible(true);
        ui->label_pay_money->setText(message);
        ui->label_pay_title->show();
        ui->label_pay_msg_time->show();
        ui->btn_pay_exit->setVisible(true);
        ui->btn_pay_exit->setText(QString::fromLocal8Bit("确认"));

        if(flag) {
            ui->label_pay_msg_time->setVisible(true);
            _label_pay_timer->setLabel(ui->label_pay_msg_time);
            _label_pay_timer->start(3);
            ui->label_pay_title->setText(QString::fromLocal8Bit("打印日结单成功"));
            ui->label_pay_time->setPixmap(QPixmap(":res/success.png"));
        } else {
            ui->label_pay_msg_time->hide();
            ui->label_pay_title->setText(QString::fromLocal8Bit("打印日结单失败"));
            ui->label_pay_time->setPixmap(QPixmap(":res/warning.png"));
        }
        return ;
    }

    if(type == againprint)
    {
        _need_exit = true;
        _label_pay_timer->stop();
        ui->label_pay_time_load->setVisible(false);
        ui->label_pay_money->setVisible(true);
        ui->label_pay_money->setText(message);
        ui->label_pay_title->show();
        ui->label_pay_msg_time->show();
        ui->btn_pay_exit->setVisible(true);
        ui->btn_pay_exit->setText(QString::fromLocal8Bit("确认"));

        if(flag) {
            ui->label_pay_msg_time->setVisible(true);
            _label_pay_timer->setLabel(ui->label_pay_msg_time);
            _label_pay_timer->start(3);
            ui->label_pay_title->setText(QString::fromLocal8Bit("重印小票成功"));
            ui->label_pay_time->setPixmap(QPixmap(":res/success.png"));
        } else {
            ui->label_pay_msg_time->hide();
            ui->label_pay_title->setText(QString::fromLocal8Bit("重印小票失败"));
            ui->label_pay_time->setPixmap(QPixmap(":res/warning.png"));
        }
        return ;
    }
}

void HostWidget::on_btn_printagain_clicked()
{
    _type = againprint;

    ui->label_pay_title->hide();
    ui->label_pay_money->hide();
    //ui->label_pay_msg_time->hide();
    ui->btn_pay_exit->hide();
    ShowWidget(ui->pay);
    _curr_show_widget = ui->pay;
}

void HostWidget::on_btn_mananger_register_clicked()
{
    QStringList list;

    ShowWidget(ui->sign);
    ui->btn_sign_sign->hide();
    ui->label_sign_title->setText(QString::fromLocal8Bit("签到中..."));
    ui->label_sign_msg->setText("");
    ui->label_sign_storeid->setText(FMTool::GetString(_data.StoreNo, 20));
    emit RequestWithType(sign, list);
}

void HostWidget::on_btn_mananger_check_clicked()
{
    _type = finds;
    ui->label_find_msg->clear();
    ui->dateEdit_find_begin->setDisplayFormat("yyyy-MM-dd");
    ui->dateEdit_find_end->setDisplayFormat("yyyy-MM-dd");
    ui->dateEdit_find_begin->setDate(QDate::currentDate());
    ui->dateEdit_find_end->setDate(QDate::currentDate());
    ui->tableWidget->hide();
    ui->frame->hide();
    ui->widget_check_load->hide();
    ShowWidget(ui->find);
    _curr_show_widget = ui->find;
    ui->label_find_page->setText("1");

}

void HostWidget::on_btn_mananger_print_clicked()
{
    QStringList list;

    _type = endday;

    ui->label_pay_title->hide();
    ui->label_pay_money->hide();
    //ui->label_pay_msg_time->hide();
    ui->btn_pay_exit->hide();
    ShowWidget(ui->pay);
    _curr_show_widget = ui->pay;

    emit RequestWithType(endday, list);
}

void HostWidget::on_TimeOut()
{
    this->hide();
    if(_need_exit)
        emit Exits();
    else
        emit ExitWithMSG("01", QString::fromLocal8Bit("操作超时"));
}

void HostWidget::on_btn_mananger_exit_clicked()
{
    this->hide();
    emit ExitWithMSG("02", QString::fromLocal8Bit("收银员取消"));
}

void HostWidget::on_btn_pay_exit_clicked()
{
    this->hide();
    if(_need_exit)
        emit Exits();
    else
        emit ExitWithMSG("02", QString::fromLocal8Bit("收银员取消"));
}

void HostWidget::on_btn_find_exit_clicked()
{
    this->hide();
    emit ExitWithMSG("02", QString::fromLocal8Bit("收银员取消"));
}

void HostWidget::on_btn_sign_exit_clicked()
{
    this->hide();
    if(_need_exit)
        emit Exits();
    else
        emit ExitWithMSG("02", QString::fromLocal8Bit("收银员取消"));
}

void HostWidget::on_btn_sign_sign_clicked()
{
    QStringList list;

    ui->btn_sign_sign->hide();
    emit RequestWithType(sign, list);
}

void HostWidget::on_btn_find_check_clicked()
{

    QStringList list;

    ui->tableWidget->clear();

    QStringList headerString;
    headerString<<QString::fromLocal8Bit("订单编号")<<QString::fromLocal8Bit("订单金额")<<QString::fromLocal8Bit("订单时间")<<QString::fromLocal8Bit("支付状态")<<QString::fromLocal8Bit("操作");

    int width  = ui->widget_find_main->width() - 4;

    qDebug() << "===========" << width;

    //ui->tableWidget->setColumnWidth(0,1/10.0*width);
    ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{border: 0px;font: 75 18px \"Microsoft YaHei UI Light\";}");
    ui->tableWidget->horizontalHeader()->setFixedHeight(25); //设置表头的高度
    ui->tableWidget->setHorizontalHeaderLabels(headerString);

    ui->tableWidget->setColumnWidth(0,5/14.0*width);
    ui->tableWidget->setColumnWidth(1,2/14.0*width);
    ui->tableWidget->setColumnWidth(2,3/14.0*width);
    ui->tableWidget->setColumnWidth(3,2/14.0*width);

    ui->frame->hide();
    ui->widget_check_load->show();
    ui->btn_find_check->hide();
    list.append(ui->dateEdit_find_begin->text().replace("/","-"));
    list.append(ui->dateEdit_find_end->text().replace("/","-"));
    list.append(ui->label_find_page->text());
    _label_find_timer->start();
    emit RequestWithType(finds, list);
}

void HostWidget::on_btn_find_next_clicked()
{
    if(ui->label_find_page->text().toInt() == _line)
        return ;

    int page = ui->label_find_page->text().toInt() + 1;
    ui->label_find_page->setText(QString::number(page));

    on_btn_find_check_clicked();
}

void HostWidget::on_btn_find_up_clicked()
{
    if(ui->label_find_page->text().compare("1") != 0)
    {
        int page = ui->label_find_page->text().toInt() - 1;
        ui->label_find_page->setText(QString::number(page));
    }
    on_btn_find_check_clicked();
}

void HostWidget::HideExit()
{
    ui->btn_pay_exitint->hide();
}

void HostWidget::on_btn_pay_exitint_clicked()
{
    if(_intertime.isActive())
        _intertime.stop();

    ui->btn_pay_exitint->hide();
    ui->btn_pay_exit->hide();
    _label_pay_timer->start(60);
    ui->label_pay_title->setText(QString::fromLocal8Bit("支付取消中"));
    emit Interrupt();
}
