"""集团级资金处置权限：加余额等仍仅集团高管。

提现审核：权限码 005bb + 按俱乐部隔离——
- 子公司视图：持有 005bb 且任职含当前俱乐部 → 可审本俱乐部（同意/拒绝/自动打款）
- 集团汇总视图 / 跨俱乐部：须集团资金处置权（GROUP_OWNER / GROUP_SUPER_ADMIN）
俱乐部本地 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,
    get_allowed_club_ids,
    is_system_super_admin,
)

MSG_GROUP_FINANCE_REQUIRED = '该操作仅集团高管可执行（需在数据范围配置中为集团级任职）'
MSG_WITHDRAW_CROSS_CLUB = '跨俱乐部提现审核仅集团高管可执行，请切换到具体俱乐部后再操作'
MSG_WITHDRAW_CLUB_DENIED = '无权审核该俱乐部提现'


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):
    """
    提现审核访问：
    1) 须权限码 005bb
    2) 集团高管：可在 ALL_CLUBS 或任意子公司视图操作
    3) 俱乐部管理员：仅 SINGLE_CLUB 且当前 club 在其任职范围内
    """
    from backend.utils import verify_kefu_permission
    from rest_framework.response import Response
    from jituan.services.club_context import resolve_club_id_from_request, resolve_club_scope

    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': '您无权操作提现审核'})

    if has_group_finance_exec(request.user, request):
        return kefu, None

    scope = resolve_club_scope(request)
    if scope == DATA_SCOPE_ALL:
        return None, Response({'code': 403, 'msg': MSG_WITHDRAW_CROSS_CLUB})

    club_id = resolve_club_id_from_request(request)
    allowed = get_allowed_club_ids(request.user)
    if not club_id or club_id not in allowed:
        return None, Response({'code': 403, 'msg': MSG_WITHDRAW_CLUB_DENIED})

    return kefu, None
