"""点单端老板推荐官相关接口（无邀请码，按 UserUID）。"""
import logging

from django.core.paginator import Paginator, EmptyPage
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 users.models import YonghuCYaoqing, UserBoss
from users.business_models import User
from users.services.c_invite import (
    bind_c_inviter_by_uid,
    get_or_create_c_yaoqing,
)

logger = logging.getLogger(__name__)


class CYaoqingmaView(APIView):
    """
    点单端推荐官摘要（兼容旧路由名 cyaoqingma）。
    不再生成邀请码，只返回本人 UID / 推荐人数 / 当前推荐官。
    POST /yonghu/cyaoqingma
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        if not getattr(user, 'UserUID', None):
            return Response({'code': 500, 'msg': '用户身份异常', 'data': None})
        try:
            profile = get_or_create_c_yaoqing(user)
            return Response({
                'code': 200,
                'msg': 'ok',
                'data': {
                    'uid': user.UserUID,
                    'yaogingshuliang': profile.yaogingshuliang or 0,
                    'yaoqingren': profile.yaoqingren or '',
                    # 兼容前端旧字段：以前误用邀请码，现改为本人 UID
                    'yaoqingma': user.UserUID,
                },
            })
        except Exception as e:
            logger.exception('获取推荐官摘要失败: %s', e)
            return Response({'code': 500, 'msg': '获取失败', 'data': None})


class CYaoqingBangdingView(APIView):
    """
    绑定/换绑推荐官（并同步店铺）。
    POST /yonghu/cyaoqingbd
    参数：yaoqingren / inviterUid / inviteCode（后两者兼容扫码旧参，均按 UserUID 解析）
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        inviter_uid = (
            request.data.get('yaoqingren')
            or request.data.get('inviterUid')
            or request.data.get('inviteCode')
            or ''
        )
        result = bind_c_inviter_by_uid(request.user, inviter_uid)
        return Response({
            'code': result['code'],
            'msg': result['msg'],
            'data': result.get('data'),
        })


class CYaoqingListView(APIView):
    """我推荐的人列表。POST /yonghu/cwyqr"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        current_user = request.user
        try:
            page = int(request.data.get('page', 1))
            page_size = int(request.data.get('pageSize', 20))
        except (TypeError, ValueError):
            return Response({'code': 400, 'msg': '分页参数错误'})
        if page < 1 or page_size < 1:
            return Response({'code': 400, 'msg': '分页参数必须大于0'})
        page_size = min(page_size, 100)

        keyword = (request.data.get('keyword') or '').strip()

        base_qs = YonghuCYaoqing.query.select_related('user').filter(
            yaoqingren=current_user.UserUID
        )

        total_all = base_qs.count()
        try:
            my_profile = current_user.CYaoqingProfile
            yaoqingzongshu = my_profile.yaogingshuliang
        except YonghuCYaoqing.DoesNotExist:
            yaoqingzongshu = total_all

        if keyword:
            uid_matched = User.query.filter(UserUID__icontains=keyword).values_list('UserUUID', flat=True)
            boss_matched = UserBoss.query.filter(nickname__icontains=keyword).values_list('user_id', flat=True)
            base_qs = base_qs.filter(Q(user_id__in=uid_matched) | Q(user_id__in=boss_matched))

        base_qs = base_qs.order_by('-CreateTime')
        paginator = Paginator(base_qs, page_size)
        try:
            page_obj = paginator.page(page)
            has_more = page_obj.has_next()
            filtered_total = paginator.count
        except EmptyPage:
            page_obj = []
            has_more = False
            filtered_total = paginator.count

        user_uuids = [p.user_id for p in page_obj]
        nick_map = {}
        if user_uuids:
            for b in UserBoss.query.filter(user_id__in=user_uuids).only('user_id', 'nickname'):
                nick_map[b.user_id] = b.nickname or ''

        rows = []
        for p in page_obj:
            u = p.user
            rows.append({
                'uid': u.UserUID,
                'nicheng': nick_map.get(p.user_id) or '微信用户',
                'touxiang': u.Avatar or '',
                'createTime': p.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if p.CreateTime else '',
            })

        return Response({
            'code': 200,
            'msg': 'ok',
            'data': {
                'list': rows,
                'yaoqingzongshu': yaoqingzongshu,
                'totalCount': filtered_total,
                'currentPage': page,
                'pageSize': page_size,
                'hasMore': has_more,
            },
        })


class CYaoqingWodeView(APIView):
    """当前用户推荐关系摘要。POST /yonghu/cyqwd"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        profile = get_or_create_c_yaoqing(request.user)
        inviter_info = None
        if profile.yaoqingren:
            try:
                inviter = User.query.get(UserUID=profile.yaoqingren)
                nicheng = '微信用户'
                try:
                    nicheng = inviter.BossProfile.nickname or nicheng
                except Exception:
                    pass
                inviter_info = {
                    'uid': inviter.UserUID,
                    'nicheng': nicheng,
                    'touxiang': inviter.Avatar or '',
                }
            except User.DoesNotExist:
                inviter_info = {'uid': profile.yaoqingren, 'nicheng': '未知', 'touxiang': ''}

        return Response({
            'code': 200,
            'msg': 'ok',
            'data': {
                'uid': request.user.UserUID,
                'yaogingshuliang': profile.yaogingshuliang or 0,
                'yaoqingren': profile.yaoqingren or '',
                'inviter': inviter_info,
            },
        })
