"""提现流水按俱乐部隔离。"""
from rest_framework.response import Response

from jituan.constants import DATA_SCOPE_ALL
from jituan.services.club_context import filter_queryset_by_club, resolve_club_id_from_request, resolve_club_scope
from jituan.services.club_user import get_user_club_id
from jituan.services.wechat_pay import club_id_for_tixian_yonghuid


def club_id_for_tixian_user(user):
    return get_user_club_id(user)


def club_id_for_tixian_yonghuid_safe(yonghuid):
    return club_id_for_tixian_yonghuid(yonghuid)


def resolve_payout_club_id(*, audit=None, jilu=None, yonghuid=None, user=None):
    """
    打款商户归属俱乐部：优先提现单/审核单上的 club_id，再回落用户归属。
    避免用户迁店后用新俱乐部商户号打旧单资金。
    """
    for obj in (audit, jilu):
        if obj is None:
            continue
        cid = (getattr(obj, 'club_id', None) or '').strip()
        if cid:
            return cid
    if user is not None:
        return get_user_club_id(user) or ''
    if yonghuid:
        return club_id_for_tixian_yonghuid(yonghuid) or ''
    return ''


def filter_tixianjilu_by_request(qs, request):
    return filter_queryset_by_club(qs, request, club_field='club_id')


def forbid_if_tixian_out_of_scope(request, tixian_record):
    """提现记录不在当前俱乐部范围时返回 Response。"""
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        from jituan.services.group_finance_gate import has_group_finance_exec
        if not has_group_finance_exec(request.user, request):
            return Response({
                'code': 403,
                'msg': '跨俱乐部提现操作仅集团高管可执行，请切换到具体俱乐部',
            })
        return None
    club_id = resolve_club_id_from_request(request)
    rec_club = getattr(tixian_record, 'club_id', None) or club_id_for_tixian_yonghuid_safe(
        tixian_record.yonghuid,
    )
    if rec_club != club_id:
        return Response({'code': 403, 'msg': '该提现记录不属于当前俱乐部数据范围'})
    return None
