# coding=utf-8

from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action
from utils import response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from apps.foundation.models import BizLog, Option
from apps.account import tenant_log
from .filters import *
from .serializers import *
from .models import *


class UsedVehicleViewSet(CustomModelViewSet):
    queryset = UsedVehicle.objects.filter()
    serializer_class = UsedVehicleSerializer

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

    def perform_create(self, serializer):
        super(UsedVehicleViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加二手车[%s]，id=%d' % (instance.number, instance.id),validated_data)

    def perform_update(self, serializer):
        super(UsedVehicleViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.UPDATE, u'修改二手车[%s]，id=%d' % (instance.number, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            tenant_log(self.request.user, BizLog.DELETE, u'删除二手车[%s]，id=%d' % (instance.number, instance.id))
            instance.delete()
        return response_ok()

    @action(methods=['post'], detail=True)
    def sale(self, request, pk):
        order = UsedVehicle.objects.filter(id=pk).first()
        with transaction.atomic():
            if order.status == UsedVehicle.SALE:
                raise CustomError(u'车辆已售出！')
            order.status =  UsedVehicle.SALE
            order.save()
        return response_ok()
