"""商家订单列表通用筛选（商家老板接口 + 子客服列表共用）。"""
from datetime import datetime

from django.conf import settings
from django.db.models import Q
from django.utils import timezone
from django.utils.dateparse import parse_datetime

from backend.utils import pick_leixing_id


def _db_dt(dt):
    """与项目 USE_TZ 设置一致：USE_TZ=False 时必须返回 naive datetime。"""
    if dt is None:
        return None
    if settings.USE_TZ:
        if timezone.is_naive(dt):
            return timezone.make_aware(dt, timezone.get_current_timezone())
        return dt
    if timezone.is_aware(dt):
        return timezone.make_naive(dt, timezone.get_current_timezone())
    return dt


def parse_order_list_bound(value, is_end=False):
    """解析列表时间边界；仅日期时开始取 00:00:00，结束取 23:59:59。"""
    if not value:
        return None
    raw = str(value).strip()
    if not raw:
        return None
    if len(raw) <= 10:
        try:
            base = datetime.strptime(raw[:10], '%Y-%m-%d')
        except ValueError:
            return None
        if is_end:
            base = base.replace(hour=23, minute=59, second=59)
        return _db_dt(base)
    dt = parse_datetime(raw.replace(' ', 'T', 1) if ' ' in raw and 'T' not in raw else raw)
    if dt is None:
        try:
            base = datetime.strptime(raw[:19], '%Y-%m-%d %H:%M:%S')
            return _db_dt(base)
        except ValueError:
            return None
    return _db_dt(dt)


def wants_auto_settle_pending(data) -> bool:
    """前端筛「待自动结算」：auto_settle_pending = 1/true。"""
    if not data:
        return False
    v = data.get('auto_settle_pending')
    if v is True or v == 1:
        return True
    if isinstance(v, str) and v.strip().lower() in ('1', 'true', 'yes'):
        return True
    return False


def apply_auto_settle_pending_filter(qs, data, *, through_order=True):
    """
    仅 Status=8 且 AutoSettleEligible 且有到期时间。
    through_order=True：MerchantOrderExt（Order__*）；False：Order 本表。
    """
    if not wants_auto_settle_pending(data):
        return qs
    if through_order:
        return qs.filter(
            Order__Status=8,
            Order__AutoSettleEligible=True,
            Order__AutoExpireAt__isnull=False,
        )
    return qs.filter(
        Status=8,
        AutoSettleEligible=True,
        AutoExpireAt__isnull=False,
    )


def apply_merchant_order_list_filters(qs, data):
    """在 MerchantOrderExt 查询集上应用类型/关键字/时间段筛选。"""
    leixing_id = pick_leixing_id(data)
    keyword = str(data.get('keyword', '')).strip()
    waibu_dingdan_id = str(data.get('waibuDingdanId') or data.get('waibu_dingdan_id') or '').strip()

    start_raw = data.get('start_time') or data.get('time_start') or data.get('create_time_start')
    end_raw = data.get('end_time') or data.get('time_end') or data.get('create_time_end')

    if leixing_id is not None:
        qs = qs.filter(Order__ProductTypeID=leixing_id)

    start_dt = parse_order_list_bound(start_raw, is_end=False)
    end_dt = parse_order_list_bound(end_raw, is_end=True)
    if start_dt and end_dt and start_dt > end_dt:
        start_dt, end_dt = end_dt, start_dt
    if start_dt:
        qs = qs.filter(Order__CreateTime__gte=start_dt)
    if end_dt:
        qs = qs.filter(Order__CreateTime__lte=end_dt)

    if waibu_dingdan_id:
        qs = qs.filter(Order__ExternalOrderID__exact=waibu_dingdan_id)
    elif keyword:
        qs = qs.filter(
            Q(Order__OrderID__exact=keyword)
            | Q(Order__Description__icontains=keyword)
            | Q(Order__Nickname__icontains=keyword)
            | Q(Order__PlayerID__exact=keyword)
            | Q(Order__ExternalOrderID__exact=keyword)
        )

    staff_member_id = data.get('staff_member_id')
    if staff_member_id:
        from merchant_ops.models import MerchantOrderDispatch
        try:
            smid = int(staff_member_id)
        except (TypeError, ValueError):
            return qs.none()
        merchant_id = data.get('_merchant_id_filter')
        disp_q = MerchantOrderDispatch.objects.filter(staff_member_id=smid)
        if merchant_id:
            disp_q = disp_q.filter(merchant_id=merchant_id)
        order_ids = list(disp_q.values_list('order_id', flat=True))
        if not order_ids:
            return qs.none()
        qs = qs.filter(Order__OrderID__in=order_ids)

    qs = apply_auto_settle_pending_filter(qs, data, through_order=True)
    return qs
