from django.forms.models import model_to_dict

from utils.rpc import get_rpc_invoker, logging_exception
from user_hierarchy.models import UserGrowthValue


def sync_user_level(user_growth_ids: list):
    """同步用户等级到 gaia。"""

    if not user_growth_ids or not isinstance(user_growth_ids, list):
        return

    users = UserGrowthValue.objects.filter(pk__in=user_growth_ids).values("user_id", "level")
    if users:
        # users = [model_to_dict(user) for user in users]
        rpc_update_user_level(list(users))


def rpc_update_user_level(users: list):
    """rpc调用修改对应用户的等级。

    users是一个字典列表。
        例如：users = [
            {'user_id': 1212, 'level': 2},
            {'user_id': 5432, 'level': 3},
            {'user_id': 5436, 'level': 3},
        ]
    """

    try:
        r = get_rpc_invoker()
        r['api/user/update_level_list'](users_list=users).unwrap()
    except:
        logging_exception()


