# 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 utils import response_ok, response_error
from utils.exceptions import CustomError
from apps.log.models import BizLog
from .models import Agent,Store
from .serializers import AgentSerializer,StoreSerializer
from .filters import AgentFilter,StoreFilter
from utils.permission import isLogin, permission_required
from apps.agent.serializers import AgentComboboxSerializer,StoreComboboxSerializer

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

    @permission_required('agent.view_agent')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        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 = []
    queryset = Store.objects.filter()
    serializer_class = StoreSerializer

    @permission_required('agent.view_store')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        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()

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

            instance.check_user = self.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):
        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,
        })
