# coding=utf-8
from django.db import transaction
from rest_framework.decorators import action
from utils import response_ok

from utils.custom_modelviewset import CustomModelViewSet
from apps.foundation.models import BizLog
from apps.account import tenant_log
from apps.images.models import Images
from apps.customer.models import Customer, CustomerVehicle
from apps.customer.filters import CustomerFilter, CustomerVehicleFilter
from .serializers import CustomerSerializer, CustomerVehicleSerializer


class CustomerViewSet(CustomModelViewSet):
    queryset = Customer.objects.filter()
    serializer_class = CustomerSerializer

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

    def perform_create(self, serializer):
        super(CustomerViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加客户[%s]，id=%d' % (instance.name, instance.id),validated_data)

    @action(methods=['post'], detail=True)
    def update_customer(self, request, pk):
        file = request.FILES.get('image', None)
        user = request.user
        instance = self.get_object()

        with transaction.atomic():
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)

            tenant_log(user, BizLog.UPDATE, u'修改客户[%s]，id=%d' % (instance.name, instance.id), request.data)
            if file:
                old_img = instance.face
                img = Images.objects.employee_addnew(user, Images.CUSTOMER_FACE, file)
                instance.face = img
                instance.save()
                if old_img:
                    old_img.del_images()

        return response_ok()


class CustomerVehicleViewSet(CustomModelViewSet):
    queryset = CustomerVehicle.objects.filter()
    serializer_class = CustomerVehicleSerializer

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