# 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()

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

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

            tenant_log(self.request.user, BizLog.UPDATE, u'修改二手车[%s]，id=%d' % (instance.number, instance.id),
                       request.data)

            if thumbnail:
                old_thumbnail = instance.thumbnail
                thumbnail = Images.objects.employee_addnew(user, Images.USEDVEHICLE_THUMBNAIL, thumbnail)
                instance.thumbnail = thumbnail
                instance.save()
                if old_thumbnail:
                    old_thumbnail.del_images()

        return response_ok()

    @action(methods=['post'], detail=True)
    def set_vehicle_img(self, request, pk):
        # 设置整车图片
        image = request.FILES.get('images', None)
        vehicle = self.get_object()
        if not image:
            raise CustomError(u'未找到上传文件！')

        with transaction.atomic():
            image = Images.objects.employee_addnew(request.user.employee, Images.USEDVEHICLE_FILE, image)
            UsedVehicleImg.objects.create(vehicle_model=vehicle, img=image)
            tenant_log(request.user, BizLog.DELETE,
                       u'二手车[%s]上传图片，id=%d' % (vehicle.number, vehicle.id))

        return response_ok()


class UsedVehicleImageViewSet(CustomModelViewSet):
    queryset = UsedVehicleImg.objects.filter()
    serializer_class = UsedVehicleImgSerializer

    def filter_queryset(self, queryset):
        f = UsedVehicleImgFilter(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 destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            tenant_log(self.request.user, BizLog.DELETE, u'删除二手车[%s]整车图片，id=%d' % (instance.main.number, instance.main_id))
            img = instance.img
            instance.delete()
            img.del_images()
        return response_ok()