"""子客服订单查询：按权限隔离，不返回商家全量（除非 order_view_all）。"""
from backend.utils import fmt_datetime
from merchant_ops.models import MerchantOrderDispatch
from merchant_ops.services.authz import member_has_perm
from orders.models import MerchantOrderExt
from orders.services.merchant_order_list_filters import apply_merchant_order_list_filters


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):
    return apply_merchant_order_list_filters(qs, data)


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,
    }
