# -*- coding: utf-8 -*-
"""点单端搜索可指定打手（仅返回未封禁、当前未在服务中的打手）。"""
from django.db.models import Q
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from jituan.constants import CLUB_ID_DEFAULT
from jituan.services.club_context import resolve_effective_club_id
from orders.models import Order
from users.models import UserDashou


# 视为「接单中」：服务中 / 待结单 / 指定待接
_BUSY_ORDER_STATUS = (2, 7, 8)


class BossSearchDashouView(APIView):
    """
    POST /yonghu/sousuodashou
    body: { "keyword": "昵称或UID" }  — 必须有关键词才返回列表（点搜索才展示）
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        keyword = (request.data.get('keyword') or '').strip()
        if not keyword:
            return Response({'code': 0, 'data': {'list': []}, 'msg': '请输入昵称或UID后搜索'})

        club_id = resolve_effective_club_id(request, request.user) or CLUB_ID_DEFAULT

        # 当前俱乐部忙碌打手 UID
        busy_qs = Order.query.filter(
            club_id=club_id,
            zhuangtai__in=_BUSY_ORDER_STATUS,
        )
        busy_uids = set()
        for row in busy_qs.only('PlayerID', 'AssignedID')[:2000]:
            if row.PlayerID:
                busy_uids.add(str(row.PlayerID))
            if row.AssignedID:
                busy_uids.add(str(row.AssignedID))

        qs = (
            UserDashou.query.select_related('user')
            .filter(zhuangtai=1, zhanghaozhuangtai=1)
            .filter(
                Q(nicheng__icontains=keyword) | Q(user__UserUID__icontains=keyword)
            )
            .order_by('-jinrijiedan', '-CreateTime')[:50]
        )

        result = []
        for ds in qs:
            user = ds.user
            uid = str(user.UserUID or '')
            if not uid or uid in busy_uids:
                continue
            user_club = (getattr(user, 'ClubID', None) or getattr(user, 'club_id', None) or '').strip()
            # 有俱乐部归属时只返回本俱乐部打手；历史无 club 的也允许被指定
            if user_club and user_club != club_id:
                continue
            result.append({
                'uid': uid,
                'nicheng': ds.nicheng or getattr(user, 'UserName', '') or uid,
                'touxiang': getattr(user, 'Avatar', '') or '',
                'zaixian': int(ds.zaixianzhuangtai or 0),
            })

        return Response({'code': 0, 'data': {'list': result}})
