#include "userlistwidget.h"
#include <QScrollBar>
#include "useritemwidget.h"

UserListWidget::UserListWidget(LockDialogModel *model, QWidget *parent)
    : MyListWidget(parent)
    , m_modelLockDialog(model)
{
    initUI();
    initConnections();
    setUserListWidget(true);
}

void UserListWidget::initUI()
{
    QString userListStyle = "QListWidget{ background-color: rgb(255,255,255,15%); border-radius: 8px; padding: 5px 5px 5px 5px;}"
            "QListWidget::item{background:rgb(255,255,255,0%);height:40px; border-radius:4px}"
            "QListWidget::item:hover{color:#333333; background-color:rgb(255,255,255,20%)}"
            "QListWidget::item::selected{border-radius: 4px;background-color:rgb(255,255,255,40%);}";
    setStyleSheet(userListStyle);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    verticalScrollBar()->setProperty("drawScrollBarGroove", false);

    onUpdateListInfo();
}

void UserListWidget::initConnections()
{
    //  响应点击事件
    connect(this, &UserListWidget::itemClicked, this, &UserListWidget::onListItemClicked);

    connect(m_modelLockDialog, &LockDialogModel::usersInfoChanged, this, &UserListWidget::onUpdateListInfo);
}

void UserListWidget::onUpdateListInfo()
{
    this->clear();
    for (auto user : m_modelLockDialog->usersInfo()) {
        QListWidgetItem *userItem = new QListWidgetItem();
        userItem->setSizeHint(QSize(420, 40));
        insertItem(count(), userItem);
        UserItemWidget *itemWidget = new UserItemWidget(this);
        QPixmap p(user->headImage());
        itemWidget->setUserPixmap(p);
        itemWidget->setUserNickName(user->fullName());
        itemWidget->setUserStatus(user->isLoggedIn());
        if (user->fullName() == m_modelLockDialog->currentUserName()) {
            setCurrentItem(userItem, QItemSelectionModel::SelectionFlag::SelectCurrent);
        }
        itemWidget->setUserName(user->name());
        setItemWidget(userItem, itemWidget);
    }
    updateWidgetSize();
}

void UserListWidget::onListItemClicked(QListWidgetItem *item)
{
    QWidget *widget = itemWidget(item);
    UserItemWidget *currentItem = qobject_cast<UserItemWidget *>(widget);
    if (currentItem) {
        Q_EMIT userSelected(currentItem->getUserName());
    }
}

void UserListWidget::updateWidgetSize()
{
    setFixedWidth(420);
    if (maxHeight() >= 0 && (count() * 40 + 10) > maxHeight()) {
        setFixedHeight(maxHeight());
    } else {
        setFixedHeight(count() * 40 + 10);
    }
    adjustSize();
}
