#include "floatForm.h"
#include "ui_floatForm.h"
#include "windows.h"
#include <QPixmap>
#include <QLabel>
#include "DTools/configManger.h"
#include "preDefine.h"
#include "QsLog.h"
#include <QProcess>
#include <QThread>

extern QThread  workThread;

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

    m_bReminding = false;
    m_bStoreStatus = true; //程序启动后,初始化为开店状态;
    m_bExistNoAckNotice = false; //程序启动后,初始化为不存在[NoAckNotice];
    QPixmap imgStoreBusiStat(":StoreBusinessStatus.png");
    m_imgStoreBusiStatSize = imgStoreBusiStat.size();

    QPixmap imgRemind(":float_remind.png");
    m_imgRemindSize = imgRemind.size();

    m_animation.setTargetObject(this);
    m_animation.setPropertyName("windowOpacity");
    m_animation.setDuration(ConfigManger::GetInstance().GetBlinkInterval());
    m_animation.setEasingCurve(QEasingCurve::InOutSine);
    m_raiseTimer.setInterval(2000);
    connect(&m_raiseTimer, &QTimer::timeout, this, &FloatForm::raise);
    _Init();
}

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

void FloatForm::mouseMoveEvent(QMouseEvent *event)
{
    if ((event->buttons()==Qt::LeftButton) && m_bMousePress)
    {
        QPoint moveAmount = event->globalPos() - m_lastMousePos;
        m_absMove += moveAmount;
        move(pos() + moveAmount);
        m_lastMousePos = event->globalPos();
        m_bMouseMove = true;
    }
}

void FloatForm::mousePressEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton) {
        m_bMousePress = true;
        m_lastMousePos = event->globalPos();
        m_absMove = QPoint(0,0);
    }

}

void FloatForm::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button()==Qt::LeftButton)
    {
        m_bMousePress = false;
    }
    int x = m_absMove.x();
    int y = m_absMove.y();
    if(!m_bMouseMove || (((x>-10)&&(x<10))&&((y>-10)&&(y<10))))
    {
        hide();
        m_raiseTimer.stop();
        emit showMainForm();
        onStopRemind();
    }

    m_bMouseMove = false;
    QPoint point = this->pos();
    QLOG_INFO()<<QString::fromLocal8Bit("float current Form position(x:%1,y:%2)").arg(point.x()).arg(point.y());
    int nWidth = GetSystemMetrics(SM_CXSCREEN) - 200;
    int nHeight = GetSystemMetrics(SM_CYSCREEN) - 220;
    QLOG_INFO()<<QString::fromLocal8Bit("floatForm active_Range(x:%1,y:%2)").arg(nWidth).arg(nHeight);
    if( (point.x()<nWidth && -80<point.x()) && (point.y()<nHeight && -50<point.y()) ){
        ConfigManger::GetInstance().setFloatInitPostion(this->pos());
    }else{
        point.setX(nWidth);
        point.setY(nHeight);
        this->move(QPoint(nWidth, nHeight));
        ConfigManger::GetInstance().setFloatInitPostion(point);
    }
}

void FloatForm::_Init()
{
    setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);

    //根据门店的开店/关店 状态来显示不同的图片;
    setFixedSize(m_imgStoreBusiStatSize);
    setStyleSheet("#floatWdg{ border-image: url(:StoreBusinessStatus.png); }");
    //初始化悬浮框 多渠道门店营业状态;
    RefreshStoreStatus();

    QPoint point = ConfigManger::GetInstance().GetFloatInitPostion();
    QLOG_INFO()<<QString::fromLocal8Bit("Float From Init Postion(x:%1,y:%2)").arg(point.x()).arg(point.y());
    int nWidth = GetSystemMetrics(SM_CXSCREEN) - 200;
    int nHeight = GetSystemMetrics(SM_CYSCREEN) - 220;
    if( (point.x()<nWidth && -80<point.x()) && (point.y()<nHeight && -50<point.y()) ){
        ConfigManger::GetInstance().setFloatInitPostion(point);
        this->move(point);
    }else{
        point.setX(nWidth);
        point.setY(nHeight);
        this->move(QPoint(nWidth, nHeight));
        ConfigManger::GetInstance().setFloatInitPostion(point);
    }
}

void FloatForm::_Blink()
{
    QEventLoop loop;
    connect(&m_animation, &QPropertyAnimation::finished, &loop, &QEventLoop::quit);
    m_animation.setStartValue(1);
    m_animation.setEndValue(0);
    m_animation.start();
    loop.exec();
    m_animation.setStartValue(0);
    m_animation.setEndValue(1);
    m_animation.start();
    loop.exec();
    m_animation.setStartValue(1);
    m_animation.setEndValue(0);
    m_animation.start();
    loop.exec();

    m_animation.setStartValue(0);
    m_animation.setEndValue(1);
    m_animation.start();
    loop.exec();

    if(m_bReminding) {
        QTimer::singleShot(ConfigManger::GetInstance().GetBlinkInterval(), this, &FloatForm::_Blink);
    }
}

void FloatForm::_PlayWav()
{
    if(m_bReminding) {
        QLOG_INFO()<<QString("[<<<----FloatForm::_PlayWav m_bReminding: --->>>>]")<< m_bReminding;
    }
}

void FloatForm::onStartRemind(int type)
{
    //每次播报音频，将会导致POS插件崩溃;顾在此处停止音频的播放;
    switch(type) {
    case REMIND_CONFIRMED_ORDER:
        //m_remindWav = QString("%1/wav/msg.wav").arg(QApplication::applicationDirPath());
        // 加上音频的时长
        m_wavPlayInterval = ConfigManger::GetInstance().GetSoundInterval() + VALUE_NEWORDERTIME;
        break;
    case REMIND_REQREFUND_ORDER:
        //m_remindWav = QString("%1/wav/msg1.wav").arg(QApplication::applicationDirPath());
        m_wavPlayInterval = ConfigManger::GetInstance().GetSoundInterval() + VALUE_REFUNDORDERTIME;
        break;
    }

    if(!m_bReminding) {
       m_bReminding = true;
       RefreshOrderManagerStatus(1);
    }
    //10s后触发将闪烁提醒标志(m_bReminding)重置为False事件;
    QTimer::singleShot(1000*10, this, &FloatForm::onStopRemind);
    //根据闪烁提醒标志(m_bReminding):只有是True，则一直循环闪烁，直到标志为False；
    _Blink();
    _PlayWav();
}

void FloatForm::onStopRemind()
{
    m_bReminding = false;
    RefreshOrderManagerStatus(0);
}

void FloatForm::onShow()
{
    show();
    m_raiseTimer.start();
}

void FloatForm::onHide()
{
    hide();
    m_raiseTimer.start();
}

void FloatForm::onLockFloatForm(){
    QLOG_INFO()<<QString("[<<<----FloatForm::onLockFloatForm : Lock Float Form --->>>>]");
    if( this->isEnabled() ){
        this->setEnabled(false);
    }
}


void FloatForm::onUnLockFloatForm(){
    QLOG_INFO()<<QString("[<<<----FloatForm::onUnLockFloatForm : unLock Float Form --->>>>]");
    if( !this->isEnabled() ){
        this->setEnabled(true);
    }
}


void FloatForm::onUpdateStoreStatus(int eleStoreStatus, int modStoreStatus, int mopStoreStatus, int mtStoreStatus, int existNoAckNotice){
    QLOG_INFO()<<QString("[<<<----FloatForm::onUpdateStoreStatus: eleStoreStatus: %1, modStoreStatus: %2, mopStoreStatus: %3, mtStoreStatus: %4, existNoAckNotice:%5 --->>>>]")
              .arg(eleStoreStatus).arg(modStoreStatus).arg(mopStoreStatus).arg(mtStoreStatus).arg(existNoAckNotice);
    m_bExistNoAckNotice = existNoAckNotice;
    RefreshStoreStatus( eleStoreStatus, modStoreStatus, mopStoreStatus, mtStoreStatus );
}


void FloatForm::RefreshStoreStatus(int eleStoreStatus, int modStoreStatus, int mopStoreStatus, int mtStoreStatus){
    QLOG_INFO()<<QString("[<<<----FloatForm::RefreshStoreStatus:--->>>>]");
    int titleLab_w = 35, titleLab_h = 14,  statusLab_w = 30, statusLab_h = 14;
    int first_x = 15, first_y = 35,  col_interval = 15, row_interval = 10;
    //准备MOD门店营业状态Label;
    this->ui->Mod1Lable->move( first_x, first_y); //左边距 first_x 像素;  上边距: first_y 像素;
    this->ui->Mod1Lable->setPixmap( QPixmap(":ModTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    this->ui->Mod2Lable->move( first_x + titleLab_w + col_interval, first_y );
    if(1 == modStoreStatus){
        this->ui->Mod2Lable->setPixmap( QPixmap(":StoreOn.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }else if(2 == modStoreStatus){
        this->ui->Mod2Lable->setPixmap( QPixmap(":StoreOff.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }else {
        this->ui->Mod2Lable->setPixmap( QPixmap(":StoreDef.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }

    //准备Eleme门店营业状态Label;
    this->ui->Eleme1Lable->move( first_x,  first_y + 1* ( titleLab_h + row_interval ) );
    this->ui->Eleme1Lable->setPixmap( QPixmap(":ElemeTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    this->ui->Eleme2Lable->move(first_x + titleLab_w + col_interval, first_y + 1* ( statusLab_h + row_interval ) );
    if(1 == eleStoreStatus){
        this->ui->Eleme2Lable->setPixmap( QPixmap(":StoreOn.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }else if(2 == eleStoreStatus){
        this->ui->Eleme2Lable->setPixmap( QPixmap(":StoreOff.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else {
        this->ui->Eleme2Lable->setPixmap( QPixmap(":StoreDef.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }

    //准备Mop门店营业状态Label;
    this->ui->Mop1Lable->move(first_x, first_y + 2* ( titleLab_h + row_interval ) );
    this->ui->Mop1Lable->setPixmap( QPixmap(":MopTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    this->ui->Mop2Lable->move(first_x + titleLab_w + col_interval,  first_y + 2* ( statusLab_h + row_interval ) );
    if(1 == mopStoreStatus){
        this->ui->Mop2Lable->setPixmap( QPixmap(":StoreOn.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else if(2 == mopStoreStatus) {
        this->ui->Mop2Lable->setPixmap( QPixmap(":StoreOff.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else {
        this->ui->Mop2Lable->setPixmap( QPixmap(":StoreDef.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }

    //准备美团 门店营业状态Label;
    this->ui->Mt1Lable->move(first_x, first_y + 3* ( titleLab_h + row_interval ) );
    this->ui->Mt1Lable->setPixmap( QPixmap(":MtTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    this->ui->Mt2Lable->move(first_x + titleLab_w + col_interval, first_y + 3* ( titleLab_h + row_interval ) );
    if(1 == mtStoreStatus){
        this->ui->Mt2Lable->setPixmap( QPixmap(":StoreOn.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else if(2 == mtStoreStatus) {
        this->ui->Mt2Lable->setPixmap( QPixmap(":StoreOff.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else {
        this->ui->Mt2Lable->setPixmap( QPixmap(":StoreDef.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }

    //准备订单管理状态Label;  NomalOrderManager
    this->ui->OrderManagerLable->move(3, 122);
    if ( m_bExistNoAckNotice ) {
        this->ui->OrderManagerLable->setPixmap( QPixmap(":SmallHorn.png").scaled(110, 30, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else {
        this->ui->OrderManagerLable->setPixmap( QPixmap(":NomalOrderManager.png").scaled(110, 30, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }

}


void FloatForm::RefreshOrderManagerStatus(int existNewOrder){
    QLOG_INFO()<<QString("[<<<----FloatForm::RefreshOrderManagerStatus:%1--->>>>]").arg(existNewOrder);
    if(existNewOrder){ //有新订单;
        this->ui->OrderManagerLable->move(3, 122);
        this->ui->OrderManagerLable->setPixmap( QPixmap(":ComeNewOrder.png").scaled(110, 30, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else { //无新订单;
        this->ui->OrderManagerLable->move(3, 122);

        if ( m_bExistNoAckNotice ) {
            this->ui->OrderManagerLable->setPixmap( QPixmap(":SmallHorn.png").scaled(110, 30, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
        } else {
            this->ui->OrderManagerLable->setPixmap( QPixmap(":NomalOrderManager.png").scaled(110, 30, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
        }
    }
}
