# coding=utf-8
from utils.custom_modelviewset import CustomModelViewSet
from django.db.models import Q
from django.utils import timezone
from rest_framework.views import APIView

from utils import response_ok, response_error
from .models import Agent,Store
from .serializers import AgentSerializer,StoreSerializer
from .filters import AgentFilter,StoreFilter
from utils.permission import isLogin
from apps.agent.serializers import AgentComboboxSerializer,StoreComboboxSerializer

class AgentViewSet(CustomModelViewSet):
    permission_classes = []
    queryset = Agent.objects.filter()
    serializer_class = AgentSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = AgentFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(AgentViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        super(AgentViewSet, self).destroy(self, request, *args, **kwargs)
        return response_ok()

class StoreViewSet(CustomModelViewSet):
    permission_classes = []
    queryset = Store.objects.filter()
    serializer_class = StoreSerializer


    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        f = StoreFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(StoreViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        super(StoreViewSet, self).destroy(self, request, *args, **kwargs)
        return response_ok()

class AgentDictView(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        rows = Agent.objects.filter(Q(create_user=request.user) | Q(id=request.user.agent_id))
        agents = AgentComboboxSerializer(rows, many=True).data
        stores = []
        for row in rows:
            store = Store.objects.filter(agent=row, enable=True, end_date__gte=timezone.now().date())
            store_serializer = StoreComboboxSerializer(store, many=True).data
            stores.extend(store_serializer)
        return response_ok({
            'agents': agents,
            'stores': stores,
        })
