"""角色/后台客服按俱乐部隔离（权限码全局共用，角色实体按 club 分开）。"""
from django.db.models import Q

from gvsdsdk.models import Role, UserRole

from jituan.constants import CLUB_ID_DEFAULT, DATA_SCOPE_ALL
from jituan.services.club_context import resolve_club_id_from_request, resolve_club_scope


def resolve_role_club_id(request, explicit=None):
    """创建/筛选角色时使用的俱乐部；集团视图可显式指定 target_club_id。"""
    if explicit:
        return (explicit or '').strip()
    scope = resolve_club_scope(request)
    if scope == DATA_SCOPE_ALL:
        return ''
    return resolve_club_id_from_request(request)


def filter_roles_for_request(request):
    """
    子公司视图：仅本俱乐部角色。
    集团汇总视图：全部角色（含各俱乐部 + 全局 club_id 为空）。
    """
    qs = Role.objects.filter(RoleStatus=1)
    scope = resolve_club_scope(request)
    if scope == DATA_SCOPE_ALL:
        return qs
    club_id = resolve_club_id_from_request(request)
    return qs.filter(ClubID=club_id)


def filter_kefu_users_qs(qs, request):
    """后台客服账号列表按俱乐部过滤（User.ClubID）。"""
    scope = resolve_club_scope(request)
    if scope == DATA_SCOPE_ALL:
        return qs
    club_id = resolve_club_id_from_request(request)
    if club_id == CLUB_ID_DEFAULT:
        return qs.filter(Q(ClubID=club_id) | Q(ClubID__isnull=True) | Q(ClubID=''))
    return qs.filter(ClubID=club_id)


def count_role_users_in_scope(role, request, kefu_user_uuids):
    """统计角色下客服数（仅计当前数据范围内的客服）。"""
    from users.business_models import User

    uuids = list(
        UserRole.objects.filter(RoleUUID=role.RoleUUID)
        .values_list('UserUUID', flat=True)
    )
    if not uuids:
        return 0
    qs = User.objects.filter(UserUUID__in=uuids, KefuProfile__isnull=False)
    qs = filter_kefu_users_qs(qs, request)
    if kefu_user_uuids is not None:
        qs = qs.filter(UserUUID__in=kefu_user_uuids)
    return qs.count()


def role_name_exists(role_name, club_id):
    return Role.objects.filter(RoleName=role_name, ClubID=club_id or '').exists()
