# coding=utf-8
from django.db import transaction

from utils import response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils.permission import IsTenantUser
from apps.tenant import tenant_log
from apps.log.models import BizLog
from .serializers import NoticesSerializer
from .models import Notices
from .filters import NoticesFilter


class NoticesViewSet(CustomModelViewSet):
    permission_classes = [IsTenantUser, ]
    serializer_class = NoticesSerializer
    queryset = Notices.objects.filter()

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

    def perform_create(self, serializer):
        super(NoticesViewSet, 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.title, instance.id),
                   validated_data)

    def perform_update(self, serializer):
        super(NoticesViewSet, 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.title, instance.id),
                   validated_data)

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