from django_filters import rest_framework as filters
from apps.hrm.models import Certificate, ClockRecord, Employee, NotWorkRemark


class ClockRecordFilterSet(filters.FilterSet):
    start_create = filters.DateTimeFilter(
        field_name="create_time", lookup_expr='gte')
    end_create = filters.DateTimeFilter(
        field_name="create_time", lookup_expr='lte')
    year = filters.NumberFilter(method='filter_year')
    month = filters.NumberFilter(method='filter_month')

    class Meta:
        model = ClockRecord
        fields = {
            'employee': ['exact'],
            'type': ['exact', 'in'],
            'employee__type': ['exact', 'in'],
            'employee__belong_dept': ['exact'],
            'clock_time': ['gte', 'lte']
        }
        # fields = ['employee', 'start_create', 'end_create', 'year', 'month', 'type', 'employee__type', 'employee__belong_dept']

    def filter_year(self, queryset, name, value):
        return queryset.filter(create_time__year=value)

    def filter_month(self, queryset, name, value):
        return queryset.filter(create_time__month=value)


class EmployeeFilterSet(filters.FilterSet):
    has_blt = filters.BooleanFilter(method='filter_has_blt')

    class Meta:
        model = Employee
        fields = {
            'job_state': ['exact'],
            'show_atwork': ['exact'],
            'type': ['exact', 'in'],
            'belong_dept': ['exact']
        }

    def filter_has_blt(self, queryset, name, value):
        if value:
            return queryset.exclude(blt__isnull=True)
        else:
            return queryset.filter(blt=None)


class NotWorkRemarkFilterSet(filters.FilterSet):
    year = filters.NumberFilter(method='filter_year')
    month = filters.NumberFilter(method='filter_month')

    class Meta:
        model = NotWorkRemark
        fields = ['year', 'month', 'user']

    def filter_year(self, queryset, name, value):
        return queryset.filter(not_work_date__year=value)

    def filter_month(self, queryset, name, value):
        return queryset.filter(not_work_date__month=value)


class CertificateFilterSet(filters.FilterSet):

    class Meta:
        model = Certificate
        fields = {
            'employee': ['exact'],
            'employee__name': ['exact', 'contains'],
            'employee__user': ['exact'],
            'employee__type': ['exact', 'in'],
            'type': ['exact'],
            "state": ['exact'],
        }
