#include "alarmEventMainDialog.h"
#include "ui_alarmEventMainDialog.h"
#include "transparentMask.h"
#include "messageDialog.h"
//#include "dashboardFrame.h"
#include "alarmEventDataView.h"
#include <QRegularExpressionValidator>
#include <QKeyEvent>

AlarmEventMainDialog::AlarmEventMainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::alarmEventMainDialog)
    , m_mode(Historical_All)
    , m_pTransparentMask(nullptr)
    , m_pMessageDialog(nullptr)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    //正则表达式，只能输入数字
    QRegularExpression regExp("[0-9]+");
    QRegularExpressionValidator* validator = new QRegularExpressionValidator(regExp, this);
    ui->lineEditPage->setValidator(validator);
    ui->lineEditPage->installEventFilter(this);

    //时间范围初始化
    QDateTime endTime = QDateTime::currentDateTime();
    QDateTime beginTime = QDateTime::currentDateTime().addDays(-15);
    ui->endTime->setDateTime(endTime);
    ui->endTime->installEventFilter(this);
    ui->beginTime->setDateTime(beginTime);
    ui->beginTime->installEventFilter(this);
    m_eventFilter.setTimeRange(beginTime, endTime);

    m_tableView = new AlarmEventDataView(Historical_All, this);
    m_tableView->model()->setFilter(m_eventFilter);
    ui->tableLayout->addWidget(m_tableView);
    connect(m_tableView->model(), &AlarmEventDataModel::syncDataStatus, this, &AlarmEventMainDialog::onSyncDataStatus);
    connect(m_tableView->model(), &AlarmEventDataModel::loadDataError, this, &AlarmEventMainDialog::onLoadDataError);

    connect(ui->btnClose, &QPushButton::clicked, this, &AlarmEventMainDialog::onBtnClicked_close);
    connect(ui->btnConfirmAll, &QPushButton::clicked, this, &AlarmEventMainDialog::onBtnClicked_confirmAll);

    connect(ui->btnFirstPage, &QPushButton::clicked, this, &AlarmEventMainDialog::onBtnClicked_firstPage);
    connect(ui->btnPreviousPage, &QPushButton::clicked, this, &AlarmEventMainDialog::onBtnClicked_previousPage);
    connect(ui->btnNextPage, &QPushButton::clicked, this, &AlarmEventMainDialog::onBtnClicked_nextPage);
    connect(ui->btnLastPage, &QPushButton::clicked, this, &AlarmEventMainDialog::onBtnClicked_lastPage);
}

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

void AlarmEventMainDialog::showEvent(QShowEvent* event)
{
    QDialog::showEvent(event);
}

void AlarmEventMainDialog::resizeEvent(QResizeEvent* event)
{
    if(m_pTransparentMask  && m_pTransparentMask->isVisible())
        m_pTransparentMask->setGeometry(0, 0, this->width(), this->height());
}

bool AlarmEventMainDialog::eventFilter(QObject* obj, QEvent* event)
{
    if(obj == ui->lineEditPage)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(event);
            if (pKeyEvent->key() == Qt::Key_Enter || pKeyEvent->key() == Qt::Key_Return)
            {
                onEditingFinished_page();
            }
        }
        else if(event->type() == QEvent::FocusOut)
            onEditingFinished_page();
    }
    else if(obj == ui->beginTime)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(event);
            if (pKeyEvent->key() == Qt::Key_Enter || pKeyEvent->key() == Qt::Key_Return)
            {
                onBeginTimeChanged();
            }
        }
        else if(event->type() == QEvent::FocusOut)
            onBeginTimeChanged();
    }
    else if(obj == ui->endTime)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(event);
            if (pKeyEvent->key() == Qt::Key_Enter || pKeyEvent->key() == Qt::Key_Return)
            {
                onEndTimeChanged();
            }
        }
        else if(event->type() == QEvent::FocusOut)
            onEndTimeChanged();
    }

    return QWidget::eventFilter(obj, event);
}

void AlarmEventMainDialog::showTransparentMask()
{
    if(m_pTransparentMask == nullptr)
        m_pTransparentMask = new TransparentMask(this);

    m_pTransparentMask->setGeometry(0, 0, this->width(), this->height());
    m_pTransparentMask->show();
}
void AlarmEventMainDialog::hideTransparentMask()
{
    if(m_pTransparentMask && m_pTransparentMask->isVisible())
        m_pTransparentMask->hide();
}

void AlarmEventMainDialog::showMessageDialog(MessageDialogType type, const QString& strTitle, const QString& strContent)
{
    if(m_pMessageDialog == nullptr)
    {
        m_pMessageDialog = new MessageDialog(this);
        m_pMessageDialog->installEventFilter(this);
        connect(m_pMessageDialog, SIGNAL(sgl_hide()), this, SLOT(onSignal_subDialogClose()));
    }

    m_pMessageDialog->setMessage(type, strTitle, strContent);
    int nX = (this->width() - m_pMessageDialog->width()) * 0.5;
    int nY = (this->height() - m_pMessageDialog->height()) * 0.5;
    m_pMessageDialog->move(nX, nY);
    m_pMessageDialog->raise();
    if(type == type_question)
        m_pMessageDialog->exec();
    else
        m_pMessageDialog->show();
}

void AlarmEventMainDialog::setMode(AlarmDataMode mode)
{
    if(mode == Historical_Unconfirmed)
    {
        ui->label_WindowlTitle->setText("实时事件");
        ui->btnConfirmAll->setVisible(true);
        ui->conboBox_confirmStatus->setEnabled(false);
        ui->conboBox_confirmStatus->setCurrentIndex(1);
        m_eventFilter.setConfirmStatusFilter(0);
    }
    else if(mode == Historical_All)
    {
        ui->label_WindowlTitle->setText("历史事件");
        ui->btnConfirmAll->setVisible(false);
        ui->conboBox_confirmStatus->setEnabled(true);
        ui->conboBox_confirmStatus->setCurrentIndex(0);
        m_eventFilter.setConfirmStatusFilter(-1); //-1表示所有事件(确认+未确认)
    }

    m_tableView->model()->setMode(mode);
    m_tableView->model()->setFilter(m_eventFilter);
    m_mode = mode;
}

void AlarmEventMainDialog::onSignal_subDialogClose()
{
    hideTransparentMask();
}

void AlarmEventMainDialog::onSyncDataStatus(const PaginationInfo& paginationInfo)
{
    QString recordInfo = QString::fromWCharArray(L"共 %1 条记录").arg(paginationInfo.totalEntries);
    ui->recordInfo->setText(recordInfo);
    ui->lineEditPage->setText(QString::number(paginationInfo.currentPage));
}

void AlarmEventMainDialog::onLoadDataError(const QString& error)
{
    if(!this->isVisible())
        return;

    showTransparentMask();
    showMessageDialog(type_warning, QString("错误"), QString("加载数据失败(%1)").arg(error));
}

void AlarmEventMainDialog::onBeginTimeChanged()
{
    //qDebug() << "beginTimeChanged: " << ui->beginTime->dateTime().toString("yyyy-MM-dd hh:mm:ss");
    qint64 beginTime = ui->beginTime->dateTime().toMSecsSinceEpoch();
    qint64 endTime = ui->endTime->dateTime().toMSecsSinceEpoch();
    if(beginTime > endTime)
    {
        showTransparentMask();
        showMessageDialog(type_warning, QString("错误"), QString("'最早时间' 不能晚于 '最后时间'"));
        return;
    }

    if(m_eventFilter.beginTime() == ui->beginTime->dateTime())
        return;

    m_eventFilter.setTimeRange(ui->beginTime->dateTime(), ui->endTime->dateTime());
    m_tableView->model()->setFilter(m_eventFilter);
}

void AlarmEventMainDialog::onEndTimeChanged()
{
    qint64 beginTime = ui->beginTime->dateTime().toMSecsSinceEpoch();
    qint64 endTime = ui->endTime->dateTime().toMSecsSinceEpoch();
    if(beginTime > endTime)
    {
        showTransparentMask();
        showMessageDialog(type_warning, QString("错误"), QString("'最后时间' 不能早于 '最早时间'"));
        return;
    }

    if(m_eventFilter.endTime() == ui->endTime->dateTime())
        return;

    m_eventFilter.setTimeRange(ui->beginTime->dateTime(), ui->endTime->dateTime());
    m_tableView->model()->setFilter(m_eventFilter);
}

void AlarmEventMainDialog::onBtnClicked_close()
{
    //reject();
    hide();
    emit sgl_hide();
}

void AlarmEventMainDialog::onBtnClicked_confirmAll()
{
    m_tableView->model()->confirmCurPageEvents();
}

void AlarmEventMainDialog::onBtnClicked_firstPage()
{
    m_tableView->model()->firstPage();
}

void AlarmEventMainDialog::onBtnClicked_previousPage()
{
    m_tableView->model()->previousPage();
}

void AlarmEventMainDialog::onBtnClicked_nextPage()
{
    m_tableView->model()->nextPage();
}

void AlarmEventMainDialog::onBtnClicked_lastPage()
{
    m_tableView->model()->lastPage();
}

void AlarmEventMainDialog::onEditingFinished_page()
{
    //qInfo() << "onEditingFinished_page";
    QString strPage = ui->lineEditPage->text();
    bool result = m_tableView->model()->setCurrentPage(strPage.toInt());
    if(!result)
        ui->lineEditPage->setText(QString::number(m_tableView->model()->currentPage()));
}
