# coding=utf-8

from django.db import transaction
from rest_framework.views import APIView
from utils.permission import IsAdministrator
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SysLog

from apps.examination.exampaper.models import ExamPaper
from apps.examination.exampaper.filters import ExamPaperFilter
from apps.examination.exampaper.serializers import ExamPaperSerializer


class ExamPaperViewSet(CustomModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = ExamPaper.objects.filter(delete=False)
    serializer_class = ExamPaperSerializer

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

    def perform_create(self, serializer):
        super(ExamPaperViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.INSERT, u'添加试卷[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(ExamPaperViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.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()
            SysLog.objects.addnew(self.request.user, SysLog.DELETE, u'删除试卷[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()