from rest_framework import serializers
from .models import Article, Material, Source, Threshold, CompanyInfo, ChildrenCompany
from utils.constants import EXCLUDE_FIELDS_BASE


class ArticelSerializer(serializers.ModelSerializer):
    """
    文章序列化
    """
    class Meta:
        model = Article
        fields = '__all__'

class ArticelListSerializer(serializers.ModelSerializer):
    """
    文章列表序列化
    """
    class Meta:
        model = Article
        exclude = ('content',)

class MaterialSerializer(serializers.ModelSerializer):
    vid = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Material
        fields = '__all__'

    def get_vid(self, obj):
        if obj.type == '视频':
            return obj.path.split('/')[-1].replace('.html', '')
        else:
            return ''

class SourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Source
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_BASE


class ThresholdSerializer(serializers.ModelSerializer):
    source_ = SourceSerializer(source='source', read_only=True)
    class Meta:
        model = Threshold
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_BASE


class PathSerializer(serializers.Serializer):
    path = serializers.CharField(label='文件地址')



class CompanyInfoSerializer(serializers.ModelSerializer):
    # children_companies = serializers.SerializerMethodField()
    class Meta:
        model = CompanyInfo
        fields = '__all__'

    # def get_children_companies(self, obj):
    #     children = ChildrenCompany.objects.filter(parent_company=obj)
    #     return ChildrenCompanySerializer(children, many=True).data

    def create(self, validated_data):
        instance = super().create(validated_data)  
        instance.sum_points = validated_data["edu_points"] + validated_data["co_sponsor_points"]
        instance.save()
        return instance

     

class ChildrenCompanySerializer(serializers.ModelSerializer):
    parent_company_name = serializers.StringRelatedField(source='parent_company.company_name', read_only=True)
    class Meta:
        model = ChildrenCompany
        fields = '__all__'
    
    def create(self, validated_data):
        instance = super().create(validated_data)
        parent_company = instance.parent_company
        children = ChildrenCompany.objects.filter(parent_company=parent_company)

        total_edu = sum(c.child_edu_points or 0 for c in children)
        total_sponsor = sum(c.child_co_sponsor_points or 0 for c in children) 
        # 加上未保存的分数
        parent_company.edu_points = total_edu
        parent_company.co_sponsor_points = total_sponsor
        parent_company.sum_points = parent_company.edu_points + parent_company.co_sponsor_points
        parent_company.save()
        return instance
