# coding=utf-8

from django.db import transaction
from rest_framework.decorators import action

from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsCustomer
from utils.custom_modelviewset import CustomModelViewSet
from apps.customer.models import CustomerAddress
from apps.customer.filters import CustomerAddressFilter
from apps.customer.address.serializers import AddressSerializer
from apps.log.models import BizLog


class CustomerAddressViewSet(CustomModelViewSet):
    permission_classes = [IsCustomer, ]
    queryset = CustomerAddress.objects.filter(delete=False)
    serializer_class = AddressSerializer

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

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)

    def perform_create(self, serializer):
        super(CustomerAddressViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(instance.customer.user, BizLog.INSERT, u'客户添加收货地址,id=%d' % instance.id, validated_data)

    def perform_update(self, serializer):
        super(CustomerAddressViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(instance.customer.user, BizLog.UPDATE, u'客户修改收货地址,id=%d' % instance.id, validated_data)

    def perform_destroy(self, instance):
        queryset = self.get_queryset().filter(customer=self.request.customer).exclude(id=instance.id)
        instance.destory(queryset)
        BizLog.objects.addnew(instance.customer.user, BizLog.DELETE, u'客户删除收货地址,id=%d' % instance.id)

    @action(methods=['get'], detail=True)
    def set_default(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            self.get_queryset().filter(customer=self.request.customer, default=True).update(default=False)
            instance.default = True
            instance.save()
            BizLog.objects.addnew(instance.customer.user, BizLog.UPDATE, u'客户设置默认收货地址,id=%d' % instance.id)
        return response_ok()
