# coding=utf-8
import datetime
from rest_framework import serializers
from .models import Exam, ExamLog, ExamAnswerLog, ExamAnswerOptionLog, ExamAnswerFillLog
from apps.examination.examquestion.models import ExamQuestion
from utils.exceptions import CustomError


class ExamSerializer(serializers.ModelSerializer):
    subject_name = serializers.CharField(source='subject.name', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    question_total_scores = serializers.IntegerField(source='exampaper.question_total_scores', read_only=True)
    passline = serializers.IntegerField(source='exampaper.passline', read_only=True)
    exampaper_name = serializers.CharField(source='exampaper.name', read_only=True)
    examinee_name = serializers.SerializerMethodField()

    class Meta:
        model = Exam
        fields = "__all__"

    def get_examinee_name(self, obj):
        examinees = ExamLog.objects.filter(exam=obj, delete=False).values('user__name')
        examinee_list = []
        for item in examinees:
            if item['user__name']:
                examinee_list.append(item['user__name'])
        if examinee_list:
            return ','.join(examinee_list)
        return ''

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        exam_end_time = validated_data['exam_time'] +  datetime.timedelta(minutes=validated_data['duration'])
        validated_data['exam_end_time'] = exam_end_time
        instance = super(ExamSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if instance.delete:
            raise CustomError(u'考试[%s]已经被删除,禁止操作' % instance.name)
        exam_end_time = validated_data['exam_time'] +  datetime.timedelta(minutes=validated_data['duration'])
        validated_data['exam_end_time'] = exam_end_time
        instance = super(ExamSerializer, self).update(instance, validated_data)
        instance.change_examtime()
        instance.save()
        return instance


class FormalExamLogSerializer(serializers.ModelSerializer):
    exam_name = serializers.CharField(source='exam.name', read_only=True)
    exam_subject_name = serializers.CharField(source='exam.subject.name', read_only=True)
    user_name = serializers.CharField(source='user.name', read_only=True)
    user_department = serializers.CharField(source='user.department.name', read_only=True)
    question_total_scores = serializers.IntegerField(source='exampaper.question_total_scores', read_only=True)
    passline = serializers.IntegerField(source='exampaper.passline', read_only=True)
    single_count = serializers.IntegerField(source='exampaper.single_total_count', read_only=True)
    single_scores = serializers.IntegerField(source='exampaper.single_total_scores', read_only=True)
    multiple_count = serializers.IntegerField(source='exampaper.multiple_total_count', read_only=True)
    multiple_scores = serializers.IntegerField(source='exampaper.multiple_total_scores', read_only=True)
    fill_count = serializers.IntegerField(source='exampaper.fill_total_count', read_only=True)
    fill_scores = serializers.IntegerField(source='exampaper.fill_total_scores', read_only=True)
    judgment_count = serializers.IntegerField(source='exampaper.judgment_total_count', read_only=True)
    judgment_scores = serializers.IntegerField(source='exampaper.judgment_total_scores', read_only=True)

    class Meta:
        model = ExamLog
        fields = "__all__"


class StaffExamLogSerializer(serializers.ModelSerializer):
    exampaper_name = serializers.CharField(source='exampaper.name', read_only=True)
    right_count = serializers.SerializerMethodField()
    wrong_count = serializers.SerializerMethodField()

    class Meta:
        model = ExamLog
        fields = ('id', 'type', 'exampaper', 'user', 'exam_time', 'exampaper_name', 'exam_time', 'submit_time',
                  'scores', 'right_count','wrong_count','rank',)

    def get_right_count(self, obj):
        return obj.single_answer_count + obj.multiple_answer_count + obj.fill_answer_count +  obj.judgment_answer_count

    def get_wrong_count(self, obj):
        return obj.exampaper.question_total_count - (obj.single_answer_count + obj.multiple_answer_count + obj.fill_answer_count +  obj.judgment_answer_count)

class StaffExamLogRetrieveSerializer(serializers.ModelSerializer):
    exampaper_name = serializers.CharField(source='exampaper.name', read_only=True)
    question_total_count = serializers.CharField(source='exampaper.question_total_count', read_only=True)
    question_total_scores = serializers.CharField(source='exampaper.question_total_scores', read_only=True)

    total_right_count = serializers.SerializerMethodField()
    answer_items = serializers.SerializerMethodField()

    class Meta:
        model = ExamLog
        fields = "__all__"

    def get_total_right_count(self, obj):
        return obj.single_answer_count + obj.multiple_answer_count + obj.fill_answer_count +  obj.judgment_answer_count

    def get_answer_items(self, obj):
        data = []
        if obj.exampaper.single_total_count:
            item = {
                'name': '单选题',
                'total_count': obj.exampaper.single_total_count,
                'total_right': obj.single_answer_count,
                'total_scores': obj.exampaper.single_total_scores,
                'answer_scores': obj.single_answer_scores,
            }
            data.append(item)
        if obj.exampaper.multiple_total_count:
            item = {
                'name': '多选题',
                'total_count': obj.exampaper.multiple_total_count,
                'total_right': obj.multiple_answer_count,
                'total_scores': obj.exampaper.multiple_total_scores,
                'answer_scores': obj.multiple_answer_scores,
            }
            data.append(item)
        if obj.exampaper.fill_total_count:
            item = {
                'name': '填空题',
                'total_count': obj.exampaper.fill_total_count,
                'total_right': obj.fill_answer_count,
                'total_scores': obj.exampaper.fill_total_scores,
                'answer_scores': obj.fill_answer_scores,
            }
            data.append(item)
        if obj.exampaper.judgment_total_count:
            item = {
                'name': '判断题',
                'total_count': obj.exampaper.judgment_total_count,
                'total_right': obj.judgment_answer_count,
                'total_scores': obj.exampaper.judgment_total_scores,
                'answer_scores': obj.judgment_answer_scores,
            }
            data.append(item)
        return data


class ExamAnswerLogSimpleSerializer(serializers.ModelSerializer):
    item = serializers.SerializerMethodField()

    class Meta:
        model = ExamAnswerLog
        fields = ('item', )

    def get_item(self, obj):
        if obj.detail.question.type <= ExamQuestion.MULTIPLE:
            rows = ExamAnswerOptionLog.objects.filter(main=obj)
            return ExamAnswerOptionLogSimpleSerializer(rows, many=True).data
        elif obj.detail.question.type == ExamQuestion.FILL:
            rows = ExamAnswerFillLog.objects.filter(main=obj)
            return ExamAnswerFillLogSimpleSerializer(rows, many=True).data
        else:
            return []


class ExamAnswerOptionLogSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExamAnswerOptionLog
        fields = ('option', )


class ExamAnswerFillLogSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExamAnswerFillLog
        fields = ('content', 'order', )
