# coding=utf-8

from django.db import transaction

from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework import generics

from utils import response_ok
from utils.permission import IsEmployee
from utils.exceptions import CustomError
from utils.custom_modelviewset import CustomModelViewSet

from apps.log.models import BizLog
from apps.images.models import Images
from apps.commodity.models import Commodity, CommodityImage
from apps.commodity.filters import CommodityFilter, CommodityImageFilter
from .serializers import CommoditySerializer, CommodityImageSerializer
from apps.option.models import Option
from apps.base import Formater


class CommodityDict(APIView):
    permission_classes = [IsEmployee, ]

    def get(self, request):
        rows = Option.objects.filter(type=Option.COMMODITY_CATEGORY, enable=True, delete=False).order_by('sort').values('id', 'name')
        data = [{'value': row['id'], 'name': row['name']} for row in rows]
        ret = {
            'category': data
        }
        return response_ok(ret)


class CommodityViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = Commodity.objects.filter(delete=False)
    serializer_class = CommoditySerializer

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

    def perform_create(self, serializer):
        super(CommodityViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'添加商品[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(CommodityViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE, u'修改商品[%s], id=%d' % (instance.name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            BizLog.objects.addnew(self.request.user, BizLog.DELETE, u'删除商品[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_show_image(self, request, pk):
        file = request.FILES.get('banner_img', None)
        user = request.user

        instance = self.get_object()
        if instance.delete:
            raise CustomError(u'该商品已删除，禁止操作！')

        if not file:
            raise CustomError(u'未发现上传文件！')

        with transaction.atomic():
            image = Images.objects._addnew(user, Images.COMMODITY_SHOW_IMAGE, file)
            old_image = instance.show_image
            instance.show_image = image
            instance.save()
            if old_image:
                old_image.del_images()
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_images(self, request, pk):
        type = request.POST.get('type')

        instance = self.get_object()
        with transaction.atomic():
            for i in range(10):
                file = request.data.get('file{}'.format(i))
                if not file:
                    continue
                if type == 'upload_carousel':
                    image = Images.objects._addnew(request.user, Images.COMMODITY_CAROUSEL_IMAGE, file)
                    CommodityImage.objects.create(commodity=instance, type=CommodityImage.CAROUSEL, image=image)
                elif type == 'upload_detail':
                    image = Images.objects._addnew(request.user, Images.COMMODITY_DETAILS_IMAGE, file)
                    CommodityImage.objects.create(commodity=instance, type=CommodityImage.DETAILS, image=image)
        return response_ok()

    @action(methods=['post'], detail=True)
    def query_images(self, request, pk):
        type = request.POST.get('type')
        instance = self.get_object()
        data = []
        rows = CommodityImage.objects.filter(commodity_id=instance.id)
        if type == 'upload_carousel':
            rows = rows.filter(type=CommodityImage.CAROUSEL)
        elif type == 'upload_detail':
            rows = rows.filter(type=CommodityImage.DETAILS)

        for row in rows:
            image_path = row.image.get_path()
            item = {
                'id': row.id,
                'src': image_path,
            }
            data.append(item)
        return response_ok(data)


class DeleteCommodityImageView(generics.DestroyAPIView):
    permission_classes = [IsEmployee, ]

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = CommodityImage.getById(kwargs['pk'])
            image = instance.image
            instance.delete()
            image.del_images()
        return response_ok()
