"""俱乐部抢单池标签筛选区配置（全局考核称号由集团定义）。"""
from jituan.constants import DATA_SCOPE_ALL
from jituan.models import ClubKaoheChenghaoConfig
from jituan.services.club_context import (
    club_id_for_write,
    resolve_club_id_from_request,
    resolve_club_scope,
)
from jituan.constants import CLUB_ID_DEFAULT
from rank.models import Chenghao

CLUB_WRITE_SCOPE_MSG = '当前为集团汇总视图，请先在顶栏切换到具体俱乐部后再操作'
CLUB_READ_SCOPE_MSG = '请先在顶栏切换到具体小程序/俱乐部后再操作'


def club_read_blocked(request):
    return resolve_club_scope(request) == DATA_SCOPE_ALL


def club_write_blocked(request):
    return resolve_club_scope(request) == DATA_SCOPE_ALL


def _config_map(club_id):
    return {
        r.chenghao_id: r
        for r in ClubKaoheChenghaoConfig.query.filter(club_id=club_id)
    }


def _is_visible(club_id, chenghao_id, cfg):
    if cfg is not None:
        return bool(cfg.is_enabled)
    return club_id == CLUB_ID_DEFAULT


def filter_chenghao_ids_for_pool(club_id, chenghao_ids):
    """抢单池标签筛选：仅保留本俱乐部已上架的称号 ID。"""
    if not chenghao_ids:
        return []
    cfg_map = _config_map(club_id)
    visible = []
    for cid in chenghao_ids:
        cfg = cfg_map.get(cid)
        if _is_visible(club_id, cid, cfg):
            visible.append(cid)
    return visible


def build_club_kaohe_admin_list(request, bankuai_id=None):
    if club_read_blocked(request):
        return {
            'club_id': resolve_club_id_from_request(request),
            'list': [],
            'scope': resolve_club_scope(request),
            'scope_error': CLUB_READ_SCOPE_MSG,
        }
    club_id = resolve_club_id_from_request(request)
    cfg_map = _config_map(club_id)
    qs = Chenghao.objects.filter(leixing='dashou')
    if bankuai_id:
        qs = qs.filter(bankuai_id=bankuai_id)
    enabled = []
    for ch in qs.order_by('id'):
        cfg = cfg_map.get(ch.id)
        if not _is_visible(club_id, ch.id, cfg):
            continue
        enabled.append({
            'id': ch.id,
            'mingcheng': ch.mingcheng,
            'bankuai_id': ch.bankuai_id,
            'kaioi_jinpai': bool(ch.kaioi_jinpai),
            'club_enabled': True,
        })
    return {
        'club_id': club_id,
        'list': enabled,
        'scope': resolve_club_scope(request),
    }


def build_club_kaohe_catalog(request, bankuai_id=None):
    if club_read_blocked(request):
        return {
            'club_id': resolve_club_id_from_request(request),
            'catalog': [],
            'scope_error': CLUB_READ_SCOPE_MSG,
        }
    club_id = resolve_club_id_from_request(request)
    cfg_map = _config_map(club_id)
    qs = Chenghao.objects.filter(leixing='dashou')
    if bankuai_id:
        qs = qs.filter(bankuai_id=bankuai_id)
    catalog = []
    for ch in qs.order_by('mingcheng'):
        cfg = cfg_map.get(ch.id)
        if _is_visible(club_id, ch.id, cfg):
            continue
        catalog.append({
            'id': ch.id,
            'mingcheng': ch.mingcheng,
            'bankuai_id': ch.bankuai_id,
        })
    return {'club_id': club_id, 'catalog': catalog}


def enable_chenghao_for_club(request, chenghao_id):
    if club_write_blocked(request):
        return None, CLUB_WRITE_SCOPE_MSG
    club_id = club_id_for_write(request)
    if not Chenghao.objects.filter(id=chenghao_id, leixing='dashou').exists():
        return None, '考核标签不存在'
    row, _ = ClubKaoheChenghaoConfig.query.get_or_create(
        club_id=club_id,
        chenghao_id=chenghao_id,
        defaults={'is_enabled': True},
    )
    row.is_enabled = True
    row.save(update_fields=['is_enabled', 'UpdateTime'])
    return {'chenghao_id': chenghao_id}, None


def disable_chenghao_for_club(request, chenghao_id):
    if club_write_blocked(request):
        return None, CLUB_WRITE_SCOPE_MSG
    club_id = club_id_for_write(request)
    row, _ = ClubKaoheChenghaoConfig.query.get_or_create(
        club_id=club_id,
        chenghao_id=chenghao_id,
        defaults={'is_enabled': False},
    )
    row.is_enabled = False
    row.save(update_fields=['is_enabled', 'UpdateTime'])
    return {'chenghao_id': chenghao_id}, None


def copy_club_kaohe_chenghao_config(template_club_id, new_club_id):
    for row in ClubKaoheChenghaoConfig.query.filter(club_id=template_club_id):
        if ClubKaoheChenghaoConfig.query.filter(
            club_id=new_club_id, chenghao_id=row.chenghao_id,
        ).exists():
            continue
        ClubKaoheChenghaoConfig.query.create(
            club_id=new_club_id,
            chenghao_id=row.chenghao_id,
            is_enabled=row.is_enabled,
        )
