# coding=utf-8
import json
from rest_framework import serializers
from utils.exceptions import CustomError
from .models import *

class ExamQuestionSerializer(serializers.ModelSerializer):
    subject = serializers.CharField(source='chapter.subject.id', read_only=True)
    subject_text = serializers.CharField(source='chapter.subject.name', read_only=True)
    chapter_text = serializers.CharField(source='chapter.name', read_only=True)
    create_user_text = serializers.CharField(source='create_user.username', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    difficulty_text = serializers.CharField(source='get_difficulty_display', read_only=True)
    judgment = serializers.SerializerMethodField()
    items = serializers.SerializerMethodField()

    def get_items(self, obj):
        if obj.type == ExamQuestion.SINGLE or obj.type == ExamQuestion.MULTIPLE:
            rows = ExamQuestionOption.objects.filter(main=obj, delete=False)
            return ExamQuestionOptionSerializer(rows,many=True).data
        elif obj.type == ExamQuestion.FILL:
            rows = ExamQuestionFill.objects.filter(main=obj, delete=False)
            return ExamQuestionFillSerializer(rows, many=True).data
        else:
            return []

    def get_judgment(self, obj):
        if obj.judgment:
            return "1"
        return "0"

    class Meta:
        model = ExamQuestion
        fields = '__all__'

    def create(self, validated_data):
        if 'judgment' in self.initial_data:
            validated_data['judgment'] = True if self.initial_data['judgment'] == '1' else False
        validated_data['create_user'] = self.context['request'].user
        instance = super(ExamQuestionSerializer, self).create(validated_data)
        rows = json.loads(self.initial_data['rows'])
        for row in rows:
            if not row['content']:
                raise CustomError('答案不能为空，请填写答案！')
            if instance.type == ExamQuestion.SINGLE or instance.type == ExamQuestion.MULTIPLE:
                ExamQuestionOption.objects.create(
                    main=instance,
                    content=row['content'],
                    right=row['right'],
                )
            elif instance.type == ExamQuestion.FILL:
                ExamQuestionFill.objects.create(
                    main=instance,
                    content=row['content'],
                    order=row['order'],
                )
        return instance

    def update(self, instance, validated_data):
        if 'judgment' in self.initial_data:
            validated_data['judgment'] = True if self.initial_data['judgment'] == '1' else False
        instance = super(ExamQuestionSerializer, self).update(instance, validated_data)
        rows = json.loads(self.initial_data['rows'])
        ExamQuestionOption.objects.filter(main=instance).update(delete=True, right=False)
        for row in rows:
            if not row['content']:
                raise CustomError('答案不能为空，请填写答案！')
            if instance.type == ExamQuestion.SINGLE or instance.type == ExamQuestion.MULTIPLE:
                if row['id']:
                    # 更新
                    ExamQuestionOption.objects.filter(main=instance, id=row['id']).update(delete=False,
                                                                                          content=row['content'],
                                                                                          right=row['right'])
                else:
                    # 新增
                    ExamQuestionOption.objects.create(
                        main=instance,
                        content=row['content'],
                        right=row['right'],
                    )
            elif instance.type == ExamQuestion.FILL:
                ExamQuestionFill.objects.filter(main=instance).update(delete=True)
                if row['id']:
                    # 更新
                    ExamQuestionFill.objects.filter(main=instance, id=row['id']).update(delete=False,
                                                                                        content=row['content'],
                                                                                        order=row['order'])
                else:
                    # 新增
                    ExamQuestionFill.objects.create(
                        main=instance,
                        content=row['content'],
                        order=row['order'],
                    )
        return instance

class ExamQuestionOptionSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExamQuestionOption
        fields = '__all__'

class ExamQuestionFillSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExamQuestionFill
        fields = '__all__'
