# 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.order.models import ShoppingCart
from apps.order.filters import ShoppingCartFilter
from apps.customer.order.serializers import ShoppingCartSerializer
from apps.log.models import BizLog


class ShoppingCartViewSet(CustomModelViewSet):
    permission_classes = [IsCustomer, ]
    queryset = ShoppingCart.objects.filter()
    serializer_class = ShoppingCartSerializer

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

    def perform_create(self, serializer):
        super(ShoppingCartViewSet, self).perform_create(serializer)

    @action(methods=['post'], detail=True)
    def update_quantity(self, request, pk):
        quantity = request.POST.get('quantity')
        try:
            quantity = int(quantity)
        except:
            raise CustomError(u'商品数量错误，请修改！')
        if quantity <= 0:
            raise CustomError(u'请输入正确的商品数量！')
        with transaction.atomic():
            instance = ShoppingCart.objects.filter(id=pk, customer=request.customer).first()
            if instance:
                instance.quantity = quantity
                instance.save()
        return response_ok()

    @action(methods=['post'], detail=False)
    def del_cart(self, request):
        car_ids = request.POST.get('ids').split(',')
        with transaction.atomic():
            ShoppingCart.objects.filter(id__in=car_ids, customer=request.customer).delete()
        return response_ok()
