from django_filters import rest_framework as filters
from apps.ecm.models import Event


class EventFilterSet(filters.FilterSet):
    start_create = filters.DateTimeFilter(field_name="create_time", lookup_expr='gte')
    end_create = filters.DateTimeFilter(field_name="create_time", lookup_expr='lte')
    is_handled = filters.BooleanFilter(method='filter_is_handled')
    cates__in = filters.CharFilter(method='filter_cates__in')
    cates__code__in = filters.CharFilter(method='filter_cates__code__in')

    class Meta:
        model = Event
        fields = {
            "cates": ["exact"],
            "area": ["exact"],
            "mark": ["exact"],
        }

    def filter_is_handled(self, queryset, name, value):
        if value:  # 我的
            queryset = queryset.exclude(handle_user=None)
        else:
            queryset = queryset.filter(handle_user=None)
        return queryset

    def filter_cates__in(self, queryset, name, value):
        if value:
            vals = value.split(',')
        return queryset.filter(cates__in=vals)
    
    def filter_cates__code__in(self, queryset, name, value):
        if value:
            vals = value.split(',')
        return queryset.filter(cates__code__in=vals)