#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_miniStoreStatusForm = new MiniStoreStatusForm(this);

    m_animation.setTargetObject(this);
    m_animation.setPropertyName("windowOpacity");
    m_animation.setDuration(ConfigManger::GetInstance().GetBlinkInterval());
    m_animation.setEasingCurve(QEasingCurve::InOutSine);
    m_raiseTimer.setInterval(2000);
    m_scrollDisplayStoreStatusTimer.setInterval(2000);
    connect(&m_raiseTimer, &QTimer::timeout, this, &FloatForm::raise);
    connect(&m_scrollDisplayStoreStatusTimer, &QTimer::timeout, this, &FloatForm::onScrollDisplayStoreStatus); 
    connect(this, &FloatForm::showMiniStoreStatusForm, m_miniStoreStatusForm, &MiniStoreStatusForm::onShow);
    _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;

        // 当子集门店营业状态是可见状态时, 移动悬浮框时, 迷你子集门店营业框同时移动;
        if ( m_miniStoreStatusForm->isVisible() ) {
            QPoint mSSFPoint = pos();
            mSSFPoint.setX( mSSFPoint.x() - MINI_STORE_STATUS_FORM_LEFT_OFFSET );
            m_miniStoreStatusForm->move( mSSFPoint + moveAmount );
        }
    }
}


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);
        // 同步移动子集门店营业状态
        if ( m_miniStoreStatusForm->isVisible() ) {
            m_miniStoreStatusForm->move( QPoint(nWidth  - MINI_STORE_STATUS_FORM_LEFT_OFFSET, nHeight) );
        }

    }
}

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

    m_eleStoreStatus = 0;
    m_modStoreStatus = 0;
    m_mopStoreStatus = 0;
    m_mtStoreStatus = 0;
    m_curbsideStoreStatus = 0;
    m_deliveryComboStoreStatus = 0;

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

    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()
{
    //QSound::play(m_remindWav);
    if(m_bReminding) {
        //QTimer::singleShot(m_wavPlayInterval, this, &FloatForm::_PlayWav);
        QLOG_INFO()<<QString("[<<<----FloatForm::_PlayWav m_bReminding: --->>>>]")<< m_bReminding;
    }
}

void FloatForm::onStartRemind(int type)
{
    QLOG_INFO()<<QString("[<<<----FloatForm::onStartRemind:type:%1;m_bReminding: --->>>>]").arg(type)<< m_bReminding;
    //每次播报音频，将会导致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 curbsideStoreStatus, int existNoAckNotice){
    QLOG_INFO()<<QString("[<<<----FloatForm::onUpdateStoreStatus: eleStoreStatus: %1, modStoreStatus: %2, "
                         "mopStoreStatus: %3, mtStoreStatus: %4, curbsideStoreStatus: %5, existNoAckNotice:%6 --->>>>]")
              .arg(eleStoreStatus).arg(modStoreStatus).arg(mopStoreStatus).arg(mtStoreStatus).arg(curbsideStoreStatus).arg(existNoAckNotice);
    m_bExistNoAckNotice = existNoAckNotice;
    m_eleStoreStatus = eleStoreStatus;
    m_modStoreStatus = modStoreStatus;
    m_mopStoreStatus = mopStoreStatus;
    m_mtStoreStatus = mtStoreStatus;
    m_curbsideStoreStatus = curbsideStoreStatus;
    RefreshStoreStatus();
}


void FloatForm::RefreshStoreStatus(){
    int titleLab_w = 30, titleLab_h = 18,  statusLab_w = 30, statusLab_h = 18;
    int first_x = 4, first_y = 25 ;
    this->ui->storeStatusWdg->move(first_x, first_y);
    //准备MOD门店营业状态的 展示逻辑; 【调试 mock 假数据】
    // m_modStoreStatus=1, m_eleStoreStatus=3, m_mtStoreStatus=1, m_mopStoreStatus =3, m_curbsideStoreStatus = 2;

    if ( m_modStoreStatus == 1 && m_eleStoreStatus == 1 && m_mtStoreStatus == 1 ) {
        m_deliveryComboStoreStatus = 1;
    } else if ( m_modStoreStatus == 2 ||  m_eleStoreStatus == 2 || m_mtStoreStatus == 2 ) {
        m_deliveryComboStoreStatus = 2;
    } else {
        m_deliveryComboStoreStatus = 3;
    }
    //准备MOD门店营业状态Label;
    this->ui->Delivery1Lable->setPixmap( QPixmap(":DeliveryTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    if(1 == m_deliveryComboStoreStatus){
        this->ui->Delivery2Button->setIcon( QIcon(":StoreComboOn.png") );
        this->ui->Delivery2Button->setIconSize( QSize( titleLab_w + 6, titleLab_h + 15) );
    }else if(2 == m_deliveryComboStoreStatus){
        this->ui->Delivery2Button->setIcon( QIcon(":StoreComboOff.png") );
        this->ui->Delivery2Button->setIconSize( QSize( titleLab_w + 6, titleLab_h + 15) );
    }else {
        this->ui->Delivery2Button->setIcon( QIcon(":StoreComboDef.png") );
        this->ui->Delivery2Button->setIconSize( QSize( titleLab_w + 6, titleLab_h + 15) );
    }

    //准备Mop门店营业状态Label;
    this->ui->Mop1Lable->setPixmap( QPixmap(":MopTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    if(1 == m_mopStoreStatus){
        this->ui->Mop2Lable->setPixmap( QPixmap(":StoreOn.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else if(2 == m_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) );
    }

    //准备Curbside 门店营业状态Label;
    this->ui->Curbside1Lable->setPixmap( QPixmap(":CurbsideTitle.png").scaled(titleLab_w, titleLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    if(1 == m_curbsideStoreStatus){
        this->ui->Curbside2Lable->setPixmap( QPixmap(":StoreOn.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else if(2 == m_curbsideStoreStatus) {
        this->ui->Curbside2Lable->setPixmap( QPixmap(":StoreOff.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    } else {
        this->ui->Curbside2Lable->setPixmap( QPixmap(":StoreDef.png").scaled(statusLab_w, statusLab_h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) );
    }

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

    //准备App-MOD 门店营业状态;
    //准备Eleme门店营业状态;
    //准备美团外卖 门店营业状态;
    m_miniStoreStatusForm->RefreshStoreStatus( m_modStoreStatus, m_eleStoreStatus, m_mtStoreStatus );
}


void  FloatForm::onScrollDisplayStoreStatus(){
    // 营业状态多页 自动切换刷新;
    int pageCount = ui->storeStatusWdg->count();
    int pageCurIndex = ui->storeStatusWdg->currentIndex();
    // QLOG_INFO()<<QString("[<<<----FloatForm::onScrollDisplayStoreStatus  pageCount:%1 curentPageIndex:%2--->>>>]").arg( pageCount ).arg( pageCurIndex );
    if ( pageCurIndex != pageCount - 1 ) {
        ui->storeStatusWdg->setCurrentIndex( pageCurIndex + 1 );
    } else {
        ui->storeStatusWdg->setCurrentIndex( 0 );
    }
    ui->storeStatusWdg->update();
}


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

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



void FloatForm::on_Delivery2Button_clicked(){
  QLOG_INFO()<<QString("[<<<----FloatForm::on_Delivery2Button_clicked--->>>>]");
  emit showMiniStoreStatusForm(m_modStoreStatus, m_eleStoreStatus, m_mtStoreStatus );

}
