from django.db.models import Q
from django_filters import rest_framework as filter


class TaskListFilter(filter.FilterSet):
    status = filter.CharFilter(method="get_status")
    name = filter.CharFilter(method="get_name")
    customer_id = filter.NumberFilter(method="get_customer_id")
    type = filter.CharFilter(method="get_type")
    keyword = filter.CharFilter(method="get_keyword")
    start_time = filter.DateTimeFilter(method="get_start_time")
    end_time = filter.DateTimeFilter(method="get_end_time")

    def get_start_time(self, queryset, name, value):
        if value:
            queryset = queryset.filter(created_time__lte=value)
        return queryset

    def get_end_time(self, queryset, name, value):
        if value:
            queryset = queryset.filter(created_time__lte=value)
        return queryset

    def get_keyword(self, queryset, name, value):
        if value:
            queryset = queryset.filter(
                Q(name__icontains=value) | Q(customer__name__icontains=value))
        return queryset

    def get_status(self, queryset, name, value):
        if value:
            # 待处理的任务
            if value == "pending":
                queryset = queryset.filter(status__in=[
                    "waiting_dispatch", "waiting_plan", "waiting_confirm",
                    "pending"
                ])
            else:
                queryset = queryset.filter(status=value)
        return queryset

    def get_name(self, queryset, name, value):
        if value:
            queryset = queryset.filter(name__icontains=value)
        return queryset

    def get_customer_id(self, queryset, name, value):
        if value:
            queryset = queryset.filter(customer_id=value)
        return queryset

    def get_type(self, queryset, name, value):
        if value:
            queryset = queryset.filter(type=value)
        return queryset
