from django_filters import rest_framework as filters
from apps.qm.models import QuaStat, TestItem, FtestWork, Qct, Ftest
from apps.utils.filters import MyJsonListFilter
from django.db.models import Q


class QuaStatFilter(filters.FilterSet):
    class Meta:
        model = QuaStat
        fields = {
            "material": ["exact"],
            "testitem": ["exact"],
            "belong_dept": ["exact"],
            "sflog": ["exact"],
            "sflog__mgroup": ["exact"],
            "sflog__end_time": ["day", "month", "year", "lt"],
        }

class QctFilter(filters.FilterSet):
    tags = MyJsonListFilter(label="tags查询,分隔")

    class Meta:
        model = Qct
        fields = {
            "testitems": ["exact"],
            "defects": ["exact"],
            "qctmat__material": ["exact"],
            "qctmat__use_for_in": ["exact"],
            "qctmat__use_for_out": ["exact"],
            "qctmat__tracing": ["exact"],
        }

class TestItemFilter(filters.FilterSet):
    tags__contains = filters.CharFilter(field_name='tags', lookup_expr='contains')
    mcate_tags__contains = filters.CharFilter(field_name='mcate_tags', lookup_expr='contains')

    class Meta:
        model = TestItem
        fields = ['tags__contains', 'mcate_tags__contains', "type", "process"]


class FtestWorkFilter(filters.FilterSet):
    cbatch = filters.CharFilter(label='批次号', method='filter_cbatch')
    class Meta:
        model = FtestWork
        fields = {
            "material__process__name": ["exact", "contains"],
            "material": ["exact"],
            "wm": ["exact", "isnull"],
            "mb": ["exact", "isnull"],
            "batch": ["exact"],
            "type": ["exact"],
            "type2": ["exact"],
            "shift": ["exact"]           
        }
    
    def filter_cbatch(self, queryset, name, value):
        qs1 = queryset.filter(wm__batch=value)
        qs2 = queryset.filter(mb__batch=value)
        return qs1.union(qs2)

class FtestFilter(filters.FilterSet):
    wpr = filters.CharFilter(label="wprId", method="filter_wpr")
    class Meta:
        model = Ftest
        fields = {
            "type": ["exact"],
            "ftest_work": ["exact"],
            "mlogbw_ftest__wpr": ["exact"],
            "mioitemw_ftest__wpr": ["exact"],
        }

    def filter_wpr(self, queryset, name, value):
        return queryset.filter(Q(mlogbw_ftest__wpr=value) | Q(mioitemw_ftest__wpr=value))