/*
* Copyright (C) 2020 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, 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 <http://www.gnu.org/licenses/&gt;.
*
*/
#include "shortcutpanelplugin.h"

extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);

shortcutPanelPlugin::shortcutPanelPlugin(QObject *parent)
{
    Q_UNUSED(parent);
    initTranslations();    //初始化翻译文件
    initDbusService();     //初始化dbus

    setScrollWidget();               //获取当前系统是否有背光文件
    initMemberVariablesMajor();      //初始化3.1插件成员变量
    initAnimation();                 //初始化动画
    initShortButtonWidgetMajor();    //初始化快捷按钮界面
    initsetShortWidget();            //布局快捷按钮界面
    setWidgetMajor();                //3.1将切换按钮和ListView界面set进插件主界面
}

void shortcutPanelPlugin::initTranslations()
{
    QTranslator *translator = new QTranslator;
    if (translator->load(QLocale(), QLatin1String("ukui-quick-operation-panel"), QLatin1String("_"), QLatin1String("/usr/share/ukui-sidebar/ukui-quick-operation-panel")))
        QApplication::installTranslator(translator);
    else
        qDebug() << "cannot load translator ukui-quick-operation-panel_" << QLocale::system().name() << ".qm!";
}

void shortcutPanelPlugin::initDbusService()
{
    //快捷操作面板dbus
    m_QuickOperationDbus = new QuickOperationDbus();
    //设置动画速度
    m_QuickOperationDbus->setAnimationSpeed(ANIMATIONSPEED);
}

//初始化动画
void shortcutPanelPlugin::initAnimation()
{
    m_pAnimationShowSidebarWidget = new QPropertyAnimation(m_pMainWidget, "geometry");
    m_pAnimationHideSidebarWidget = new QPropertyAnimation(m_pMainWidget, "geometry");

    connect(m_pAnimationShowSidebarWidget, &QPropertyAnimation::finished, this, &shortcutPanelPlugin::foldClikedSlots);
    connect(m_pAnimationHideSidebarWidget, &QPropertyAnimation::stateChanged, this, &shortcutPanelPlugin::spreadClikedSlots);
}

//隐藏动画
void shortcutPanelPlugin::hideAnimation()
{
    m_pAnimationShowSidebarWidget->setStartValue(QRect(0, SidebarCoreDbus::getInstance()->getSidebarHeight() - MAJOR_QUICK_PANEL_HEIGHT + SIDEBAR_AND_PANEL_DISTANCE + m_pChangeSize, \
                                                       MAJOR_QUICK_PANEL_WIDTH, MAJOR_QUICK_PANEL_HEIGHT));

    m_pAnimationShowSidebarWidget->setEndValue(QRect(0, SidebarCoreDbus::getInstance()->getSidebarHeight() - (MAJOR_QUICK_PANEL_HEIGHT - MAJOR_QUICK_PANEL_CHANGE_HEIGHT), \
                                                     MAJOR_QUICK_PANEL_WIDTH, MAJOR_QUICK_PANEL_HEIGHT));

    m_pAnimationShowSidebarWidget->setDuration(ANIMATIONSPEED);
    m_pAnimationShowSidebarWidget->start();
    return;
}

//展开动画
void shortcutPanelPlugin::showAnimation()
{
    m_pAnimationHideSidebarWidget->setStartValue(QRect(0,SidebarCoreDbus::getInstance()->getSidebarHeight() - (MAJOR_QUICK_PANEL_HEIGHT - MAJOR_QUICK_PANEL_CHANGE_HEIGHT), \
                                                       MAJOR_QUICK_PANEL_WIDTH, MAJOR_QUICK_PANEL_HEIGHT));

    m_pAnimationHideSidebarWidget->setEndValue(QRect(0, SidebarCoreDbus::getInstance()->getSidebarHeight() - MAJOR_QUICK_PANEL_HEIGHT + SIDEBAR_AND_PANEL_DISTANCE + m_pChangeSize, \
                                                     MAJOR_QUICK_PANEL_WIDTH, MAJOR_QUICK_PANEL_HEIGHT));

    m_pAnimationHideSidebarWidget->setDuration(ANIMATIONSPEED);
    m_pAnimationHideSidebarWidget->start();
    return;
}

// 布局快捷按钮界面
void shortcutPanelPlugin::initsetShortWidget()
{
    int tmpx = 0, tmpy = 0;
    for (int j = 0; j < 2; j++) {
        for (int  k = 0; k < 4; k++) {
            m_pShortGLayout->addWidget(ShortButtonWidgetList.at(4 * j + k), tmpx, tmpy, 1, 1);
            tmpy++;
            if (tmpy == 4) {
                tmpy = 0;
                tmpx++;
            }
        }
    }
    return;
}

/* 获取快捷操作面板界面 */
QWidget* shortcutPanelPlugin::getShortCutPanelWidget()
{
    if (m_pMainWidget == nullptr) {
        return nullptr;
    }
    return m_pMainWidget;
}

/* 获取接口代号 */
InterfaceEnum shortcutPanelPlugin::getInterfaceMark(QString key)
{

    if ("" == key) {
        qDebug() << "获取接口代号失败， 传入参数有误";
        return InterfaceEnum::Else;
    }
    if (m_InterfaceHash.contains(key)) {
        return m_InterfaceHash.value(key);
    } else
        return InterfaceEnum::Else;
}

/* 移除Hash中接口 */
void shortcutPanelPlugin::removeInterfaceMark(QString key)
{
    if ("" == key) {
        qDebug() << "移除Hash中接口失败， 传入参数有误";
        return;
    }
    if (m_InterfaceHash.contains(key))
        m_InterfaceHash.remove(key);
    return;
}

/* 插入接口和代号往Hash表中 */
void shortcutPanelPlugin::insertInterfaceMark(QString key, InterfaceEnum value)
{
    if ("" == key || value < 0) {
        qDebug() << "插入数据失败， 传入参数有误";
        return;
    }
    if (m_InterfaceHash.contains(key)) {
        qDebug() << "此Key值已存在";
        return;
    }
    m_InterfaceHash.insert(key, value);
    return;
}

/* 展开按钮槽函数 */
void shortcutPanelPlugin::spreadClikedSlots()
{
    setGridLayoutWidgetShow();
    m_pWeatherWidget->setVisible(true);
    m_pShortWidget->setFixedHeight(227);
    m_pScrollingAreaWidgetMajor->setVisible(true);
    if (m_bBacklitFile) {
        m_pMainWidget->setFixedHeight(MAJOR_QUICK_PANEL_HEIGHT);
    } else {
        m_pMainWidget->setFixedHeight(MAJOR_QUICK_PANEL_HEIGHT - 40);
    }
    m_PartLine2->setVisible(true);
    m_PartLine3->setVisible(true);
    m_pMainWidget->update();
    return;
}

/* 折叠按钮槽函数 */
void shortcutPanelPlugin::foldClikedSlots()
{
    setGridLayoutWidgetHide();
    m_pShortWidget->setFixedHeight(107);
    m_pMainWidget->setFixedHeight(MAJOR_QUICK_PANEL_HEIGHT - MAJOR_QUICK_PANEL_CHANGE_HEIGHT);
    m_pScrollingAreaWidgetMajor->setVisible(false);
    m_pWeatherWidget->setVisible(false);
    m_PartLine2->setVisible(false);
    m_PartLine3->setVisible(false);
    m_pMainWidget->update();
    return;
}

void shortcutPanelPlugin::setGridLayoutWidgetHide()
{
    for (int i = 1; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            if (m_pShortGLayout->itemAtPosition(i, j) == nullptr) {
                return;
            } else {
                m_pShortGLayout->itemAtPosition(i, j)->widget()->setVisible(false);
            }
        }
    }
}

void shortcutPanelPlugin::setGridLayoutWidgetShow()
{
    for (int i = 1; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            if (m_pShortGLayout->itemAtPosition(i, j) == nullptr) {
                return;
            } else {
                m_pShortGLayout->itemAtPosition(i, j)->widget()->setVisible(true);
            }
        }
    }
}


//**************************3.1特性函数

/* 获取系统内核是否包含有背光文件，是否支持调整亮度 */
void shortcutPanelPlugin::setScrollWidget()
{
    QProcess process;
    process.start("ukui-power-backlight-helper --get-max-brightness");
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString str_output = output;
    if (str_output == "没有找到您系统上的背光\n") {
        m_bBacklitFile = false;
//             m_bBacklitFile = true; //调试
    } else {
        m_bBacklitFile = true;
    }
    qDebug() << "是否含有背光文件---->" << str_output;
    return;
}

// 初始化3.1插件成员变量
void shortcutPanelPlugin::initMemberVariablesMajor()
{
    m_pMainVLayout = new QVBoxLayout;
    m_pMainVLayout->setContentsMargins(0, 0, 0, 0);
    m_pMainVLayout->setSpacing(0);

    m_pShortGLayout  = new QGridLayout;
    m_pShortGLayout->setContentsMargins(30, 16, 16, 16);
    m_pShortGLayout->setHorizontalSpacing(35);
    m_pShortGLayout->setVerticalSpacing(16);

    m_userAndPowerHLayout = new QHBoxLayout;        // 用户名、折叠按钮、关机按钮的水平布局
    m_userAndPowerHLayout->setContentsMargins(0, 0, 0, 0);
    m_userAndPowerHLayout->setSpacing(0);

    m_foldAndSpreadVLayout = new QVBoxLayout;       // 折叠按钮的垂直布局，下面加弹簧
    m_foldAndSpreadVLayout->setContentsMargins(0, 0, 0, 0);

    m_pMainWidget  = new MainWidget;
    m_pMainWidget->setContentsMargins(0, 0, 0, 0);

    //检测是否有背光文件，设置差异大小
    if (m_bBacklitFile) {
        m_pChangeSize = 0;
    } else {
        m_pChangeSize = 40;
    }
    m_pMainWidget->setFixedSize(MAJOR_QUICK_PANEL_WIDTH, MAJOR_QUICK_PANEL_HEIGHT - m_pChangeSize);

    /* 分割线 */
    m_PartLine1 =new PartLineWidget;
    m_PartLine1->setFixedSize(392, 1);
    m_PartLine1->setContentsMargins(0, 0, 0, 0);

    m_PartLine2 =new PartLineWidget;
    m_PartLine2->setFixedSize(392, 1);
    m_PartLine2->setContentsMargins(0, 0, 0, 0);

    m_PartLine3 =new PartLineWidget;
    m_PartLine3->setFixedSize(392, 1);
    m_PartLine3->setContentsMargins(0, 0, 0, 0);

    m_pSpreadOrFoldButton  = new StateSpreadOrFoldWidget();
    connect(m_pSpreadOrFoldButton, &StateSpreadOrFoldWidget::LabelClicked,[=](bool isFoldState){
        if(isFoldState) {
            //隐藏动画效果
            emit m_QuickOperationDbus->Sig_QuickOperation("HIDE");
            hideAnimation();
        } else {
            //展开动画效果
            emit m_QuickOperationDbus->Sig_QuickOperation("SHOW");
            showAnimation();
        }
    });

    /* 账户信息界面 */
    m_PAccountInfoWidget    = new AccountInformation();
    m_PAccountInfoWidget->setFixedSize(300, 55);


    /* 关机按钮界面 */
    m_shutDownButton = new ShutDownWidget();

    /* 快捷操作面板界面 */
    m_pShortWidget   = new QWidget;
    m_pShortWidget->setFixedHeight(227);
    m_pShortWidget->setContentsMargins(0, 0, 0, 0);

    m_pScrollingAreaWidgetMajor = new ScrollingAreaWidgetMajor();
    /* 当系统有背光文件时，调整音量与屏幕亮度界面 */
    if (m_bBacklitFile) {
        m_pScrollingAreaWidgetMajor->setFixedSize(392,80);
    } else {
        m_pScrollingAreaWidgetMajor->setFixedSize(392,50);
    }

    /* 显示天气界面 */
    m_pWeatherWidget = new weatherWidget();
    m_pWeatherWidget->setFixedSize(392, 20);
    m_pWeatherWidget->setContentsMargins(0, 0, 0, 0);
//    m_pMainWidget->setStyleSheet("QWidget{border:1px solid rgba(255,0,0,1);}");//测试用，画出边界线

    //将位置信息载入dbus
    m_QuickOperationDbus->setQuickOperationPanelWidth(MAJOR_QUICK_PANEL_WIDTH);
    m_QuickOperationDbus->setQuickOperationPanelHeight(MAJOR_QUICK_PANEL_HEIGHT - m_pChangeSize);
    m_QuickOperationDbus->setQuickOperationPanelHideHeight(MAJOR_QUICK_PANEL_HEIGHT - MAJOR_QUICK_PANEL_CHANGE_HEIGHT);
    return;
}

// 初始化3.1快捷按钮界面
void shortcutPanelPlugin::initShortButtonWidgetMajor()
{
    ShortButtonWidgetList.clear();

    QStringList buttonName;
    buttonName << POWERSAVING_NAME
               << BLUETOOTH_NAME
               << FLIGHTMODE_NAME
               << PAD_NAME
               << PROJECTSCREEN_NAME
               << EYE_PROTECTION_NAME
               << SCREENSHOT_NAME
               << SETTING_NAME;

    for(int i = 0; i < 8; i++) {
        templatewidget *m_ptemplatewidget = new templatewidget(buttonName.at(i));
        ShortButtonWidgetList.append(m_ptemplatewidget);
    }
}


void shortcutPanelPlugin::setWidgetMajor()
{
    //收纳按钮的布局
    m_foldAndSpreadVLayout->addWidget(m_pSpreadOrFoldButton);
    m_foldAndSpreadVLayout->addStretch();

    //横向用户信息、收纳按钮、关机按钮布局
    m_userAndPowerHLayout->addWidget(m_PAccountInfoWidget);
    m_userAndPowerHLayout->addLayout(m_foldAndSpreadVLayout);
    m_userAndPowerHLayout->addWidget(m_shutDownButton);

    //栅格布局加入widget
    m_pShortWidget->setLayout(m_pShortGLayout);

    m_pMainVLayout->addLayout(m_userAndPowerHLayout);        //横向用户信息、收纳按钮、关机按钮
    m_pMainVLayout->addWidget(m_PartLine1);
    m_pMainVLayout->addWidget(m_pShortWidget);               //快捷按钮
    m_pMainVLayout->addWidget(m_PartLine2);
    m_pMainVLayout->addWidget(m_pScrollingAreaWidgetMajor);  // 滚动条区域
    m_pMainVLayout->addItem(new QSpacerItem(50, 8, QSizePolicy::Expanding));
    m_pMainVLayout->addWidget(m_PartLine3);
    m_pMainVLayout->addItem(new QSpacerItem(50, 8, QSizePolicy::Expanding));
    m_pMainVLayout->addWidget(m_pWeatherWidget);             // 天气界面
    m_pMainVLayout->addItem(new QSpacerItem(50, 8, QSizePolicy::Expanding));
    m_pMainWidget->setLayout(m_pMainVLayout);

    return;
}

StateSpreadOrFoldWidget::StateSpreadOrFoldWidget(QWidget *parent) : QWidget(parent),
    isFoldState(false)
{
    m_pPictureToWhite = new PictureToWhite();
    setFixedSize(80, 40);
    button = new QLabel();
    m_hlayout = new QHBoxLayout(this);
    m_hlayout->setContentsMargins(28, 8, 28, 8);
    m_hlayout->addWidget(button);

    button->setFixedSize(48, 24);
    QPixmap myPix(KYLIN_TOP_CLOSE_NORMAL_MAJOR_PATH);
    myPix = m_pPictureToWhite->drawSymbolicColoredPixmap(myPix);
    button->setPixmap(myPix);

    const QByteArray id("org.ukui.style");
    if (QGSettings::isSchemaInstalled(id)) {
        QGSettings * gsettingchange = new QGSettings(id);
        connect(gsettingchange, &QGSettings::changed,[=](QString key){
            if(isFoldState){
                QPixmap myPix(KYLIN_TOP_OPEN_NORMAL_MAJOR_PATH);
                myPix = m_pPictureToWhite->drawSymbolicColoredPixmap(myPix);
                button->setPixmap(myPix);
            } else {
                QPixmap myPix(KYLIN_TOP_CLOSE_NORMAL_MAJOR_PATH);
                myPix = m_pPictureToWhite->drawSymbolicColoredPixmap(myPix);
                button->setPixmap(myPix);
            }
        });
    }
}

StateSpreadOrFoldWidget::~StateSpreadOrFoldWidget(){

}

void StateSpreadOrFoldWidget::mouseReleaseEvent(QMouseEvent *ev)
{
    Q_UNUSED(ev);
    isFoldState = !isFoldState;
    if (isFoldState) {
        QPixmap myPix(KYLIN_TOP_OPEN_NORMAL_MAJOR_PATH);
        myPix = m_pPictureToWhite->drawSymbolicColoredPixmap(myPix);
        button->setPixmap(myPix);
    } else {
        QPixmap myPix(KYLIN_TOP_CLOSE_NORMAL_MAJOR_PATH);
        myPix = m_pPictureToWhite->drawSymbolicColoredPixmap(myPix);
        button->setPixmap(myPix);
    }
    emit LabelClicked(isFoldState);
}

PartLineWidget::PartLineWidget(QWidget *parent) : QWidget(parent)
{
    initStyle();

}

void PartLineWidget::initStyle()
{
    if (QGSettings::isSchemaInstalled(THEME_QT_SCHEMA)) {
        m_pStyleGsetting = new QGSettings(THEME_QT_SCHEMA);
        m_pStyleName =  m_pStyleGsetting->get(MODE_QT_KEY).toString();
        connect(m_pStyleGsetting, &QGSettings::changed, [=](QString key) {
            m_pStyleName =  m_pStyleGsetting->get(MODE_QT_KEY).toString();
            this->update();
        });
    }
}

void PartLineWidget::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    QRect rect = this->rect();
    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    QColor color=qApp->palette().color(QPalette::Base);

    if (m_pStyleName == "ukui-dark") {
        color.setRgb(255,255,255,255);
    } else {
        color.setRgb(1,1,1,255);
    }

    p.setBrush(color);
    p.setOpacity(0.05);
    p.setPen(Qt::NoPen);
    p.drawRoundedRect(rect,0,0);

    QWidget::paintEvent(event);
}

MainWidget::MainWidget()
{
   getTransParency();
}

void MainWidget::getTransParency()
{
    m_dtranSparency = ControlCenterPersonGsetting::getInstance()->getTransparency();
    connect(ControlCenterPersonGsetting::getInstance(),&ControlCenterPersonGsetting::Sig_personChanged,
            this,[=](QString key) {
        if (key == CONTROL_CENTER_PERSONALISE_TRANS_KEY) {
            m_dtranSparency = ControlCenterPersonGsetting::getInstance()->getTransparency();
            setTransParency();
        }
    });
}

/* 设置当前匹配的透明度值
  设计要求，快速操作面板比通知中心透明度高0.3；
  思路如下:
  由于窗口透明度叠加，所以只能通过算比例;
  相当于100束光照进来，透明度为0.3，则剩下的光就是70束；
  在透过第二层为0.6的玻璃时，光束就只剩下28束，但是我们想要的是没有通过第一层过滤的，直接得到40束，表达式如下：
  100*(1 - 通知中心透明度) * X(所求的比例) = 100 * (1 - (通知中心透明度 + 0.3));
  当比例大于0.7小于0.9时，俩个透明度的比例差为0.1；
  当大于0.9.就直接将透明度设置为1，俩层叠加，视觉效果较明显
 */
void MainWidget::setTransParency()
{
    if (m_dtranSparency >= 0.7 && m_dtranSparency < 0.9) {
        m_dtranSparency = (1 - (m_dtranSparency + 0.1)) / (1.0 - m_dtranSparency);
    } else if (m_dtranSparency < 0.7) {
        m_dtranSparency = (1 - (m_dtranSparency + 0.3)) / (1.0 - m_dtranSparency);
    } else {
        m_dtranSparency = 1;
    }
    return;
}

//重新绘制背景色
void MainWidget::paintEvent(QPaintEvent *event)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);
    QPainterPath rectPath;
    rectPath.addRoundedRect(this->rect().adjusted(0, 0, 0, 0), 12, 12);

    QPixmap pixmap(this->rect().size());
    pixmap.fill(Qt::transparent);
    QPainter pixmapPainter(&pixmap);
    pixmapPainter.setRenderHint(QPainter::Antialiasing);
    pixmapPainter.setPen(Qt::transparent);
    pixmapPainter.setBrush(Qt::black);
    pixmapPainter.drawPath(rectPath);
    pixmapPainter.end();

    QImage img = pixmap.toImage();
    qt_blurImage(img, 2, false, false);

    pixmap = QPixmap::fromImage(img);
    QPainter pixmapPainter2(&pixmap);
    pixmapPainter2.setRenderHint(QPainter::Antialiasing);
    pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear);
    pixmapPainter2.setPen(Qt::transparent);
    pixmapPainter2.setBrush(Qt::transparent);
    pixmapPainter2.drawPath(rectPath);
    p.setOpacity(1);
    p.drawPixmap(this->rect(), pixmap, pixmap.rect());
    p.save();
    p.fillPath(rectPath, qApp->palette().color(QPalette::Base));
    p.restore();
    QWidget::paintEvent(event);
}
