from rest_framework import serializers
from .models import Organization


class OrganizationSerializer(serializers.ModelSerializer):
    job_count = serializers.SerializerMethodField()
    edu_summary = serializers.SerializerMethodField()

    class Meta:
        model = Organization
        fields = ['id', 'name', 'parent', 'logo', 'description', 'email', 'is_active', 'job_count', 'edu_summary']

    def get_job_count(self, obj):
        return obj.jobs.filter(status='published').count()

    def get_edu_summary(self, obj):
        """每个学历的招聘总人数"""
        from django.db.models import Sum
        jobs = obj.jobs.filter(status='published')
        result = []
        for edu in ['博士', '硕士', '本科及以下']:
            total = jobs.filter(education=edu).aggregate(s=Sum('headcount'))['s'] or 0
            if total > 0:
                result.append({'education': edu, 'count': total})
        return result


class OrganizationTreeSerializer(serializers.ModelSerializer):
    """带子公司列表，用于门户展示"""
    children = serializers.SerializerMethodField()
    job_count = serializers.SerializerMethodField()
    jobs_by_education = serializers.SerializerMethodField()

    class Meta:
        model = Organization
        fields = ['id', 'name', 'logo', 'description', 'email', 'job_count', 'children', 'jobs_by_education']

    def get_job_count(self, obj):
        return obj.jobs.filter(status='published').count()

    def get_children(self, obj):
        return OrganizationSerializer(
            obj.children.filter(is_active=True), many=True, context=self.context
        ).data

    def get_jobs_by_education(self, obj):
        from apps.jobs.models import Job
        org_ids = [obj.id] + list(obj.children.filter(is_active=True).values_list('id', flat=True))
        jobs = Job.objects.filter(organization_id__in=org_ids, status='published').values('title', 'education', 'headcount')
        result = []
        for edu in ['博士', '硕士', '本科及以下']:
            edu_jobs = [{'title': j['title'], 'headcount': j['headcount']} for j in jobs if j['education'] == edu]
            if edu_jobs:
                result.append({'education': edu, 'jobs': edu_jobs})
        return result
