"""罚单 / 管事分红俱乐部隔离与写入。"""
from rest_framework.response import Response

from jituan.constants import CLUB_ID_DEFAULT
from jituan.services.club_context import (
    DATA_SCOPE_ALL,
    resolve_club_id_from_request,
    resolve_club_scope,
)
from jituan.services.club_user import get_user_club_id


def _club_id_from_user_uid(uid):
    if not uid:
        return None
    from users.business_models import User
    u = User.query.filter(UserUID=str(uid)).first()
    if u:
        return get_user_club_id(u)
    return None


def penalty_cz_club_id(fadan):
    """罚款支付 czjilu.club_id：与罚单归属一致（申请人俱乐部）。"""
    cid = (getattr(fadan, 'ClubID', None) or '').strip()
    return cid or CLUB_ID_DEFAULT


def resolve_penalty_club_id(
    order=None,
    penalized_user_id=None,
    request=None,
    applicant_id=None,
    user=None,
):
    """
    创建金额罚单时写入 club_id。
    只认申请人/操作人俱乐部，不看订单、不看被罚人（交款打手）。
    """
    cid = _club_id_from_user_uid(applicant_id)
    if cid:
        return cid

    if request is not None or user is not None:
        from jituan.services.club_write import resolve_club_id_for_write
        u = user or getattr(request, 'user', None)
        cid = resolve_club_id_for_write(request, u)
        if cid:
            return cid

    return CLUB_ID_DEFAULT


def resolve_penalty_record_club_id(
    order_id=None,
    player_id=None,
    request=None,
    applicant_id=None,
    user=None,
):
    """
    创建积分处罚（chufajilu）时写入 club_id。
    只认申请人/操作人俱乐部，不看订单、不看被罚打手。
    """
    cid = _club_id_from_user_uid(applicant_id)
    if cid:
        return cid

    if request is not None or user is not None:
        from jituan.services.club_write import resolve_club_id_for_write
        u = user or getattr(request, 'user', None)
        cid = resolve_club_id_for_write(request, u)
        if cid:
            return cid

    return CLUB_ID_DEFAULT


def resolve_gsfenhong_club_id(dingdan_id=None, dashouid=None, order=None, czjilu=None):
    """管事分红写入 club_id。"""
    if czjilu is not None and getattr(czjilu, 'club_id', None):
        return czjilu.club_id
    if order is not None:
        cid = getattr(order, 'ClubID', None) or getattr(order, 'club_id', None)
        if cid:
            return cid
    if dingdan_id:
        from products.models import Czjilu
        cz = Czjilu.query.filter(dingdan_id=dingdan_id).first()
        if cz and cz.club_id:
            return cz.club_id
        from orders.models import Order
        o = Order.query.filter(OrderID=dingdan_id).first()
        if o and getattr(o, 'ClubID', None):
            return o.ClubID
    if dashouid:
        cid = _club_id_from_user_uid(dashouid)
        if cid:
            return cid
    return CLUB_ID_DEFAULT


def _filter_by_penalty_club_id(qs, request):
    """
    罚单/积分处罚列表：只按记录自身 club_id（=申请人俱乐部）过滤。
    不按被罚人、不按订单、不按交款人俱乐部掺数据。
    """
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        return qs
    if not hasattr(qs.model, 'ClubID'):
        return qs

    from django.db.models import Q

    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 filter_penalty_qs(qs, request):
    return _filter_by_penalty_club_id(qs, request)


def filter_gsfenhong_qs(qs, request):
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        return qs
    club_id = resolve_club_id_from_request(request)
    return qs.filter(club_id=club_id)


def forbid_penalty_out_of_scope(request, penalty):
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        return None
    club_id = resolve_club_id_from_request(request)
    penalty_club = getattr(penalty, 'ClubID', None) or CLUB_ID_DEFAULT
    if penalty_club != club_id:
        return Response({'code': 403, 'msg': '该罚单不属于当前俱乐部'})
    return None


def filter_penalty_record_qs(qs, request):
    """积分处罚记录（chufajilu）按申请人俱乐部 club_id 过滤。"""
    return _filter_by_penalty_club_id(qs, request)
