#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
#include <QPainterPath>
#include "accountinformation.h"

AccountInformation::AccountInformation(QWidget *parent) : QWidget(parent)
{
    initMemberVariable();
    registeredAccountsDbus();
    setAllControlsLabelInfo();
    initLayout();
}

void AccountInformation::initMemberVariable()
{
    adminIstrators = QObject::tr("administrators");
    standardUser = QObject::tr("standard users");

    m_pHeadPortraitIconLabel = new IconLabel();
    m_pHeadPortraitIconLabel->setFixedSize(48, 48);
    connect(m_pHeadPortraitIconLabel, &IconLabel::LabelClicked, this, &AccountInformation::openContorlCenterWidgetSlots);

    m_pNameLabel = new QLabel();
    m_pNameLabel->setFixedHeight(30);

    m_pIdentityLabel = new QLabel();
    m_pIdentityLabel->setFixedHeight(24);

    m_pMainLayout = new QHBoxLayout();
    m_pMainLayout->setContentsMargins(32, 0, 0, 0);
    m_pMainLayout->setSpacing(0);

    m_pVLabelLayout = new QVBoxLayout();
    m_pVLabelLayout->setContentsMargins(0, 0, 0, 0);
    m_pVLabelLayout->setSpacing(0);

    m_pInfoWidget = new QWidget();
    m_pInfoWidget->setContentsMargins(0, 0, 0, 0);
    m_pInfoWidget->setFixedHeight(55);

    this->update();
}

void AccountInformation::initLayout()
{
    /* 设置中间俩个label界面 */
    m_pVLabelLayout->addWidget(m_pNameLabel, Qt::AlignVCenter);
    m_pVLabelLayout->addWidget(m_pIdentityLabel, Qt::AlignVCenter);
    m_pVLabelLayout->addItem(new QSpacerItem(1, 5, QSizePolicy::Fixed));
    m_pInfoWidget->setLayout(m_pVLabelLayout);

    m_pMainLayout->addWidget(m_pHeadPortraitIconLabel, Qt::AlignVCenter);
    m_pMainLayout->addItem(new QSpacerItem(8, 5));
    m_pMainLayout->addWidget(m_pInfoWidget);
    this->setLayout(m_pMainLayout);
}

void AccountInformation::registeredAccountsDbus()
{
    m_pSystemUserIface = new QDBusInterface("org.freedesktop.Accounts",
                                            "/org/freedesktop/Accounts",
                                            "org.freedesktop.Accounts",
                                            QDBusConnection::systemBus());
}

QStringList AccountInformation::getUserObjectPath()
{
    QStringList users;
    QDBusReply<QList<QDBusObjectPath> > reply = m_pSystemUserIface->call("ListCachedUsers");
    if (reply.isValid()) {
        for (QDBusObjectPath op : reply.value())
            users << op.path();
    }
    return users;
}

UserInfomation AccountInformation::GetUserInformation(QString objpath)
{
    UserInfomation user;

    //默认值
    user.current = false;
    user.logined = false;
    user.autologin = false;
    QDBusInterface * iproperty = new QDBusInterface("org.freedesktop.Accounts",
                                            objpath,
                                            "org.freedesktop.DBus.Properties",
                                            QDBusConnection::systemBus());

    iproperty->connection().connect("org.freedesktop.Accounts",objpath, "org.freedesktop.DBus.Properties", "PropertiesChanged",
                                    this, SLOT(AccountSlots(QString, QMap<QString, QVariant>, QStringList)));

    QDBusReply<QMap<QString, QVariant> > reply = iproperty->call("GetAll", "org.freedesktop.Accounts.User");
    if (reply.isValid()) {
        QMap<QString, QVariant> propertyMap;
        propertyMap = reply.value();
        user.username = propertyMap.find("UserName").value().toString();
        user.realname = propertyMap.find("RealName").value().toString();
        if (user.username == QString(g_get_user_name())) {
            user.current = true;
            user.logined = true;
        }
        user.accounttype = propertyMap.find("AccountType").value().toInt();
        user.iconfile = propertyMap.find("IconFile").value().toString();
        user.passwdtype = propertyMap.find("PasswordMode").value().toInt();
        user.uid = propertyMap.find("Uid").value().toInt();
        user.autologin = false;
        user.objpath = objpath;
        delete iproperty;
        return user;
    } else
        qDebug() << "reply failed";
}

void AccountInformation::setAllControlsLabelInfo()
{
    QStringList objectpaths = getUserObjectPath();
    UserInfomation user;
    for (QString objectpath : objectpaths){
         user = GetUserInformation(objectpath);
         if(user.current == true && user.logined == true){
             break;
         }
    }
    QFontMetrics fontMetrics1(m_pNameLabel->font());
    QString formatRealName = fontMetrics1.elidedText(user.realname, Qt::ElideRight,115);
    m_pNameLabel->setText(formatRealName);
    if (user.accounttype == ADMINISTRATORS ){
        m_pIdentityLabel->setText(adminIstrators);
    } else if (user.accounttype == STANDARDUSER){
        m_pIdentityLabel->setText(standardUser);
    }
    char * iconpath = user.iconfile.toLatin1().data();
    if (!g_file_test(iconpath, G_FILE_TEST_EXISTS)){
        user.iconfile = DEFAULTFACE;
    }
    m_gsettings = new QGSettings("org.notification.settings");
    connect(m_gsettings, &QGSettings::changed, [=](QString key) {
        if (key == "showflag") {
            QStringList objectpaths = getUserObjectPath();
            UserInfomation user;
            for (QString objectpath : objectpaths){
                 user = GetUserInformation(objectpath);
                 if(user.current == true && user.logined == true){
                     break;
                 }
            }
            char * iconpath = user.iconfile.toLatin1().data();
            if (!g_file_test(iconpath, G_FILE_TEST_EXISTS)){
                user.iconfile = DEFAULTFACE;
            }
            QPixmap facePixmap= pixmapAdjustLabel(user.iconfile);
            m_pHeadPortraitIconLabel->setFixedSize(48, 48);
            m_pHeadPortraitIconLabel->setPixmap(PixmapToRound(facePixmap, m_pHeadPortraitIconLabel->width()/2));

        }
    });

    QPixmap facePixmap= pixmapAdjustLabel(user.iconfile);
    m_pHeadPortraitIconLabel->setFixedSize(48, 48);
    m_pHeadPortraitIconLabel->setPixmap(PixmapToRound(facePixmap, m_pHeadPortraitIconLabel->width()/2));
}

QPixmap AccountInformation::pixmapAdjustLabel(QString iconfile)
{
    //设置用户头像
    QPixmap iconcop = QPixmap(iconfile);
    if (iconcop.width() > iconcop.height()) {
        QPixmap iconPixmap = iconcop.copy((iconcop.width() - iconcop.height())/2, 0, iconcop.height(), iconcop.height());
        // 根据label高度等比例缩放图片
        QPixmap rectPixmap = iconPixmap.scaledToHeight(m_pHeadPortraitIconLabel->height());
        return rectPixmap;
    } else {
        QPixmap iconPixmap = iconcop.copy(0, (iconcop.height() - iconcop.width())/2, iconcop.width(), iconcop.width());
        // 根据label宽度等比例缩放图片
        QPixmap rectPixmap = iconPixmap.scaledToWidth(m_pHeadPortraitIconLabel->width());
        return rectPixmap;
    }
}

void AccountInformation::openContorlCenterWidgetSlots()
{
    QString path=QDir::homePath()+"/.cache/ukui-menu/ukui-menu.ini";
    QSettings *setting=new QSettings(path,QSettings::IniFormat);
    setting->beginGroup("application");
    bool bo=setting->contains("ukui-control-center");
    setting->sync();
    setting->endGroup();
    if (bo) {
        return;
    }

    QStringList args;
    args.append("-m");
    args.append("Userinfo");
    if(!AppManagerDbus::getInstance()->LaunchAppWithArguments("ukui-control-center",args)) {
        qWarning()<<"AppManagerDbus 接口无效，采用QProcess启动";
        QProcess p(0);
        p.startDetached("ukui-control-center -m Userinfo");
        p.waitForStarted();
    }
    return;
}

QPixmap AccountInformation::PixmapToRound(const QPixmap &src, int radius)
{
    if (src.isNull()) {
        return QPixmap();
    }

    QPixmap pixmapa(src);
    QPixmap pixmap(radius*2,radius*2);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
    QPainterPath path;
    path.addEllipse(0, 0, radius*2, radius*2);
    painter.setClipPath(path);
    painter.drawPixmap(0, 0, radius*2, radius*2, pixmapa);
    return pixmap;
}

void AccountInformation::AccountSlots(QString property, QMap<QString, QVariant> propertyMap, QStringList propertyList)
{
    Q_UNUSED(property);
    Q_UNUSED(propertyList);
    if (propertyMap.keys().contains("IconFile")) {
        QPixmap facePixmap= pixmapAdjustLabel(propertyMap.value("IconFile").toString());
        m_pHeadPortraitIconLabel->setFixedSize(48, 48);
        m_pHeadPortraitIconLabel->setPixmap(PixmapToRound(facePixmap, m_pHeadPortraitIconLabel->width()/2));
    }
    if (propertyMap.keys().contains("RealName")) {

        QFontMetrics fontMetrics1(m_pNameLabel->font());
        QString newname = propertyMap.value("RealName").toString();
        QString formatRealName = fontMetrics1.elidedText(newname, Qt::ElideRight, m_pNameLabel->width());
        m_pNameLabel->setText(formatRealName);
    }
    if (propertyMap.keys().contains("AccountType")){
        if (propertyMap.value("AccountType").toInt() == STANDARDUSER){
            //普通用户
            m_pIdentityLabel->setText(standardUser);
        } else if (propertyMap.value("AccountType").toInt() == ADMINISTRATORS){
            //管理员用户
            m_pIdentityLabel->setText(adminIstrators);
        }
    }
}

ShutDownWidget::ShutDownWidget(QWidget *parent) : QWidget(parent){
    QString arg = KDKGetPrjCodeName().c_str();
    m_pMainLayout = new QHBoxLayout(this);
    m_pMainLayout->setContentsMargins(88, 0, 20, 0);
    m_pShutDownButton = new QPushButton();
    m_pMainLayout->addWidget(m_pShutDownButton);

    m_pShutDownButton->setFixedSize(48, 48);
    m_pShutDownButton->setIcon(QIcon::fromTheme(KYLIN_POWER_NORMAL_NAME, QIcon(KYLIN_POWER_NORMAL_PATH_MAJOR)));
    m_pShutDownButton->setIconSize(QSize(26,26));
    connect(m_pShutDownButton, &QPushButton::clicked, this, &ShutDownWidget::openShutdownWidgetSlots);
    m_pShutDownButton->setFlat(true);
}

void ShutDownWidget::openShutdownWidgetSlots()
{
    if(!AppManagerDbus::getInstance()->LaunchApp("ukui-session-tools.desktop")) {
        qWarning()<<"AppManagerDbus 接口无效，采用QProcess启动";
        QProcess p(0);
        p.startDetached("ukui-session-tools");
        p.waitForStarted();
    }
}

IconLabel::IconLabel(QWidget *parent) : QLabel(parent)
{

}

void IconLabel::mouseReleaseEvent(QMouseEvent *ev)
{
    Q_UNUSED(ev);
    emit LabelClicked();
}


