"""俱乐部订单单向互通抢单：grabber 可看/抢 order 俱乐部的待接单。"""
from django.db.models import Q

from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import Club, ClubOrderGrabLink


def normalize_club_id(club_id):
    return (club_id or '').strip() or CLUB_ID_DEFAULT


def order_club_ids_for_grabber(grabber_club_id):
    """
    打手所属俱乐部可见的订单 ClubID 集合（含本店 + 已配置可抢的对方店）。
    """
    gc = normalize_club_id(grabber_club_id)
    ids = {gc}
    for oc in ClubOrderGrabLink.query.filter(
        grabber_club_id=gc,
    ).values_list('order_club_id', flat=True):
        oc = (oc or '').strip()
        if oc:
            ids.add(oc)
    return ids


def order_club_q_for_grabber(grabber_club_id):
    """用于 Order 查询的 Q：本店 + 互通店；本店含默认俱乐部时兼容空 ClubID 旧单。"""
    allowed = order_club_ids_for_grabber(grabber_club_id)
    q = Q(ClubID__in=list(allowed))
    if CLUB_ID_DEFAULT in allowed:
        q |= Q(ClubID__isnull=True) | Q(ClubID='')
    return q


def can_grabber_take_order_club(grabber_club_id, order_club_id):
    gc = normalize_club_id(grabber_club_id)
    oc = normalize_club_id(order_club_id)
    if gc == oc:
        return True
    return ClubOrderGrabLink.query.filter(
        grabber_club_id=gc, order_club_id=oc,
    ).exists()


def list_grab_links():
    name_map = {c.club_id: c.name for c in Club.query.filter(status=1)}
    rows = list(ClubOrderGrabLink.query.order_by('grabber_club_id', 'order_club_id'))
    return [
        {
            'id': r.id,
            'grabber_club_id': r.grabber_club_id,
            'grabber_club_name': name_map.get(r.grabber_club_id, r.grabber_club_id),
            'order_club_id': r.order_club_id,
            'order_club_name': name_map.get(r.order_club_id, r.order_club_id),
            'create_time': r.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if r.CreateTime else '',
        }
        for r in rows
    ]


def add_grab_link(grabber_club_id, order_club_id):
    gc = (grabber_club_id or '').strip()
    oc = (order_club_id or '').strip()
    if not gc or not oc:
        return None, '请选择抢单方与被抢订单俱乐部'
    if gc == oc:
        return None, '不能配置本店抢本店（本店订单默认可见）'
    if not Club.query.filter(club_id=gc, status=1).exists():
        return None, f'抢单方俱乐部不存在: {gc}'
    if not Club.query.filter(club_id=oc, status=1).exists():
        return None, f'订单方俱乐部不存在: {oc}'
    if ClubOrderGrabLink.query.filter(grabber_club_id=gc, order_club_id=oc).exists():
        return None, '该互通规则已存在'
    row = ClubOrderGrabLink.query.create(
        grabber_club_id=gc,
        order_club_id=oc,
    )
    return {'id': row.id, 'grabber_club_id': gc, 'order_club_id': oc}, None


def delete_grab_link(link_id):
    try:
        link_id = int(link_id)
    except (TypeError, ValueError):
        return False, '无效的规则 id'
    deleted, _ = ClubOrderGrabLink.objects.filter(id=link_id).delete()
    if not deleted:
        return False, '规则不存在'
    return True, None
