from django_filters import rest_framework as filters
from apps.inm.models import MaterialBatch, MIO
from django.db.models import Q, Subquery, OuterRef, F

class MaterialBatchFilter(filters.FilterSet):
    count_canmio__gt = filters.NumberFilter(
        method='filter_count_canmio__gt', label='可发数量大于')

    class Meta:
        model = MaterialBatch
        fields = {
            "warehouse": ["exact"],
            "material": ["exact"],
            "material__type": ["exact", "in"],
            "material__process": ["exact", "in"],
            "count": ["exact", "gte", "lte"],
            "state": ["exact", "in"],
            "defect": ["exact"],
            "batch": ["exact"]
        }

    def filter_count_canmio__gt(self, queryset, name, value):
        # 可发数量 = 存量 - 正在出入库数量; count_mioing_anno 由 MaterialBatchViewSet 的 queryset 注解
        return queryset.filter(count__gt=F('count_mioing_anno') + value)


class MioFilter(filters.FilterSet):
    materials__type = filters.CharFilter(
        method='filter_materials__type', label='物料类型')
    materials__type__in = filters.CharFilter(
        method='filter_materials__type__in', label="物料类型多选")
    # is_testd = filters.CharFilter(label="是否已检验yes/no", method="filter_is_testd")

    class Meta:
        model = MIO
        fields = {
            'id': ["exact"],
            'state': ["exact", "in"],
            "type": ["exact", "in"],
            "pu_order": ["exact"],
            "order": ["exact"],
            "item_mio__test_date": ["isnull"],
            "item_mio__test_user": ["isnull"],
            "item_mio__w_mioitem__number": ["exact"],
            "mgroup": ["exact"],
            "item_mio__batch": ["exact"],
            "inout_date": ["gte", "lte", "exact"],
            "belong_dept": ["exact"]
        }

    def filter_materials__type(self, queryset, name, value):
        if value:
            return queryset.filter(Q(materials__type=value) | Q(materials__isnull=True)).distinct()
        return queryset

    def filter_materials__type__in(self, queryset, name, value):
        if value:
            return queryset.filter(Q(materials__type__in=value.split(',')) | Q(materials__isnull=True)).distinct()
        return queryset
    
    # def filter_is_testd(self, queryset, name, value):
    #     if value == "yes":
    #         return queryset.filter(item_mio__test_date__isnull=False).distinct()  # 这里有问题，需要用到子查询影响性能
    #     elif value == "no":
    #         return queryset.filter(item_mio__test_date__isnull=True).distinct()
    #     else:
    #         return queryset
