"""罚单 / 管事分红俱乐部隔离与写入。"""
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 resolve_penalty_club_id(order=None, penalized_user_id=None, request=None):
    """创建罚单时写入 club_id。"""
    if order is not None:
        cid = getattr(order, 'ClubID', None)
        if cid:
            return cid
    if penalized_user_id:
        from users.business_models import User
        u = User.query.filter(UserUID=penalized_user_id).first()
        if u:
            return get_user_club_id(u)
    if request is not None:
        return resolve_club_id_from_request(request)
    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:
        from users.business_models import User
        u = User.query.filter(UserUID=dashouid).first()
        if u:
            return get_user_club_id(u)
    return CLUB_ID_DEFAULT


def _collect_club_user_ids(club_id):
    """俱乐部下属用户 UID（User.ClubID + 微信绑定 club）。"""
    from users.business_models import User
    from jituan.models import UserWxOpenid
    ids = set(User.query.filter(ClubID=club_id).values_list('UserUID', flat=True))
    ids.update(UserWxOpenid.query.filter(club_id=club_id).values_list('yonghuid', flat=True))
    return [x for x in ids if x]


def _filter_club_penalty_like_qs(qs, request, user_id_field, order_id_field):
    """罚单/积分处罚共用：ClubID + 被罚人 + 关联订单 归属当前俱乐部。"""
    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        return qs
    club_id = resolve_club_id_from_request(request)
    from django.db.models import Q
    from orders.models import Order

    parts = []
    if hasattr(qs.model, 'ClubID'):
        if club_id == CLUB_ID_DEFAULT:
            parts.append(
                Q(ClubID=club_id) | Q(ClubID__isnull=True) | Q(ClubID='')
            )
        else:
            parts.append(Q(ClubID=club_id))

    user_ids = _collect_club_user_ids(club_id)
    if user_ids:
        parts.append(Q(**{f'{user_id_field}__in': user_ids}))

    order_q = Q(ClubID=club_id)
    if club_id == CLUB_ID_DEFAULT:
        order_q = Q(ClubID=club_id) | Q(ClubID__isnull=True) | Q(ClubID='')
    order_ids = list(Order.query.filter(order_q).values_list('OrderID', flat=True))
    if order_ids:
        parts.append(Q(**{f'{order_id_field}__in': order_ids}))

    if not parts:
        return qs.none()
    combined = parts[0]
    for p in parts[1:]:
        combined |= p
    return qs.filter(combined)


def filter_penalty_qs(qs, request):
    return _filter_club_penalty_like_qs(
        qs, request, user_id_field='PenalizedUserID', order_id_field='RelatedOrderID'
    )


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 resolve_penalty_record_club_id(order_id=None, player_id=None):
    if order_id:
        from orders.models import Order
        o = Order.query.filter(OrderID=order_id).first()
        if o and getattr(o, 'ClubID', None):
            return o.ClubID
    if player_id:
        from users.business_models import User
        u = User.query.filter(UserUID=player_id).first()
        if u:
            return get_user_club_id(u)
    return CLUB_ID_DEFAULT


def filter_penalty_record_qs(qs, request):
    """积分处罚记录（chufajilu）按俱乐部过滤。"""
    return _filter_club_penalty_like_qs(
        qs, request, user_id_field='PlayerID', order_id_field='OrderID'
    )
