#include "timewidget.h"
#include "ledtext.h"

#include <QHBoxLayout>
#include <QLabel>
#include <QLCDNumber>


TimeWidget::TimeWidget(QWidget *parent)
    : QWidget(parent)
{
    initUI();
    connects();
}

TimeWidget::~TimeWidget()
{
}

void TimeWidget::start()
{
    mTimer.start();
    mStartTime = QDateTime::currentDateTime();
    mEndTime = mStartTime;

    QString strStartTime = mStartTime.toString("hh:mm:ss");
    mStartTimeLCDNumber->display(strStartTime);
    mEndTimeLCDNumber->display(strStartTime);
}

void TimeWidget::stop()
{
    mTimer.stop();
    QString startTime = QDateTime::currentDateTime().toString("hh:mm:ss");
    mEndTimeLCDNumber->display(startTime);

    mEndTime = QDateTime::currentDateTime();
}


void TimeWidget::initUI()
{
    mTimeHLayout = new QHBoxLayout;
    mTimeHLayout->setContentsMargins(10, 0, 10, 0);
    mStartTimeLabel = new QLabel("开始时间：");
    mStartTimeLCDNumber = new QLCDNumber;
    mStartTimeLCDNumber->setDigitCount(8);
    mStartTimeLCDNumber->setMinimumHeight(50);
    mStartTimeLCDNumber->setMinimumWidth(150);
    mEndTimeLabel = new QLabel("结束时间：");
    mEndTimeLCDNumber = new QLCDNumber;
    mEndTimeLCDNumber->setDigitCount(8);
    mEndTimeLCDNumber->setMinimumHeight(50);
    mEndTimeLCDNumber->setMinimumWidth(150);
    mTimeSpanLabel = new QLabel("时间差：");
    mTimeSpanLedText = new LedText;
    mTimeSpanLedText->setForeground("#FFC400");
    mTimeHLayout->addWidget(mStartTimeLabel);
    mTimeHLayout->addWidget(mStartTimeLCDNumber);
    mTimeHLayout->addStretch();
    mTimeHLayout->addWidget(mEndTimeLabel);
    mTimeHLayout->addWidget(mEndTimeLCDNumber);
    mTimeHLayout->addStretch();
    mTimeHLayout->addWidget(mTimeSpanLabel);
    mTimeHLayout->addWidget(mTimeSpanLedText);
    this->setLayout(mTimeHLayout);

    mTimer.setInterval(1000);

}

void TimeWidget::connects()
{
    connect(&mTimer, &QTimer::timeout, this, &TimeWidget::updateTimeDisplay);
}

void TimeWidget::updateTimeDisplay()
{
    mEndTime = QDateTime::currentDateTime();
    QString startTime = mEndTime.toString("hh:mm:ss");
    mEndTimeLCDNumber->display(startTime);

    int secondSpan = mEndTime.toSecsSinceEpoch() - mStartTime.toSecsSinceEpoch();
    QString strSpanTime;
    if(secondSpan < 60)
    {
        strSpanTime = QString("%1秒").arg(secondSpan);
    }
    else if(secondSpan >= 60 && secondSpan < 60 * 60)
    {
        int minute = int(secondSpan / 60);
        int second = secondSpan - minute * 60;
        strSpanTime = QString("%1分%2秒").arg(minute).arg(second);
    }
    else if(secondSpan >= 60 * 60 && secondSpan < 60 * 60 * 24)
    {
        int hour = int(secondSpan / 3600);
        int minute = (secondSpan - hour * 3600) / 60;
        int second = secondSpan - hour * 3600 - minute * 60;
        strSpanTime = QString("%1时%2分%3秒").arg(hour).arg(minute).arg(second);
    }
    mTimeSpanLedText->setText(strSpanTime);
}
