"""子客服订单查询：按权限隔离，不返回商家全量（除非 order_view_all）。"""
from django.db.models import Q

from backend.utils import fmt_datetime, pick_leixing_id
from merchant_ops.models import MerchantOrderDispatch
from merchant_ops.services.authz import member_has_perm
from orders.models import MerchantOrderExt


def staff_can_view_all_orders(member):
    return member_has_perm(member, 'order_view_all')


def staff_order_ext_qs(member, zhuangtai_list=None):
    """商家名下订单；无 order_view_all 时仅本人派单记录。"""
    qs = MerchantOrderExt.query.filter(
        MerchantID=member.merchant_id,
    ).select_related('Order')
    if zhuangtai_list is not None:
        qs = qs.filter(Order__Status__in=zhuangtai_list)
    if not staff_can_view_all_orders(member):
        own_ids = list(
            MerchantOrderDispatch.query.filter(staff_member_id=member.id).values_list('order_id', flat=True)
        )
        qs = qs.filter(Order__OrderID__in=own_ids)
    return qs


def staff_apply_order_filters(qs, data):
    leixing_id = pick_leixing_id(data)
    keyword = str(data.get('keyword', '')).strip()
    if leixing_id is not None:
        qs = qs.filter(Order__ProductTypeID=leixing_id)
    if keyword:
        qs = qs.filter(
            Q(Order__OrderID__exact=keyword)
            | Q(Order__Description__icontains=keyword)
            | Q(Order__Nickname__icontains=keyword)
            | Q(Order__PlayerID__exact=keyword)
        )
    return qs


def staff_order_to_dict(ext):
    o = ext.Order
    ct = fmt_datetime(o.CreateTime)
    return {
        'dingdan_id': o.OrderID,
        '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 '',
        'CreateTime': ct,
        'create_time': ct,
    }
