from django_filters import rest_framework as filters
from apps.mtm.models import Goal, Material, Route
from django.db.models.expressions import F


class MaterialFilter(filters.FilterSet):
    tag = filters.CharFilter(method='filter_tag')

    class Meta:
        model = Material
        fields = {
            "id": ["exact", "in"],
            "cate": ["exact", "in"],
            "code": ["exact", "in", "isnull"],
            "type": ["exact", "in"],
            "is_hidden": ["exact"],
            "is_assemb": ["exact"],
            "need_route": ["exact"],
            "name": ["exact", 'contains'],
            "process": ["exact", "in", "isnull"],
            "orderitem_material__order": ['exact'],
            "pu_orderitem_material__pu_order": ["exact"],
            "route_material_out__mgroup": ["exact"],
            "count": ["gte", "lte", "exact", "gt", "lt"],
            "count_safe": ["gte", "lte", "exact", "gt", "lt"]
        }

    def filter_tag(self, queryset, name, value):
        if value == 'low_inm':
            queryset = queryset.exclude(count_safe=None).filter(
                count__lte=F('count_safe'))
        return queryset


class GoalFilter(filters.FilterSet):
    class Meta:
        model = Goal
        fields = {
            "mgroup": ["exact", "in"],
            "mgroup__name": ["exact", "in"],
            "goal_cate": ["exact", "in"],
            "goal_cate__code": ["exact", "in"],
            "year": ["exact"]
        }


class RouteFilter(filters.FilterSet):
    class Meta:
        model = Route
        fields = { 
            "material": ["exact", "in", "isnull"],
            "material_out": ["exact", "in"],
            "material_in": ["exact", "in"],
            "process": ["exact", "in"],
            "is_autotask": ["exact"],
            "routepack": ["exact", "isnull"],
            "routepack__state": ["exact"],
            "mgroup": ["exact", "in", "isnull"],
            "mgroup__name": ["exact", "contains"],
            "mgroup__belong_dept": ["exact"],
            "mgroup__belong_dept__name": ["exact", "contains"]
        }
