/*
 * Kylin-video
 *
 * Copyright (C) 2021, Tianjin KYLIN Information Technology Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: Liu Cong <liucong1@kylinos.cn>
 *
 */

#include "contralbar.h"
#include "ui_contralbar.h"
#include <QDebug>
#include <QTime>
#include <QTimer>
#include <QSlider>
#include <QToolTip>
#include <QGSettings>
#include <QListWidget>
#include <QHBoxLayout>
#include <QPropertyAnimation>
#include <QPalette>

#include "global/globalsignal.h"
#include "global/global.h"
#include "filletwidget.h"
#include "previewwidget.h"

using namespace Global;

QString int2ts(int64_t time, bool use_msec)
{
    if (time == 0) {
        return QString("--:--:--");
    }
    // 当前是秒
    time *= 1000;

    int64_t hour = 60*60*1000;
    int64_t minute = 60*1000;
    int64_t second = 1*1000;

    int64_t h = time/hour;
    int64_t m = time%hour/minute;
    int64_t s = time%minute/second;
    int64_t ms = time%1000;
    char res[16];
    if(use_msec)
        sprintf(res, "%02ld:%02ld:%02ld.%03ld", h, m, s, ms);
    else
        sprintf(res, "%02ld:%02ld:%02ld", h, m, s);
    return QString(res);
}

ContralBar::ContralBar(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ContralBar),
    m_isMute(false)
{
    ui->setupUi(this);

    m_speed = 1;
    m_seekTime = 0;
    m_duration = 0;
    m_isChangeTime = false;
    m_isFullScreen = false;
    m_isMouseEnter = false;
    m_isMiniMode = false;
    m_canChangeDuration = true;
    m_speedList = nullptr;

    m_isSeeking = false;
    m_seekTimer = new QTimer;
    m_seekTimer->setInterval(200);
    connect(m_seekTimer, &QTimer::timeout, this, [this](){m_isSeeking = false;});

    if(g_settings->contains("General/volume"))
    {
        m_volume = g_settings->value("General/volume").toInt();
        g_user_signal->setVolume(m_volume);
    }
    else
    {
        m_volume = 50;
        g_settings->setValue("General/volume", m_volume);
    }

    initStyle();
    initConnect();
    initGlobalSig();
    initAnimation();
    ui->slider_time->installEventFilter(this);

    // 根据主题设置样式
    if(g_settings->value("General/follow_system_theme").toBool())
    {
        if(g_gsettings->get("styleName").toString() == STYLE_UKUI_DEFAULT)
            setLightTheme();
        else
            setBlackTheme();
    }
    else
    {
        if(g_settings->value("General/theme").toInt() == 0)
            setLightTheme();
        else
            setBlackTheme();
    }

    // 设置进度条为伸缩量，不设置的话会和其他控件平分剩下空间
    ((QBoxLayout*)ui->widget->layout())->setStretchFactor(ui->slider_time, 1);
}

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

void ContralBar::setDuration(int duration)
{
    m_duration = duration;
    ui->slider_time->setRange(0, m_duration * 100);
    ui->label_pos->setText(QString("00:00:00").append("/").append(int2ts(m_duration, false)));
}

void ContralBar::setCurrentTime(int currentTime)
{
    if(m_isChangeTime)
        return;
    m_currentTime = currentTime;
    ui->slider_time->setValue(currentTime);
    ui->label_pos->setText(int2ts(currentTime, false).append("/").append(int2ts(m_duration, false)));
}

void ContralBar::setPreviewSize(QSize size)
{
    m_previewWidget->resize(size);
    m_previewWidget->setMoveRange(ui->slider_time->width());
}

void ContralBar::setHide()
{
    m_volumeWidget->hide();
    m_speedWidget->hide();
    hide();
}

void ContralBar::setShow()
{
    if(!m_isMiniMode)
        show();
}

void ContralBar::setBlackTheme()
{
    m_theme = STYLE_UKUI_BLACK;
    ui->btn_pre->setStyleSheet("QPushButton:!hover{border-image: url(:/ico/lastsong_d_3x.png);}"
                               "QPushButton:hover{border-image: url(:/ico/lastsong_h_3x.png);}"
                               "QPushButton:pressed{border-image: url(:/ico/lastsong_h_3x.png);}");

    ui->btn_next->setStyleSheet("QPushButton:!hover{border-image: url(:/ico/nextsong_d_3x.png);}"
                                "QPushButton:hover{border-image: url(:/ico/nextsong_h_3x.png);}"
                                "QPushButton:pressed{border-image: url(:/ico/nextsong_h_3x.png);}");

    ui->btn_speed->setStyleSheet("QPushButton:!hover{border-image: url(:/ico/nextsong_d_3x.png);}"
                                 "QPushButton:hover{border-image: url(:/ico/nextsong_h_3x.png);}"
                                 "QPushButton:pressed{border-image: url(:/ico/nextsong_h_3x.png);}");

    ui->btn_tool->setStyleSheet("QPushButton:!hover{border-image: url(:/ico/icon-screenshot-symbolic-d.png);}"
                                "QPushButton:hover{border-image: url(:/ico/icon-screenshot-symbolic-d.png);}"
                                "QPushButton:pressed{border-image: url(:/ico/icon-screenshot-symbolic-d.png);}");

    ui->label_pos->setStyleSheet("color:#ffffff;");

    ui->slider_time->setBlackTheme();

    m_speedList->setStyleSheet("QListWidget{background-color: rgba(255, 255, 255, 0);}"
                               "QListWidget::item::!selected{background-color:rgba(1,1,1,0);color:rgb(255,255,255);}"
                               "QListWidget::item::selected{background-color:rgba(1,1,1,0);color:rgb(55,144,250);}");

    updateIcon();
}

void ContralBar::setLightTheme()
{
    m_theme = STYLE_UKUI_DEFAULT;
    ui->btn_pre->setStyleSheet("QPushButton:!hover{border-image: url(:/ico_light/lastsong-d.png);}"
                               "QPushButton:hover{border-image: url(:/ico_light/lastsong-h.png);}"
                               "QPushButton:pressed{border-image: url(:/ico_light/lastsong-h.png);}");

    ui->btn_next->setStyleSheet("QPushButton:!hover{border-image: url(:/ico_light/nextsong-d.png);}"
                                "QPushButton:hover{border-image: url(:/ico_light/nextsong-h.png);}"
                                "QPushButton:pressed{border-image: url(:/ico_light/nextsong-h.png);}");

    ui->btn_speed->setStyleSheet("QPushButton:!hover{border-image: url(:/ico_light/nextsong_d_3x.png);}"
                                 "QPushButton:hover{border-image: url(:/ico_light/nextsong_h_3x.png);}"
                                 "QPushButton:pressed{border-image: url(:/ico_light/nextsong_h_3x.png);}");

    ui->btn_tool->setStyleSheet("QPushButton:!hover{border-image: url(:/ico_light/icon-screenshot-symbolic-d.png);}"
                                "QPushButton:hover{border-image: url(:/ico_light/icon-screenshot-symbolic-d.png);}"
                                "QPushButton:pressed{border-image: url(:/ico_light/icon-screenshot-symbolic-d.png);}");

    ui->label_pos->setStyleSheet("color:#000000;");

    ui->slider_time->setLightTheme();

    m_speedList->setStyleSheet("QListWidget{background-color: rgba(255, 255, 255, 0);}"
                               "QListWidget::item::!selected{background-color:rgba(1,1,1,0);color:rgb(48,49,51);}"
                               "QListWidget::item::selected{background-color:rgba(1,1,1,0);color:rgb(55,144,250);}");

    updateIcon();
}

void ContralBar::clearMark()
{
    m_markMap.clear();
    ui->slider_time->clearMark();
}

void ContralBar::addMark(int mark_pos, QString desc)
{
    m_markMap[mark_pos] = desc;
}

void ContralBar::insertMark(int mark_pos, QString desc)
{
    m_markMap[mark_pos] = desc;
    ui->slider_time->addMark(mark_pos, desc);
}

void ContralBar::deleteMark(int mark_pos)
{
    ui->slider_time->deleteMark(mark_pos);
}

void ContralBar::initGlobalSig()
{
    // 播放状态改变
    connect(g_core_signal, &GlobalCoreSignal::sigStateChange, this, &ContralBar::slotPlayStateChange);

    // 文件信息改变
    connect(g_core_signal, &GlobalCoreSignal::sigFileInfoChange, [&](Mpv::FileInfo fi){
        if (fi.length == 0) {
            ui->slider_time->setRange(0, 1);
            ui->slider_time->setValue(0);
            ui->slider_time->setEnabled(false);
        }
        m_videoId = -1;
        if (fi.video_params.codec.indexOf("jpeg") >= 0 ||
                fi.video_params.codec.indexOf("png") >= 0 ||
                fi.video_params.codec == "") {
            m_isVideo = false;
            // 设置截图不可用
            m_toolList->item(0)->setFlags(Qt::NoItemFlags);
        }
        else {
            m_isVideo = true;
            m_toolList->item(0)->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
        }
    });

    connect(g_user_signal, &GlobalUserSignal::sigNoMarkMode, this, [&](bool noMark){
        m_toolList->setEnabled(!noMark);
    });

    connect(g_core_signal, &GlobalCoreSignal::sigDuration, [&](QString file, double duration){
        // 此处应该只接受一次改变，下一次只有在停止之后再去改变
        if (!m_canChangeDuration) {
            return;
        }
        m_canChangeDuration = false;

        m_duration = duration;
        if (m_duration == 0)
            return;
        ui->slider_time->setEnabled(true);
        ui->slider_time->setRange(0, m_duration * 100);
        ui->label_pos->setText(QString("00:00:00").append("/").append(int2ts((int)m_duration, false)));

        QMap<int, QString>::iterator iter = m_markMap.begin();
        while (iter != m_markMap.end())
        {
            ui->slider_time->addMark(iter.key(), iter.value());
            iter++;
        }
    });

    connect(g_core_signal, &GlobalCoreSignal::sigVideoIdChange, [&](int vid){
        // 打开视频全屏功能删除
        m_videoId = vid;
        return;

        // 打开视频时全屏功能
        if (vid >= 0 && m_videoId != vid) {
            if(gsetup->fullScreenWhenPlay.first)
                if(!m_isFullScreen)
                    slotFullScreen();
        }

        m_videoId = vid;
        if(m_videoId < 0){
            ui->btn_tool->setEnabled(false);
            ui->btn_fullscreen->setEnabled(false);
        }
        else{
            ui->btn_tool->setEnabled(true);
            ui->btn_fullscreen->setEnabled(true);
        }
    });

    // 更新播放时间
    connect(g_core_signal, &GlobalCoreSignal::sigCurrentTime, [&](double time){
        if(m_isChangeTime)
            return;
        m_canChangeDuration = false;
        m_currentTime = time;
        ui->slider_time->setValue(time * 100);
        if (m_currentTime >= 1)
            ui->label_pos->setText(int2ts((int)m_currentTime, false).append("/").append(int2ts((int)m_duration, false)));
    });

    // 音量改变
    connect(g_core_signal, &GlobalCoreSignal::sigVolumeChange, [&](int volume){
        if(m_state < 0)
            return;
        m_volume = volume;
        g_settings->setValue("General/volume", m_volume);
        updateIcon();
    });

    // 静音
    connect(g_core_signal, &GlobalCoreSignal::sigMuteChange, [&](bool mute){
        if(m_state < 0)
            return;
        m_isMute = mute;
        g_settings->setValue("General/mute", m_isMute);
        updateIcon();
    });

    // 快捷键设置静音走这里中转
    connect(g_user_signal, SIGNAL(sigMute()), this, SLOT(slotMute()));

    // 播放速度改变
    connect(g_core_signal, &GlobalCoreSignal::sigSpeedChange, [&](double speed){
        if(m_state < 0)
            return;
        m_speed = speed;
        int row = 7-(int)(speed*4);
        row = row<0.2 ? 0 : row;
        m_speedList->setCurrentRow(row);
        g_settings->setValue("General/speed", m_speed);
        updateIcon();
    });

    // 主题改变
    connect(g_user_signal, &GlobalUserSignal::sigTheme, [&](int theme){
        switch (theme) {
        case 0:
            if(g_gsettings->get("styleName").toString() == STYLE_UKUI_DEFAULT)
                setLightTheme();
            else
                setBlackTheme();
            break;
        case 1:
            setLightTheme();
            break;
        case 2:
            setBlackTheme();
            break;
        default:
            break;
        }
    });

    // 隐藏 显示
//    connect(g_user_signal, &GlobalUserSignal::sigHideBar, [&](bool is_hide){
//        if(is_hide)
//        {
//            if(m_isMouseEnter)
//                ((QWidget*)parent())->setCursor(QCursor(Qt::ArrowCursor));
//            else
//            {
//                hide();
//                m_volumeWidget->hide();
//                m_speedWidget->hide();
//            }
//        }
//        else
//        {
//            if(!m_isMiniMode)
//                show();
//        }
//    });

    // 快捷键全屏
    connect(g_user_signal, &GlobalUserSignal::sigFullScreen, this, &ContralBar::slotFullScreen);
}

void ContralBar::initStyle()
{
//    ui->widget->layout()->addWidget();

    ui->btn_next->setToolTip(tr("Next"));
    ui->btn_pre->setToolTip(tr("Previous"));
    ui->btn_play_pause->setToolTip(tr("Play"));
    ui->btn_volume->setToolTip(tr("Volume"));
    ui->btn_speed->setToolTip(tr("Speed"));
    ui->btn_tool->setToolTip(tr("Tools"));
    ui->btn_fullscreen->setToolTip(tr("Full screen"));

    ui->btn_next->setFixedSize(16, 16);
    ui->btn_play_pause->setFixedSize(16, 22);
    ui->btn_pre->setFixedSize(16, 16);

    ui->btn_fullscreen->setFixedSize(16, 16);
    ui->btn_speed->setFixedSize(32, 14);
    ui->btn_tool->setFixedSize(16, 16);
    ui->btn_volume->setFixedSize(16, 16);

    ui->btn_next->setCursor(Qt::PointingHandCursor);
    ui->btn_play_pause->setCursor(Qt::PointingHandCursor);
    ui->btn_pre->setCursor(Qt::PointingHandCursor);
    ui->btn_fullscreen->setCursor(Qt::PointingHandCursor);
    ui->btn_speed->setCursor(Qt::PointingHandCursor);
    ui->btn_tool->setCursor(Qt::PointingHandCursor);
    ui->btn_volume->setCursor(Qt::PointingHandCursor);

    // 音量调节界面
    m_volumeWidget = new FilletWidget((QWidget*)parent());
    m_volumeWidget->setRadius(4);
    m_volumeWidget->installEventFilter(this);
    m_volumeWidget->setFixedSize(30, 90);
    QHBoxLayout *hl_volume = new QHBoxLayout(m_volumeWidget);
    hl_volume->setContentsMargins(5, 10, 5, 10);
    m_volumeSlider = new QSlider;
    m_volumeSlider->setRange(0, 100);
    m_volumeSlider->setValue(g_settings->value("General/volume").toInt());
    hl_volume->addWidget(m_volumeSlider);
    m_volumeWidget->hide();

    // 音量调节隐藏逻辑
    m_timerVolumeWidgetHide = new QTimer;
    m_timerVolumeWidgetHide->setSingleShot(true);
    connect(m_timerVolumeWidgetHide, &QTimer::timeout, [&](){m_volumeWidget->hide();});
    m_timerVolumeWidgetHide->setInterval(500);

    // 倍速调节界面
    m_speedWidget = new FilletWidget((QWidget*)parent());
    m_speedWidget->setRadius(4);
    m_speedWidget->setFixedSize(56, 150);
    m_speedWidget->installEventFilter(this);
    QHBoxLayout *hl_speed = new QHBoxLayout(m_speedWidget);
    hl_speed->setContentsMargins(0, 0, 0, 0);
    m_speedList = new QListWidget;
    connect(m_speedList, &QListWidget::itemClicked, [&](QListWidgetItem *item){
        QString test = item->text();
        m_speed = test.left(test.length()-1).toDouble();
        g_user_signal->setSpeed(m_speed);
    });
    hl_speed->addWidget(m_speedList);
    initSpeedList();
    m_speedWidget->hide();

    m_timerSpeedWidgetHide = new QTimer;
    m_timerSpeedWidgetHide->setSingleShot(true);
    connect(m_timerSpeedWidgetHide, &QTimer::timeout, [&](){m_speedWidget->hide();});
    m_timerSpeedWidgetHide->setInterval(500);

    // 工具界面
    m_toolWidget = new FilletWidget((QWidget*)parent());
    m_toolWidget->setRadius(4);
    m_toolWidget->setFixedSize(105, 52);
    m_toolWidget->installEventFilter(this);
    QHBoxLayout *hl_tool = new QHBoxLayout(m_toolWidget);
    hl_tool->setContentsMargins(0, 0, 0, 0);
    m_toolList = new QListWidget;
    m_toolList->setAlternatingRowColors(false);
    connect(m_toolList, &QListWidget::itemClicked, [&](QListWidgetItem *item){
        item->setSelected(false);
        if (item->text() == tr("Screen shot")) {
            // 截图
            g_user_signal->screenShot(false);
        }
        else {
            // 添加书签, 现在没有书签描述
            // 判断是否无痕浏览，如果无痕浏览不能添加书签
            if (!gsetup->seamlessBrowsing.first)
                g_user_signal->addBookMark("");
        }
    });
    hl_tool->addWidget(m_toolList);
    initToolList();
    m_toolWidget->hide();

    m_timerToolWidgetHide = new QTimer;
    m_timerToolWidgetHide->setSingleShot(true);
    connect(m_timerToolWidgetHide, &QTimer::timeout, [&](){m_toolWidget->hide();});
    m_timerToolWidgetHide->setInterval(500);

    ui->btn_volume->installEventFilter(this);
    ui->btn_speed->installEventFilter(this);
    ui->btn_tool->installEventFilter(this);

    // 视频预览
    m_previewWidget = new PreviewWidget((QWidget*)parent());
    // 初始值设置为进度条的长度，当前为固定值
//    m_previewWidget->setGeometry(0, 0, ((QWidget*)parent())->width(), ((QWidget*)parent())->height());
    m_previewWidget->setHide();
    m_previewWidget->raise();
    raise();
}

/** **********************************************
 * 初始化控件槽函数
 *************************************************/
void ContralBar::initConnect()
{
    connect(g_gsettings, &QGSettings::changed, [&](QString key){
        // 如果不是跟随主题的话直接返回
        if(key == "styleName")
            if(g_settings->value("General/follow_system_theme").toBool())
                if(g_gsettings->get("styleName").toString() == STYLE_UKUI_DEFAULT)
                    setLightTheme();
                else
                    setBlackTheme();
    });

    connect(m_volumeSlider, &QSlider::valueChanged, [&](int volume){
        m_volume = volume;
        g_user_signal->setVolume(m_volume);
    });

//    connect(ui->slider_time, &TimeSlider::valueChange, [&](int value){
//        if(m_isChangeTime)
//            m_seekTime = value / 100;
//    });

    connect(ui->slider_time, &TimeSlider::sliderMoved, [&](int value){
//        if(m_isChangeTime)

        // 最后一次的时间必须要更新
        m_seekTime = value / 100;
        if (m_isSeeking)
            return;
        m_isSeeking = true;
        m_seekTimer->stop();
        m_seekTimer->start();
        QTimer::singleShot(200, [=](){
            g_user_signal->seek(m_seekTime);
        });
    });

    connect(ui->btn_play_pause, &QPushButton::clicked, [&](){
        if(m_state == Mpv::Playing)
            g_user_signal->pause();
        else if(m_state == Mpv::Paused)
            g_user_signal->play();
    });

    connect(ui->btn_pre, &QPushButton::clicked, [&](){
        g_user_signal->playPrev(true);
    });

    connect(ui->btn_next, &QPushButton::clicked, [&](){
        g_user_signal->playNext(true);
    });

    connect(ui->btn_fullscreen, &QPushButton::clicked, this, &ContralBar::slotFullScreen);
    connect(ui->btn_volume, &QPushButton::clicked, this, &ContralBar::slotMute);
    connect(ui->slider_time, &TimeSlider::mousePosChange, this, &ContralBar::slotShowPreview);
    connect(ui->slider_time, &TimeSlider::mouseLeave, [this](){
        m_previewWidget->setHide();
    });
}

void ContralBar::initAnimation()
{
    // 透明度动画不生效
    m_showAnm = new QPropertyAnimation(this, "windowOpacity");
    m_showAnm->setDuration(200);

    m_hideAnm = new QPropertyAnimation(this, "windowOpacity");
    m_hideAnm->setDuration(200);
}

/** **********************************************
 * 速度选择列表，需要做主题适配
 *************************************************/
void ContralBar::initSpeedList()
{
    QFont f("Noto Sans CJK SC Regular");
    f.setPixelSize(16);
    m_speedList->setFont(f);

    // 先设置背景，透明就行
    m_speedList->setStyleSheet("QListWidget{background-color: rgba(255, 255, 255, 0);}"
                               "QListWidget::item::selected{background-color:rgba(1,1,1,0);color:rgb(55,144,250);}");

    m_speedList->clear();
    m_speedList->addItems(QStringList() << tr("2.0X") << tr("1.5X") << tr("1.25X") << tr("1.0X") << tr("0.75X") << tr("0.5X"));
    // 初始化的时候设置
    m_speed = g_settings->value("General/speed").toDouble();
    if(m_speed == 0)
    {
        m_speed = 1.0;
        g_settings->setValue("General/speed", m_speed);
    }

    for(int i=0; i<m_speedList->count(); i++) {
        QListWidgetItem *it = m_speedList->item(i);
        it->setTextAlignment(Qt::AlignCenter);
        it->setSizeHint(QSize(52, 24));
        QString test = it->text();
        if(test.left(test.length()-1).toDouble() == m_speed)
            it->setSelected(true);
    }
    updateIcon();
}

void ContralBar::initToolList()
{
    QFont f("Noto Sans CJK SC Regular");
    f.setPixelSize(16);
    m_toolList->setFont(f);

    // 先设置背景，透明就行
    m_toolList->setStyleSheet("QListWidget{background-color: rgba(255, 255, 255, 0);}"
                              "QListWidget::item::selected{background-color:rgba(1,1,1,0);color:rgb(55,144,250);}");

    m_toolList->clear();
    m_toolList->addItems(QStringList() << tr("Screen shot") << tr("Add mark"));
    for (int i=0; i<m_toolList->count(); i++) {
        m_toolList->item(i)->setTextAlignment(0x0004);
    }
}

void ContralBar::updateIcon()
{
    // 更新播放按钮
    QString ico_dir, ico;
    if(m_theme == STYLE_UKUI_DEFAULT)
        ico_dir = "ico_light";
    else
        ico_dir = "ico";

    if(m_state == Mpv::Playing) {
        ico = "suspend";
        ui->btn_play_pause->setToolTip(tr("Pause"));
    }
    else {
        ico = "play";
        ui->btn_play_pause->setToolTip(tr("Play"));
    }


    ui->btn_play_pause->setStyleSheet(QString("QPushButton:!hover{border-image: url(:/%1/%2-d.png);}"
                                      "QPushButton:hover{border-image: url(:/%1/%2-h.png);}"
                                      "QPushButton:pressed{border-image: url(:/%1/%2-h.png);}")
                                      .arg(ico_dir).arg(ico));

    // 更新音量按钮
    m_volume = g_settings->value("General/volume").toInt();
    m_isMute = g_settings->value("General/mute").toBool();
    m_volumeSlider->setValue(m_volume);
    if(m_volume == 0 || m_isMute)
        ico = "muted";
    else if(m_volume < 50)
        ico = "medium";
    else
        ico = "high";
    ui->btn_volume->setStyleSheet(QString("QPushButton:!hover{border-image: url(:/%1/audio-volume-%2-symbolic-d.png);}"
                                  "QPushButton:hover{border-image: url(:/%1/audio-volume-%2-symbolic-h.png);}"
                                  "QPushButton:pressed{border-image: url(:/%1/audio-volume-%2-symbolic-h.png);}")
                                  .arg(ico_dir).arg(ico));

    // 倍速播放按钮 视频播放开始倍速都默认为1
    ui->btn_speed->setStyleSheet(QString("QPushButton:!hover{border-image: url(:/%1/%2X-d.png);}"
                                  "QPushButton:hover{border-image: url(:/%1/%2X-h.png);}"
                                  "QPushButton:pressed{border-image: url(:/%1/%2X-h.png);}")
                                 .arg(ico_dir).arg(m_speed));

    // 全屏按钮
    if(m_isFullScreen) {
        ico = "restore";
        ui->btn_fullscreen->setToolTip(tr("Exit full screen"));
    }
    else {
        ui->btn_fullscreen->setToolTip(tr("Full screen"));
        ico = "fullscreen";
    }
    ui->btn_fullscreen->setStyleSheet(QString("QPushButton:!hover{border-image: url(:/%1/icon-%2-d.png);}"
                                      "QPushButton:hover{border-image: url(:/%1/icon-%2-h.png);}"
                                      "QPushButton:pressed{border-image: url(:/%1/icon-%2-h.png);}")
                                      .arg(ico_dir).arg(ico));

}

bool ContralBar::eventFilter(QObject *target, QEvent *event)
{
    if(target == ui->slider_time)
    {
//        if(event->type() == QEvent::MouseButtonPress)
//        {
//            m_isChangeTime = true;
//        }
//        else if(event->type() == QEvent::MouseButtonRelease && m_isChangeTime)
//        {
//            g_user_signal->seek(m_seekTime);
//            m_isChangeTime = false;
//        }
    }
    else if(target == m_volumeWidget)
    {
        if(event->type() == QEvent::Leave)
        {
            m_timerVolumeWidgetHide->start();
            m_isMouseEnter = false;
            emit sigCanHide(true);
        }
        else if(event->type() == QEvent::Enter)
        {
            m_timerVolumeWidgetHide->stop();
            m_isMouseEnter = true;
            emit sigCanHide(false);
        }
    }
    else if(target == m_speedWidget)
    {
        if(event->type() == QEvent::Leave)
        {
            m_timerSpeedWidgetHide->start();
            m_isMouseEnter = false;
            emit sigCanHide(true);
        }
        else if(event->type() == QEvent::Enter)
        {
            m_timerSpeedWidgetHide->stop();
            m_isMouseEnter = true;
            emit sigCanHide(false);
        }
    }
    else if(target == m_toolWidget)
    {
        if(event->type() == QEvent::Leave)
        {
            m_timerToolWidgetHide->start();
            m_isMouseEnter = false;
            emit sigCanHide(true);
        }
        else if(event->type() == QEvent::Enter)
        {
            m_timerToolWidgetHide->stop();
            m_isMouseEnter = true;
            emit sigCanHide(false);
        }
    }
    else if(target == ui->btn_speed)
    {
        if(event->type() == QEvent::Leave)
        {
            m_timerSpeedWidgetHide->start();
        }
        else if(event->type() == QEvent::Enter)
        {
            m_volumeWidget->hide();
            m_toolWidget->hide();
            m_speedWidget->show();
            m_timerSpeedWidgetHide->stop();
        }
    }
    else if(target == ui->btn_volume)
    {
        if(event->type() == QEvent::Leave)
        {
            m_timerVolumeWidgetHide->start();
        }
        else if(event->type() == QEvent::Enter)
        {
            m_speedWidget->hide();
            m_toolWidget->hide();
            m_volumeWidget->show();
            m_timerVolumeWidgetHide->stop();
        }
    }
    else if (target == ui->btn_tool) {
        if(event->type() == QEvent::Leave)
        {
            m_timerToolWidgetHide->start();
        }
        else if(event->type() == QEvent::Enter)
        {
            m_speedWidget->hide();
            m_volumeWidget->hide();
            m_toolWidget->show();
            m_timerToolWidgetHide->stop();
        }
    }
    return QWidget::eventFilter(target, event);
}

void ContralBar::moveEvent(QMoveEvent *event)
{
    // 位置写为固定相对位置, 152和129为手动调试测出来的，可能不精确.
    m_volumeWidget->move(x()+width()-152, y()-2-m_volumeWidget->height());
    m_speedWidget->move(x()+width()-129, y()-2-m_speedWidget->height());
    m_toolWidget->move(x()+width()-110, y()-2-m_toolWidget->height());
    return QWidget::moveEvent(event);
}

void ContralBar::leaveEvent(QEvent *event)
{
    m_isMouseEnter = false;
    emit sigCanHide(true);
}

void ContralBar::showEvent(QShowEvent *event)
{
    m_previewWidget->setMoveRange(ui->slider_time->width());
}

void ContralBar::enterEvent(QEvent *event)
{
    m_isMouseEnter = true;
    emit sigCanHide(false);
}

/** **********************************
 * 播放暂停
 *************************************/
void ContralBar::on_btn_play_pause_clicked()
{
    switch (m_state) {
    case Mpv::Playing:
        g_user_signal->pause();
        break;
    case Mpv::Paused:
        g_user_signal->play();
        break;
    default:
        break;
    }
}

/** **********************************
 * 全屏/非全屏
 *************************************/
void ContralBar::slotFullScreen()
{
    if (m_isFullScreen) {
        m_isFullScreen = false;
    }
    else {
        m_isFullScreen = true;
    }
    emit sigFullScreen(m_isFullScreen);
    updateIcon();
    return;
}

void ContralBar::slotMute()
{
    g_user_signal->setMute(!m_isMute);
}

void ContralBar::slotShowPreview(int _time)
{
    if (m_videoId < 0 || !m_isVideo) {
        QString str_time;
        QTime time = QTime::fromMSecsSinceStartOfDay(_time * 1000);
        if(_time >= 3600)    // hours
            str_time = time.toString("h:mm:ss");
        else if(_time >= 60) // minutes
            str_time = time.toString("mm:ss");
        else
            str_time = time.toString("0:ss");
        ui->slider_time->setTimeTip(str_time);
    }
    else {
        ui->slider_time->setTimeTip("");
        if (m_duration == 0)
            return;
        // 防止一直获取占用过多cpu，但是要保证最后获取的时间正确
        int64_t tmp_time = QDateTime::currentMSecsSinceEpoch();
        if (tmp_time - m_lastPreviewShowTime < 300) {
            return;
        }
        m_lastPreviewShowTime = tmp_time;
        m_previewWidget->setPreview(_time);
    }
}

void ContralBar::slotPlayStateChange(Mpv::PlayState state)
{
    m_state = state;
    switch (m_state) {
    case Mpv::Idle:
        break;
    case Mpv::Started:
        // 如果是无痕浏览的话不能截图和添加书签
        if (gsetup->seamlessBrowsing.first)
            m_toolList->setEnabled(false);
        else
            m_toolList->setEnabled(true);

        break;
    case Mpv::Loaded:
        m_canChangeDuration = true;
        break;
    case Mpv::Playing:
        updateIcon();
        break;
    case Mpv::Paused:
        updateIcon();
        break;
    case Mpv::Stopped:
        m_videoId = -1;
        m_duration = 0;
        ui->slider_time->clearMark();
        ui->label_pos->setText("--:--:--/--:--:--");
        updateIcon();
        break;
    default:
        break;
    }
}
