from django_filters import rest_framework as filters
from apps.wpm.models import (Handoverbw, Mlogbw)
from apps.inm.models import MIOItemw
from apps.wpmw.models import Wpr
from apps.mtm.models import Route, Material
from django.db.models import Q
from rest_framework.exceptions import ParseError


class WprFilter(filters.FilterSet):
    can_use = filters.CharFilter(method='filter_can_use')
    class Meta:
        model = Wpr
        fields = {
            "mb": ["exact", "isnull"],
            "wm": ["exact", "isnull"],
            "material__process": ["exact"],
            "state": ["exact"],
            "defects": ["exact"],
            "number": ["exact"]
        }

    def filter_can_use(self, queryset, name, value):
        if value == 'yes':
            # 交接记录
            handoverws = Handoverbw.objects.filter(handoverb__handover__submit_time__isnull=True)
            if self.data.get("wm"):
                handoverws = handoverws.filter(handoverb__wm=self.data.get("wm"))
            handoverws = handoverws.values_list('wpr__id', flat=True)
            # 生产日志
            mlogbws = Mlogbw.objects.filter(mlogb__mlog__submit_time__isnull=True)
            if self.data.get("wm"):
                mlogbws = mlogbws.filter(mlogb__wm_in=self.data.get("wm"))
            mlogbws = mlogbws.values_list('wpr__id', flat=True)
            # 出入库记录
            mioitemws = MIOItemw.objects.filter(mioitem__mio__submit_time__isnull=True)
            if self.data.get("wm"):
                mioitemws = mioitemws.filter(mioitem__wm=self.data.get("wm"))
            if self.data.get("mb"):
                mioitemws = mioitemws.filter(mioitem__mb=self.data.get("mb"))
            mioitemws = mioitemws.values_list('wpr__id', flat=True)
            return queryset.exclude(id__in=handoverws).exclude(id__in=mlogbws).exclude(id__in=mioitemws)
        return queryset