# coding=utf-8

from rest_framework import serializers
from .models import KnowledgeBase, KnowledgeBaseFeedback
from utils.exceptions import CustomError

class KnowledgeBaseSerializer(serializers.ModelSerializer):
    subject_name = serializers.CharField(source='chapter.subject.name', read_only=True)
    subject = serializers.CharField(source='chapter.subject.id', read_only=True)
    chapter_name = serializers.CharField(source='chapter.name', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)

    class Meta:
        model = KnowledgeBase
        fields = "__all__"

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        instance = super(KnowledgeBaseSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if instance.delete:
            raise CustomError(u'知识[%s]已经被删除,禁止操作' % instance.name)
        instance = super(KnowledgeBaseSerializer, self).update(instance, validated_data)
        return instance

class KnowledgeBaseFeedbackSerializer(serializers.ModelSerializer):
    subject_name = serializers.CharField(source='main.chapter.subject.name', read_only=True)
    chapter_name = serializers.CharField(source='main.chapter.name', read_only=True)
    name = serializers.CharField(source='main.name', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)

    class Meta:
        model = KnowledgeBaseFeedback
        fields = "__all__"

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        instance = super(KnowledgeBaseFeedbackSerializer, self).create(validated_data)
        return instance
