# coding=utf-8

from utils.custom_modelviewset import CustomModelViewSet
from rest_framework.views import APIView
from django.db.models import Q
import traceback
from .models import Poster
from utils.permission import IsTenantUser, permission_required
from .serializer import PosterSerializer
from apps.log.models import BizLog
from apps.tenant import tenant_log
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 = [IsTenantUser, ]
    queryset = Poster.objects.filter()
    serializer_class = PosterSerializer

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

    def perform_create(self, serializer):
        super(PosterViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'添加建筑信息[%s]，id=%d' % (instance.building, instance.id),
                   validated_data)

    def perform_update(self, serializer):
        super(PosterViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.UPDATE, u'修改建筑信息[%s]，id=%d' % (instance.building, instance.id),
                   validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            if instance.area.tenant != request.user.employee.tenant:
                raise CustomError(u'禁止跨租户操作！')
            super(PosterViewSet,self).destroy(self, request, *args, **kwargs)
            tenant_log(self.request.user.employee, BizLog.DELETE, u'删除建筑信息[%s]，id=%d' % (instance.building, instance.id))
        return response_ok()

