from django_filters import rest_framework as filters
from apps.mtm.models import Material, Step
from apps.pm.models import SubProductionProgress
from apps.wpm.models import Operation, WProduct

from apps.wpm.services import WpmServies


class SubproductionProgressFilterSet(filters.FilterSet):

    operation = filters.NumberFilter(method='filter_operation')
    class Meta:
        model = SubProductionProgress
        fields = ['material', 'subproduction_plan', 'operation', 'type']

    def filter_operation(self, queryset, name, value):
        operation = Operation.objects.get(pk=value)
        wproducts = WProduct.objects.filter(ow_wproduct__operation=value)
        step = operation.step
        if wproducts.exists():
            subplans = WpmServies.get_subplans_queryset_from_wproducts(wproducts)
        else:
            subplans = WpmServies.get_subplans_queyset_from_step(step)
        queryset = queryset.filter(subproduction_plan__in=subplans)
        if step.type == Step.STEP_TYPE_NOM:
            queryset = queryset.exclude(material__type__in =[Material.MA_TYPE_HALFGOOD, Material.MA_TYPE_GOOD])
        return queryset