from django_filters import rest_framework as filters
from apps.wpm.models import (SfLog, StLog, WMaterial, Mlog, Mlogbw,
                             Handover, Mgroup, Mlogb, Mtask, BatchSt)
from apps.mtm.models import Route, Material
from django.db.models import Q
from rest_framework.exceptions import ParseError

class SfLogFilter(filters.FilterSet):
    class Meta:
        model = SfLog
        fields = {
            "mgroup": ["exact"],
            "shift": ["exact"],
            "team": ["exact"],
            "leader": ["exact"],
            "team__belong_dept": ["exact"],
            "end_time": ["day", "month", "year", "lt"],
            "start_time": ["gte"]
        }


class StLogFilter(filters.FilterSet):
    class Meta:
        model = StLog
        fields = {
            "mgroup": ["exact"],
            "mgroup__name": ["exact"],
            "start_time": ["day", "month", "year", "gte", "lte"],
            "sflogs__team": ["exact"],
            "end_time": ["isnull"],
            "sflog": ["exact"],
            "sflogs": ["exact"],
            "cate": ["exact"],
        }


class WMaterialFilter(filters.FilterSet):
    mgroupx = filters.CharFilter(label='MgroupId', method='filter_mgroupx')
    tag = filters.CharFilter(label="todo/done", method="filter_tag")
    mtaskx = filters.CharFilter(label='MtaskId', method='filter_mtaskx')
    route = filters.CharFilter(label='routeId', method='filter_route')
    material__process__exclude = filters.CharFilter(field_name="material__process", lookup_expr="exact", exclude=True)

    def filter_mgroupx(self, queryset, name, value):
        return WMaterial.ava_qs(mgroup=Mgroup.objects.get(id=value), qs=queryset)
    
    def filter_tag(self, queryset, name, value):
        mgroupId = self.data.get("mgroup", None)
        mgroupxId = self.data.get("mgroupx", None)
        mgroupId = mgroupId if mgroupId else mgroupxId
        if mgroupId:
            process = Mgroup.objects.get(id=mgroupId).process
            
            queryset = queryset.filter(material__type__in=[Material.MA_TYPE_MAINSO, Material.MA_TYPE_HALFGOOD, Material.MA_TYPE_GOOD])
            if value == "todo":
                matIds = process.get_canin_mat_ids()
                qs = queryset.filter(material__id__in=matIds).exclude(state=WMaterial.WM_REPAIRED)|queryset.filter(state=WMaterial.WM_REPAIR, mgroup__id=mgroupId)
                return qs
            elif value == "done":
                matoutIds = process.get_canout_mat_ids()
                qs = queryset.filter(material__id__in=matoutIds).exclude(state=WMaterial.WM_REPAIR)|queryset.filter(state=WMaterial.WM_REPAIRED, mgroup__id=mgroupId)
            elif value == "canfix":
                matoutIds = process.get_canout_mat_ids()
                qs = queryset.filter(state=WMaterial.WM_REPAIR, mgroup__id=mgroupId)| queryset.filter(material__id__in=matoutIds, state=WMaterial.WM_NOTOK).exclude(
                    state=WMaterial.WM_REPAIR).exclude(state=WMaterial.WM_REPAIRED)
            return qs
        else:
            raise ParseError("请提供工段查询条件")

    def filter_mtaskx(self, queryset, name, value):
        mtask = Mtask.objects.get(id=value)
        if mtask.route and mtask.route.batch_bind:
            return WMaterial.mat_in_qs(mtask=Mtask.objects.get(id=value), qs=queryset.filter(count__gt=0))
        return queryset

    def filter_route(self, queryset, name, value):
        try:
            route = Route.objects.get(id=value)
        except Route.DoesNotExist:
            raise ParseError('生产路线不存在!')
        return queryset.filter(material=route.material_in)|queryset.filter(material__in=route.materials.all())
    
    class Meta:
        model = WMaterial
        fields = {
            "material": ["exact", "in"],
            "state": ["exact", "in"],
            "material__type": ["exact", "in"],
            "material__name": ["exact", "in", "contains"],
            "material__process": ["exact", "in"],
            "material__process__name": ["exact", "contains", "in"],
            "belong_dept": ["exact"],
            "belong_dept__name": ["exact", "in"],
            "batch": ["exact", "contains"],
            "mgroup": ["exact", "in", "isnull"],
            "mgroup__name": ["exact", "in"],
            "count": ["gte", "lte", "exact"],
            "notok_sign": ["exact", "in", "isnull"],
            "count_xtest": ["gte", "isnull"],
            "supplier": ["exact"],
            "defect": ["exact", "isnull"]
        }

class MlogFilter(filters.FilterSet):
    cbatch = filters.CharFilter(label='批次号', method='filter_cbatch')
    cnumber = filters.CharFilter(label='单个编号', method='filter_cnumber')
    class Meta:
        model = Mlog
        fields = {
            "mtask": ["exact", "in"],
            "batch": ["exact"],
            "handle_date": ["exact"],
            "handle_user": ["exact"],
            "mgroup": ["exact"],
            "mtask__mgroup__belong_dept__name": ["exact", "contains", "in"],
            "mgroup__belong_dept__name": ["exact", "in", "contains"],
            "mgroup__name": ["exact", "in", "contains"],
            "submit_time": ["isnull"],
            "fmlog": ["exact"],
            "b_mlog__batch": ["exact"],
            "b_mlog__w_mlogb__number": ["exact"],
        }
    
    def filter_cbatch(self, queryset, name, value):
        qs1 = queryset.filter(batch=value)
        qs2 = queryset.filter(b_mlog__batch=value)
        return qs1.union(qs2)
    
    def filter_cnumber(self, queryset, name, value):
        return queryset.filter(b_mlog__w_mlogb__number=value).distinct()


class HandoverFilter(filters.FilterSet):
    cbatch = filters.CharFilter(label='批次号', method='filter_cbatch')
    mgroup = filters.CharFilter(label='MgroupId', method='filter_mgroup')
    dept = filters.CharFilter(label='DeptId', method='filter_dept')

    def filter_mgroup(self, queryset, name, value):
        return queryset.filter(send_mgroup__id=value)|queryset.filter(recive_mgroup__id=value)
    
    def filter_dept(self, queryset, name, value):
        return queryset.filter(send_dept__id=value)|queryset.filter(recive_dept__id=value)
    
    def filter_cbatch(self, queryset, name, value):
        qs1 = queryset.filter(Q(batch=value)|Q(new_batch=value)|Q(wm__batch=value))
        qs2 = queryset.filter(Q(b_handover__batch=value))
        return qs1.union(qs2)

    class Meta:
        model = Handover
        fields = {
            "id": ["exact"],
            "batch": ["exact", "contains"],
            "material": ["exact", "in"],
            "send_user": ["exact"],
            "send_dept": ["exact"],
            "send_dept__name": ["exact"],
            "recive_dept": ["exact"],
            "recive_dept__name": ["exact"],
            "send_date": ["exact"],
            "material__type": ["exact", "in"],
            "material__process": ["exact", "in"],
            "material__process__name": ["exact", "contains", "in"],
            "submit_time": ["isnull"],
            "mlog": ["isnull"],
            "send_mgroup": ["exact"],
            "send_mgroup__name": ["exact"],
            "recive_mgroup": ["exact"],
            "recive_mgroup__name": ["exact"],
            "type": ["exact", "in"],
            "mtype": ["exact", "in"],
            "b_handover__batch": ["exact"],
            "b_handover__w_handoverb__number": ["exact"]
        }


class MlogbFilter(filters.FilterSet):
    type = filters.CharFilter(label="in/out", method='filter_type')
    class Meta:
        model = Mlogb
        fields = {
            "mlog": ["exact"],
            "mtask": ["exact"],
            "wm_in": ["exact"],
            "mlog__submit_time": ["isnull"],
            "wm_in__state": ["exact"],
            "material_in": ["exact", "isnull"],
            "material_out": ["exact", "isnull"],
        }
    
    def filter_type(self, queryset, name, value):
        if value:
            if value == 'in':
                return queryset.filter(material_in__isnull=False)
            elif value == 'out':
                return queryset.filter(material_out__isnull=False)
            return queryset
        return queryset.none()
    

class BatchStFilter(filters.FilterSet):
    batch__startswith__in = filters.CharFilter(method='filter_batch')
    data__has_key = filters.CharFilter(method='filter_data')

    def filter_data(self, queryset, name, value):
        return queryset.filter(data__has_key=value)

    class Meta:
        model = BatchSt
        fields = {
            "batch": ["exact", "contains", "startswith"],
            "version": ["exact", "gte", "lte"],
            "first_time": ["exact", "gte", "lte", "isnull"],
            "last_time": ["exact", "gte", "lte", "isnull"],
            "update_time": ["exact", "gte", "lte"],
            "material_start": ["exact"],
            "material_start__cate": ["exact"],
            "material_start__type": ["exact"],
            "material_start__process": ["exact"]
        }

    def filter_batch(self, queryset, name, value):
        v_list = value.split(',')
        query = Q()
        for value in v_list:
            query |= Q(batch__startswith=value)
        return queryset.filter(query)
    

class MlogbwFilter(filters.FilterSet):
    type = filters.CharFilter(label="in/out", method='filter_type')
    class Meta:
        model = Mlogbw
        fields = {
            "mlogb": ["exact"],
            "mlogb__mlog": ["exact"],
            "mlogb__mlog__mgroup": ["exact"],
            "mlogb__mlog__submit_time": ["isnull"],
            "wpr": ["exact"],
            "ftest": ["isnull"],
            "ftest__is_ok": ["exact"],
            "ftest__defect_main": ["exact"]
        }

    def filter_type(self, queryset, name, value):
        if value:
            if value == 'in':
                return queryset.filter(mlogb__material_in__isnull=False)
            elif value == 'out':
                return queryset.filter(mlogb__material_out__isnull=False)
            return queryset
        return queryset.none()