# 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 .filters import *
from .serializers import *
from .models import *


class ProductViewSet(CustomModelViewSet):
    queryset = Product.objects.filter(delete=False)
    serializer_class = ProductSerializer

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

    def perform_create(self, serializer):
        super(ProductViewSet, 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_obj(self, request, pk):
        '''由于layui上传文件使用的是post方法，且不能改为put方法，所以不能通过重写update来实现更新实例'''
        obj = self.get_object()
        if obj.delete:
            raise CustomError(u"该商品已删除，禁止修改！")
        with transaction.atomic():
            serializer = self.get_serializer(obj, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            instance = serializer.instance
            validated_data = serializer.validated_data
            tenant_log(self.request.user, BizLog.UPDATE, u'修改商品[%s]，id=%d' % (instance.name, instance.id), validated_data)
        return response_ok()

    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.name, instance.id))
            instance.delete = True
            instance.save()
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_images(self, request, pk):
        instance = self.get_object()
        if instance.delete:
            raise CustomError(u"该商品已删除，禁止修改！")
        images = request.FILES.get('images', None)

        with transaction.atomic():
            image = Images.objects.employee_addnew(self.request.user, Images.PRODUCT_FILE, images)
            ProductImg.objects.create(product=instance, img=image)
            tenant_log(self.request.user, BizLog.INSERT, u'商品[%s]上传图片儿，id=%d' % (instance.name, instance.id))
        return response_ok()


class ProductImageViewSet(CustomModelViewSet):
    queryset = ProductImg.objects.filter()
    serializer_class = ProductImgSerializer

    def filter_queryset(self, queryset):
        f = ProductImageFilter(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.product.name, instance.product.id))
            img = instance.img
            instance.delete()
            img.del_images()
        return response_ok()
