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

from utils import response_ok, response_error
from utils.exceptions import CustomError
from apps.log.models import BizLog
from .models import GeneralAgent, Agent, Store
from .serializers import GeneralAgentSerializer, AgentSerializer, StoreSerializer
from .filters import GeneralAgentFilter, AgentFilter, StoreFilter
from utils.permission import isLogin, check_permission, permission_required
from apps.agent.serializers import AgentComboboxSerializer, StoreComboboxSerializer, GeneralAgentComboboxSerializer

class GeneralAgentViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = GeneralAgent.objects.filter()
    serializer_class = GeneralAgentSerializer

    @permission_required('agent.view_agent')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        if self.request.user.general_agent:
            queryset = queryset.filter(id=self.request.user.general_agent.id)
        f = GeneralAgentFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('agent.add_general_agent')
    def perform_create(self, serializer):
        super(GeneralAgentViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加总代理[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('agent.delete_general_agent')
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除总代理[%s]，id=%d' % (instance.name, instance.id))
        super(GeneralAgentViewSet, self).perform_destroy(instance)
        return response_ok()


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

    @permission_required('agent.view_agent')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(Q(general_agent__create_user=self.request.user)
                                   | Q(create_user=self.request.user))
        f = AgentFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('agent.add_agent')
    def perform_create(self, serializer):
        super(AgentViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加代理商[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('agent.delete_agent')
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除代理商[%s]，id=%d' % (instance.name, instance.id))
        super(AgentViewSet, self).perform_destroy(instance)
        return response_ok()


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

    @permission_required('agent.view_store')
    def filter_queryset(self, queryset):
        queryset = queryset.filter(id__in=self.request.user.get_manager_range())
        f = StoreFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('agent.add_store')
    def perform_create(self, serializer):
        super(StoreViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加门店[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('agent.delete_store')
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除门店[%s]，id=%d' % (instance.name, instance.id))
        super(StoreViewSet, self).perform_destroy(instance)
        return response_ok()

    @action(methods=['post'], detail=True)
    def check(self, request, pk):
        # 审核
        check_permission(request, 'agent.check_store')
        status = request.POST.get('status')
        try:
            with transaction.atomic():
                instance = Store.objects.filter(id=pk).first()
                if not instance:
                    raise CustomError('当前门店信息有误！')
                if instance.status > settings.DEFAULT:
                    raise CustomError('当前企业已审核！')

                instance.check_user = request.user
                instance.status = status
                instance.check_time = timezone.now()
                instance.save()
                BizLog.objects.addnew(request.user, BizLog.INSERT,
                                      u'审核门店[%s]状态为[%s],id=%d' % (instance.name, status, instance.id))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('审核完成！')


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

    def get(self, request):
        general_agent_rows = GeneralAgent.objects.filter(
            Q(create_user=request.user) | Q(id=request.user.general_agent_id))
        general_agents = GeneralAgentComboboxSerializer(general_agent_rows, many=True).data
        agents = stores = []
        for general_agent_row in general_agent_rows:
            rows = Agent.objects.filter(general_agent=general_agent_row,)
            if request.user.agent:
                rows = rows.filter(id=request.user.agent.id)
            agents = AgentComboboxSerializer(rows, many=True).data
            stores = []

            for row in rows:
                store = Store.objects.filter(agent=row, enable=True, check_user__isnull=False, end_date__gte=timezone.now().date())
                if request.user.store:
                    store = store.filter(id=request.user.store.id)
                store_serializer = StoreComboboxSerializer(store, many=True).data
                stores.extend(store_serializer)
        return response_ok({
            'general_agents': general_agents,
            'agents': agents,
            'stores': stores,
        })
