# coding=utf-8

from utils.custom_modelviewset import CustomModelViewSet
from rest_framework.views import APIView
from django.db.models import Q
import traceback
from rest_framework.decorators import action
import json
from apps.tenant.poster.models import Poster
from utils.permission import IsTenantUser, IsAdministratorUser
from apps.tenant.poster.serializer import PosterSerializer
from apps.log.models import BizLog
from apps.tenant import tenant_log
from apps.tenant.poster.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()
        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')
        with transaction.atomic():
            data['create_user'] = request.user
            poster = Poster.objects.create(**data)
            poster._add_img(banner_img)
            BizLog.objects.addnew(None, request.user, BizLog.INSERT, u'添加轮播信息', data)
        return response_ok()

    @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:
            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)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()
