# coding=utf-8

from utils.custom_modelviewset import CustomModelViewSet
from rest_framework.decorators import action
import json
import traceback
from .models import Poster
from utils.permission import IsAdministratorUser
from .serializer import PosterSerializer
from apps.log.models import BizLog
from .filters import PosterFilter
from django.db import transaction
from utils.exceptions import CustomError
from utils import response_ok, response_error


class PosterViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = Poster.objects.filter()
    serializer_class = PosterSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = PosterFilter(self.request.GET, queryset=queryset)
        return f.qs

    def create(self, request, *args, **kwargs):
        data = json.loads(request.POST.get('data'))
        banner_img = request.FILES.get('banner_img')
        try:
            with transaction.atomic():
                data['create_user'] = request.user
                tenant = request.user.employee.tenant
                posters = Poster.objects.filter(tenant=tenant, enable=True).count()
                if posters >= 2:
                    raise CustomError(u'只能添加2个在用的轮播！')
                data['tenant'] = tenant
                poster = Poster.objects.create(**data)
                poster._add_img(banner_img,request.user)
                BizLog.objects.addnew(tenant, request.user, BizLog.INSERT, u'添加轮播信息', data)
            return response_ok()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def update_poster(self, request, pk):
        data = json.loads(request.POST.get('data'))
        # data = {'title': '644', 'content': '发斯蒂芬44', 'location': '1', 'enable': '1'}
        banner_img = request.FILES.get('banner_img')
        try:
            if data['enable']:
                tenant = request.user.employee.tenant
                posters = Poster.objects.filter(tenant=tenant, enable=True).exclude(id=pk).count()
                if posters >= 2:
                    raise CustomError(u'只能添加2个在用的轮播！')
            with transaction.atomic():
                Poster.objects.filter(id=pk).update(**data)
                poster = self.get_object()
                if banner_img:
                    poster.del_images()
                    poster._add_img(banner_img,request.user)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

