"""集团级资金处置权限：提现审核、加余额等。俱乐部 000001 超级管理不能绕过。"""
from django.db.models import Q

from jituan.constants import DATA_SCOPE_ALL
from jituan.models import AdminAssignment
from jituan.services.admin_context import GROUP_MANAGE_ROLES, build_admin_club_context, is_system_super_admin

MSG_GROUP_FINANCE_REQUIRED = '该操作仅集团高管可执行（需在数据范围配置中为集团级任职）'


def has_group_finance_exec(user, request=None):
    """系统超管 / 集团任职（GROUP_OWNER、GROUP_SUPER_ADMIN）。"""
    if is_system_super_admin(user):
        return True
    ctx = build_admin_club_context(user)
    if ctx.get('is_group_admin') and ctx.get('role_code') in GROUP_MANAGE_ROLES:
        return True
    uid = getattr(user, 'UserUID', None)
    if not uid:
        return False
    return AdminAssignment.query.filter(
        yonghuid=uid,
        status=1,
        role_code__in=GROUP_MANAGE_ROLES,
    ).filter(
        Q(club_id__isnull=True) | Q(data_scope=DATA_SCOPE_ALL),
    ).exists()


def deny_group_finance_exec(user, request=None):
    from rest_framework.response import Response
    if has_group_finance_exec(user, request):
        return None
    return Response({'code': 403, 'msg': MSG_GROUP_FINANCE_REQUIRED})


def require_withdraw_audit_access(request, phone):
    """提现审核：须 005bb 且集团资金处置权。"""
    from backend.utils import verify_kefu_permission
    from rest_framework.response import Response

    kefu, permissions = verify_kefu_permission(request, phone)
    if kefu is None:
        return None, permissions
    if '005bb' not in permissions:
        return None, Response({'code': 403, 'msg': '您无权操作提现审核'})
    deny = deny_group_finance_exec(request.user, request)
    if deny:
        return None, deny
    return kefu, None
