"""用户管理汇总统计（集团汇总 + 按俱乐部拆分）。"""
from django.utils import timezone

from jituan.constants import DATA_SCOPE_ALL
from jituan.models import Club
from jituan.services.club_context import (
    filter_queryset_by_club,
    resolve_club_id_from_request,
    resolve_club_scope,
    filter_user_qs_by_club,
    filter_user_related_by_club,
)
from products.models import Huiyuangoumai
from users.business_models import User
from users.models import UserDashou, UserGuanshi, UserShangjia, UserZuzhang


def _dashou_valid_count(request, dashou_user_ids):
    now = timezone.now()
    hy_qs = filter_queryset_by_club(Huiyuangoumai.query.all(), request)
    return hy_qs.filter(
        yonghu_id__in=dashou_user_ids,
        huiyuan_zhuangtai=1,
        daoqi_time__gt=now,
    ).values('yonghu_id').distinct().count()


def _counts_for_club_id(club_id):
    dashou_qs = UserDashou.query.filter(user__ClubID=club_id)
    dashou_ids = dashou_qs.values_list('user__UserUID', flat=True)
    now = timezone.now()
    dashou_valid = Huiyuangoumai.query.filter(
        club_id=club_id,
        yonghu_id__in=dashou_ids,
        huiyuan_zhuangtai=1,
        daoqi_time__gt=now,
    ).values('yonghu_id').distinct().count()
    shangjia_qs = UserShangjia.query.filter(user__ClubID=club_id)
    return {
        'club_id': club_id,
        'dashou_total': dashou_qs.count(),
        'dashou_valid': dashou_valid,
        'guanshi_total': User.query.filter(ClubID=club_id, GuanshiProfile__isnull=False).count(),
        'shangjia_total': shangjia_qs.count(),
        'shangjia_valid': shangjia_qs.filter(zhuangtai=1).count(),
        'zuzhang_total': UserZuzhang.query.filter(user__ClubID=club_id).count(),
        'zuzhang_active': UserZuzhang.query.filter(user__ClubID=club_id, zhuangtai=1).count(),
    }


def build_user_summary(request):
    dashou_qs = filter_user_related_by_club(UserDashou.query.all(), request)
    guanshi_qs = filter_user_qs_by_club(
        User.query.filter(GuanshiProfile__isnull=False), request,
    )
    shangjia_qs = filter_user_related_by_club(UserShangjia.query.all(), request)
    zuzhang_qs = filter_user_related_by_club(UserZuzhang.query.all(), request)

    dashou_ids = dashou_qs.values_list('user__UserUID', flat=True)
    result = {
        'club_id': resolve_club_id_from_request(request),
        'scope': resolve_club_scope(request),
        'dashou_total': dashou_qs.count(),
        'dashou_valid': _dashou_valid_count(request, dashou_ids),
        'guanshi_total': guanshi_qs.count(),
        'shangjia_total': shangjia_qs.count(),
        'shangjia_valid': shangjia_qs.filter(zhuangtai=1).count(),
        'zuzhang_total': zuzhang_qs.count(),
        'zuzhang_active': zuzhang_qs.filter(zhuangtai=1).count(),
    }

    if resolve_club_scope(request) == DATA_SCOPE_ALL:
        by_club = []
        for club in Club.query.filter(status=1).order_by('sort_order', 'club_id'):
            row = _counts_for_club_id(club.club_id)
            row['name'] = club.name
            by_club.append(row)
        result['by_club'] = by_club

    return result
