from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from console.learningcenter.models import KnowledgePoint, KnowledgeRepository


# 知识点列表展示与删除
class KnowledgeListSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = KnowledgePoint
        fields = ('id', 'title', 'operator', 'updated_time')


# 创建与更新
class KnowledgePointSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    knowledge_warehouse_name = serializers.SerializerMethodField()

    def get_knowledge_warehouse_name(self, obj):
        return KnowledgeRepositorySerializer(
            obj.knowledge_warehouse_type).data['name']

    class Meta:
        model = KnowledgePoint
        fields = ('id', 'title', 'abstract', 'text', 'knowledge_type',
                  'is_key_knowledge', 'knowledge_warehouse_type',
                  'cover_picture', 'operator', 'visit_nums', 'updated_time',
                  'knowledge_warehouse_name')

    def create(self, validated_data):

        return KnowledgePoint.objects.create(**validated_data)


# 知识库
class KnowledgeRepositorySerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = KnowledgeRepository
        fields = ('id', 'name', 'is_hot', 'updated_time', 'operator')

    def create(self, validated_data):
        return KnowledgeRepository.objects.create(**validated_data)


# 小程序知识点列表
class MiniKnowledgeListSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = KnowledgePoint
        fields = ('id', 'title', 'abstract')


# 小程序新闻列表
class MiniNewsListSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = KnowledgePoint
        fields = ('id', 'title', 'updated_time', 'visit_nums', 'cover_picture')
