# coding=utf-8

import json
from django.db import transaction
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.decorators import action
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.serializers import ExamPaperSerializer
from apps.examination.exam.models import Exam, ExamLog, ExamAnswerLog
from apps.examination.exam.filters import ExamFilter, FormalExamLogFilter
from apps.examination.exam.serializers import ExamSerializer, FormalExamLogSerializer

class ExamViewSet(CustomModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = Exam.objects.filter(delete=False)
    serializer_class = ExamSerializer

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

    def perform_create(self, serializer):
        super(ExamViewSet, 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(ExamViewSet, 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()

    @action(methods=['post'], detail=True)
    def add_examinee(self, request, pk):
        user_ids = json.loads(request.POST.get('user_ids'))

        with transaction.atomic():
            exam = Exam.getById(pk)
            exam.change_examinee(user_ids)
            exam.save()
            SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'添加考生，id=%d' % exam.id, request.POST.get('user_ids'))
        return response_ok()

    @action(methods=['post'], detail=True)
    def allocation_fixed_exampaper(self, request, pk):
        exampaper_id = request.POST.get('exampaper_id')

        with transaction.atomic():
            exam = Exam.getById(pk)
            exampaper = ExamPaper.getById(exampaper_id)
            exam.allocation_exampaper(Exam.FIXED, exampaper)
            exam.save()
            SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'分配固定试卷，id=%d' % exam.id, request.POST.get('exampaper_id'))
        return response_ok()

    @action(methods=['post'], detail=True)
    def allocation_random_exampaper(self, request, pk):
        data = request.data.copy()

        with transaction.atomic():
            exam = Exam.getById(pk)

            data['name'] = exam.name
            data['type'] = ExamPaper.RANDOM
            data['passline'] = 0
            exampaper_serializer = ExamPaperSerializer(data=data, context={'request': request})
            exampaper_serializer.is_valid(raise_exception=True)
            exampaper = exampaper_serializer.save()
            exampaper.generate_passline()
            exampaper.save()

            exam.allocation_exampaper(Exam.RANDOM, exampaper)
            exam.save()

            data['id'] = exampaper.id
            SysLog.objects.addnew(self.request.user, SysLog.UPDATE, u'分配随机试卷，id=%d' % exam.id, data)
        return response_ok()

    @action(methods=['get'], detail=True)
    def examinee(self, request, pk):
        result = []
        rows = ExamLog.objects.filter(exam_id=pk, delete=False).values('user_id', 'user__username','user__name', 'user__department__name')
        for row in rows:
            item = {
                'id':row['user_id'],
                'username': row['user__username'],
                'name': row['user__name'],
                'department_text': row['user__department__name'],
            }
            result.append(item)
        return response_ok(result)

class ExamLogViewSet(ReadOnlyModelViewSet):
    permission_classes = [IsAdministrator, ]
    queryset = ExamLog.objects.filter(type=ExamLog.FORMAL, delete=False)
    serializer_class = FormalExamLogSerializer

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

    @action(methods=['get'], detail=True)
    def answer_log(self, request, pk):
        rows = ExamAnswerLog.objects.filter(main_id=pk).order_by('detail__order').values_list('status', flat=True)
        return response_ok(list(rows))