"""商家订单列表增强：标签、头像、优质商家等与抢单池 /ddhq 对齐。"""
import json
import logging

from jituan.services.identity_tag import SHENFEN_DASHOU, SHENFEN_SHANGJIA, batch_identity_tags
from orders.models import MerchantOrderExt
from rank.models import DingdanBiaoqian, YonghuChenghao
from users.business_models import User
from users.models import UserShangjia
from backend.utils import fmt_datetime
from jituan.services.order_deal import order_auto_settle_payload

logger = logging.getLogger(__name__)


def _parse_texiao_json(texiao_miaoshu):
    if not texiao_miaoshu:
        return {}
    try:
        return json.loads(texiao_miaoshu)
    except Exception:
        return {}


def _chenghao_tag(ch):
    return {
        'id': ch.id,
        'mingcheng': ch.mingcheng,
        'texiao_json': _parse_texiao_json(ch.texiao_miaoshu),
    }


def enrich_merchant_order_list_items(ext_list, club_id=None):
    """
    批量格式化商家订单列表项。
    ext_list: MerchantOrderExt 实例列表（已 select_related Order）
    """
    if not ext_list:
        return []

    order_ids = []
    merchant_uids = set()
    zhiding_ids = set()
    pairs = []

    for ext in ext_list:
        o = ext.Order
        order_ids.append(o.OrderID)
        if ext.MerchantID:
            merchant_uids.add(ext.MerchantID)
        zid = o.AssignedID or ''
        if zid:
            zhiding_ids.add(zid)

    # 订单需求标签
    xuqiu_tags_map = {}
    if order_ids:
        try:
            for dbq in DingdanBiaoqian.query.filter(dingdan_id__in=order_ids).select_related('chenghao'):
                xuqiu_tags_map.setdefault(dbq.dingdan_id, []).append(_chenghao_tag(dbq.chenghao))
        except Exception as e:
            logger.error('商家订单列表-需求标签查询失败: %s', e, exc_info=True)

    uid_set = set(merchant_uids) | zhiding_ids
    user_id_map = {}
    user_avatar_map = {}
    user_nick_map = {}
    if uid_set:
        for u in User.query.filter(UserUID__in=uid_set).select_related('ShopProfile', 'DashouProfile'):
            user_id_map[u.UserUID] = u.UserUUID
            user_avatar_map[u.UserUID] = (u.Avatar or '').strip()
            nick = ''
            if hasattr(u, 'ShopProfile') and u.ShopProfile:
                nick = u.ShopProfile.nicheng or ''
            user_nick_map[u.UserUID] = nick

    user_main_ids = list(user_id_map.values())
    user_tags_map = {}
    if user_main_ids:
        for uc in YonghuChenghao.query.filter(yonghu_id__in=user_main_ids).select_related('chenghao'):
            user_tags_map.setdefault(uc.yonghu_id, []).append(uc.chenghao)

    youzhi_map = {}
    if merchant_uids:
        for row in UserShangjia.query.filter(user__UserUID__in=merchant_uids).values(
            'user__UserUID', 'is_youzhi_shangjia'
        ):
            youzhi_map[row['user__UserUID']] = bool(row['is_youzhi_shangjia'])

    for ext in ext_list:
        o = ext.Order
        oid = o.OrderID
        sj_uid = ext.MerchantID or ''
        zid = o.AssignedID or ''
        if zid:
            pairs.append((zid, SHENFEN_DASHOU))
        if sj_uid:
            pairs.append((sj_uid, SHENFEN_SHANGJIA))

    identity_tag_map = batch_identity_tags(club_id, pairs) if (club_id and pairs) else {}

    zhiding_info = {}
    if zhiding_ids:
        for u in User.query.filter(UserUID__in=zhiding_ids).select_related('DashouProfile'):
            nicheng = ''
            if hasattr(u, 'DashouProfile') and u.DashouProfile:
                nicheng = u.DashouProfile.nicheng or ''
            zhiding_info[u.UserUID] = {
                'avatar': u.Avatar or '',
                'nicheng': nicheng,
            }

    result = []
    for ext in ext_list:
        o = ext.Order
        oid = o.OrderID
        sj_uid = ext.MerchantID or ''
        ct = fmt_datetime(o.CreateTime)

        shangjia_biaoqian = []
        if sj_uid and sj_uid in user_id_map:
            uid = user_id_map[sj_uid]
            for ch in user_tags_map.get(uid, []):
                if ch.leixing == 'shangjia':
                    shangjia_biaoqian.append(_chenghao_tag(ch))

        zid = o.AssignedID or ''
        zinfo = zhiding_info.get(zid, {})

        item = {
            'dingdan_id': oid,
            'zhuangtai': o.Status,
            'jine': float(o.Amount) if o.Amount else 0.0,
            'jieshao': o.Description or '',
            'beizhu': o.Remark or '',
            'nicheng': o.Nickname or '',
            'leixing_id': o.ProductTypeID,
            'tupian': o.ImageURL or '',
            'jiedan_dashou_id': o.PlayerID or '',
            'waibu_dingdan_id': o.ExternalOrderID or '',
            'creat_time': ct,
            'create_time': ct,
            'sjnicheng': ext.MerchantNickname or user_nick_map.get(sj_uid, '') or '未知商家',
            'shangjia_id': sj_uid,
            'sj_avatar': user_avatar_map.get(sj_uid, ''),
            'xuqiu_biaoqian': xuqiu_tags_map.get(oid, []),
            'shangjia_biaoqian': shangjia_biaoqian,
            'shangjia_identity_biaoqian': identity_tag_map.get((sj_uid, SHENFEN_SHANGJIA), []) if sj_uid else [],
            'shangjia_youzhi': bool(youzhi_map.get(sj_uid)) if sj_uid else False,
            'zhiding_uid': zid,
            'zhiding_avatar': zinfo.get('avatar', ''),
            'zhiding_nicheng': zinfo.get('nicheng', ''),
        }
        item.update(order_auto_settle_payload(o))
        result.append(item)

    return result
