"""订单响应增强：派单客服信息、头像相对路径。"""
from merchant_ops.constants import ACTOR_MERCHANT, ACTOR_STAFF
from merchant_ops.models import MerchantOrderDispatch, MerchantStaffMember
from users.business_models import User


def user_avatar_relative(user):
    """返回用户表 Avatar 相对路径（前端自行拼接 OSS）。"""
    if not user:
        return ''
    av = (getattr(user, 'Avatar', None) or '').strip()
    if not av:
        return ''
    if av.startswith('http://') or av.startswith('https://'):
        return av
    return av.lstrip('/')


def get_user_avatar_by_uid(uid):
    if not uid:
        return ''
    u = User.query.filter(UserUID=uid).first()
    return user_avatar_relative(u)


def staff_display_label(member):
    """商家侧展示名：商家备注 > 显示名 > 角色名 > UID"""
    if not member:
        return ''
    remark = (getattr(member, 'merchant_remark', None) or '').strip()
    if remark:
        return remark
    name = (member.display_name or '').strip()
    if name:
        return name
    if member.role:
        return member.role.role_name or member.staff_user_id
    return member.staff_user_id


def get_dispatch_staff_payload(order_id):
    """订单派单归属；无记录则 None（商家老板派单可能无 dispatch 记录）。"""
    if not order_id:
        return None
    disp = MerchantOrderDispatch.query.filter(order_id=order_id).first()
    if not disp:
        return None
    if disp.dispatch_actor_type == ACTOR_MERCHANT:
        u = User.query.filter(UserUID=disp.dispatch_actor_id).first() if disp.dispatch_actor_id else None
        return {
            'dispatch_staff_type': ACTOR_MERCHANT,
            'dispatch_staff_uid': disp.dispatch_actor_id or '',
            'dispatch_staff_name': '商家老板',
            'dispatch_staff_avatar': user_avatar_relative(u),
            'dispatch_role_code': '',
            'dispatch_role_name': '商家老板',
            'dispatch_member_id': None,
        }
    if disp.staff_member_id:
        m = MerchantStaffMember.query.filter(id=disp.staff_member_id).select_related('role').first()
        if m:
            u = User.query.filter(UserUID=m.staff_user_id).first()
            return {
                'dispatch_staff_type': ACTOR_STAFF,
                'dispatch_staff_uid': m.staff_user_id,
                'dispatch_staff_name': staff_display_label(m),
                'dispatch_staff_avatar': user_avatar_relative(u),
                'dispatch_role_code': m.role.role_code if m.role else '',
                'dispatch_role_name': m.role.role_name if m.role else '',
                'dispatch_member_id': m.id,
            }
    return {
        'dispatch_staff_type': disp.dispatch_actor_type,
        'dispatch_staff_uid': disp.dispatch_actor_id or '',
        'dispatch_staff_name': disp.dispatch_actor_id or '',
        'dispatch_role_code': '',
        'dispatch_role_name': '',
        'dispatch_member_id': disp.staff_member_id,
    }


def enrich_order_detail_data(data, order_id):
    """订单详情追加派单客服；打手头像优先用户表相对路径。"""
    if not data or not isinstance(data, dict):
        return data
    payload = get_dispatch_staff_payload(order_id)
    if payload:
        data['dispatch_staff'] = payload
    else:
        data['dispatch_staff'] = None
    dashou_uid = data.get('dashou_yonghuid') or data.get('fuwudashou_id') or ''
    av = get_user_avatar_by_uid(dashou_uid)
    if av:
        data['dashou_avatar'] = av
    return data


def staff_order_list_item(ext):
    """子客服订单列表项：不含派单客服字段，打手头像走用户表。"""
    from merchant_ops.services.order_query import staff_order_to_dict
    d = staff_order_to_dict(ext)
    pid = d.get('jiedan_dashou_id')
    if pid:
        d['jiedan_dashou_avatar'] = get_user_avatar_by_uid(pid)
    return d
