# coding=utf-8
import django_filters
from django.utils import timezone
from .models import ReportCustomer, NewCustomer, Review, NewCustomerRemind


class ReportCustomerFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    tel = django_filters.CharFilter(field_name='tel', lookup_expr='icontains')

    class Meta:
        model = ReportCustomer
        fields = '__all__'


class NewCustomerFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
    tel = django_filters.CharFilter(field_name='tel', lookup_expr='icontains')
    param = django_filters.CharFilter(method='param_filter')
    count_param = django_filters.CharFilter(method='count_param_filter')

    def param_filter(self, queryset, name,value):
        param = value.split('_')
        if param[0] == 'store':
            queryset = queryset.filter(store_id=param[1])
        elif param[0] == 'user':
            customer_ids = NewCustomerRemind.objects.filter(remind_user_id=param[1]).values_list('customer_id',flat=True)
            queryset = queryset.filter(id__in=customer_ids)
        elif param[0] == 'agent':
            queryset = queryset.filter(store__agent_id=param[1])
        elif param[0] == 'general_agent':
            queryset = queryset.filter(store__agent__general_agent_id=param[1])
        return queryset

    def count_param_filter(self, queryset, name,value):
        # 查询主跟踪人
        today = timezone.now().date()
        if value == 'today':
            queryset = queryset.filter(next_time=today)
        elif value == 'overdue':
            queryset = queryset.filter(next_time__lt=today)
        return queryset

    class Meta:
        model = NewCustomer
        fields = '__all__'


class ReviewFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(field_name='customer__name', lookup_expr='icontains')
    tel = django_filters.CharFilter(field_name='customer__tel', lookup_expr='icontains')

    class Meta:
        model = Review
        fields = '__all__'
