"""身份装饰标签查询与组装（与考核称号、订单需求标签分离）。"""
import json

from django.db.models import Q

from jituan.constants import CLUB_ID_DEFAULT
from jituan.models import IdentityTag, IdentityTagBind

SHENFEN_DASHOU = 1
SHENFEN_GUANSHI = 2
SHENFEN_SHANGJIA = 3
SHENFEN_ZUZHANG = 4


def _tag_texiao(tag):
    """合并 texiao_json 与 color / flash 列，避免空 JSON 导致前端默认金黄。"""
    base = {}
    if tag.texiao_json:
        try:
            parsed = json.loads(tag.texiao_json)
            if isinstance(parsed, dict):
                base = dict(parsed)
        except (TypeError, ValueError, json.JSONDecodeError):
            pass
    if not base.get('color') and tag.color:
        base['color'] = tag.color
    if 'flash' not in base:
        base['flash'] = bool(tag.flash_enabled)
    # 身份装饰标签固定圆角 pill，勿沿用考核称号的 shape
    if 'shape' in base and base.get('shape') not in (None, '', 'pill', 'rounded', 'rectangle'):
        base.pop('shape', None)
    return base


def format_tag_item(tag):
    texiao = _tag_texiao(tag)
    return {
        'id': tag.id,
        'mingcheng': tag.name,
        'color': texiao.get('color') or tag.color or '#000000',
        'flash_enabled': bool(texiao.get('flash')),
        'texiao_json': texiao,
    }


def _club_id_filter(club_id):
    """按俱乐部查绑定；非默认俱乐部时回退 xq / 空，兼容集团历史数据。"""
    q = Q(club_id=club_id)
    if club_id and club_id != CLUB_ID_DEFAULT:
        q |= Q(club_id=CLUB_ID_DEFAULT) | Q(club_id__isnull=True) | Q(club_id='')
    elif club_id == CLUB_ID_DEFAULT:
        q |= Q(club_id__isnull=True) | Q(club_id='')
    return q


def get_identity_tags_for_user(club_id, yonghuid, shenfen):
    """单用户单身份装饰标签列表。"""
    binds = (
        IdentityTagBind.query.filter(
            yonghuid=yonghuid,
            shenfen=shenfen,
        )
        .filter(_club_id_filter(club_id))
        .select_related('tag')
        .order_by('tag__sort_order', 'tag__id')
    )
    result = []
    for b in binds:
        tag = b.tag
        if tag.status != 1:
            continue
        result.append(format_tag_item(tag))
    return result


def batch_identity_tags(club_id, yonghuid_shenfen_pairs):
    """
    批量查询：[(yonghuid, shenfen), ...] -> {(yonghuid, shenfen): [tags]}
    """
    if not yonghuid_shenfen_pairs:
        return {}
    yonghuids = {p[0] for p in yonghuid_shenfen_pairs}
    shenfens = {p[1] for p in yonghuid_shenfen_pairs}
    binds = (
        IdentityTagBind.query.filter(
            yonghuid__in=yonghuids,
            shenfen__in=shenfens,
        )
        .filter(_club_id_filter(club_id))
        .select_related('tag')
        .order_by('tag__sort_order', 'tag__id')
    )
    out = {}
    pair_set = set(yonghuid_shenfen_pairs)
    seen = {}
    for b in binds:
        key = (b.yonghuid, b.shenfen)
        if key not in pair_set:
            continue
        if b.tag.status != 1:
            continue
        tag_id = b.tag.id
        if seen.get(key, set()).intersection({tag_id}):
            continue
        seen.setdefault(key, set()).add(tag_id)
        out.setdefault(key, []).append(format_tag_item(b.tag))
    return out


def get_my_identity_tags(user, club_id):
    """当前用户各已激活身份的装饰标签。"""
    uid = user.UserUID
    data = {'dashou': [], 'guanshi': [], 'zuzhang': [], 'shangjia': []}

    try:
        dp = user.DashouProfile
        if dp.zhanghaozhuangtai == 1:
            data['dashou'] = get_identity_tags_for_user(club_id, uid, SHENFEN_DASHOU)
    except Exception:
        pass

    try:
        gp = user.GuanshiProfile
        if gp.zhuangtai == 1:
            data['guanshi'] = get_identity_tags_for_user(club_id, uid, SHENFEN_GUANSHI)
    except Exception:
        pass

    try:
        zp = user.ZuzhangProfile
        if zp.zhuangtai == 1:
            data['zuzhang'] = get_identity_tags_for_user(club_id, uid, SHENFEN_ZUZHANG)
    except Exception:
        pass

    try:
        sp = user.ShopProfile
        if sp.zhuangtai == 1:
            data['shangjia'] = get_identity_tags_for_user(club_id, uid, SHENFEN_SHANGJIA)
    except Exception:
        pass

    return data
