# coding=utf-8
import json
from django.db.models import Sum, F
from rest_framework.decorators import action
from rest_framework.views import APIView
from django.db import transaction
from rest_framework.viewsets import ReadOnlyModelViewSet
from django.db.models import Q
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_ok, response_error
from utils.permission import IsAdministrator
from apps.examination.examquestion.serializers import *
from apps.examination.examquestion.filters import *
from apps.system.models import SysLog

class ExamQuestionViewSet(CustomModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = ExamQuestion.objects.filter(delete=False)
    serializer_class = ExamQuestionSerializer

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

    def perform_create(self, serializer):
        super(ExamQuestionViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.INSERT, u'添加试题库试题，id=%d' % (instance.id), validated_data)

    def perform_update(self, serializer):
        super(ExamQuestionViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'修改试题库试题，id=%d' % (instance.id), validated_data)

        if 'feedback' in self.request.data and self.request.data['feedback']:
            feedback = ExamQuestionFeedback.getById(self.request.data['feedback'])
            feedback.process(self.request.user)
            feedback.save()
            SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'处理试题错误反馈，id=%d' % (feedback.id))

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            SysLog.objects.addnew(request.user, SysLog.INSERT, u"删除试题库试题,id=%d" % instance.id)
        return response_ok()

class ExamQuestionFeedbackViewSet(ReadOnlyModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = ExamQuestionFeedback.objects.filter().order_by('status', '-id')
    serializer_class = ExamQuestionFeedbackSerializer

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