from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework import serializers as serializer
from console.organizations.models import Organization


class OrganizationCreateSerializer(serializer.Serializer):
    name = serializer.CharField(required=True,
                                allow_null=False,
                                allow_blank=False,
                                help_text="名称")
    parent_id = serializer.IntegerField(required=False,
                                        allow_null=True,
                                        help_text="上级部门id")
    enterprise_id = serializer.IntegerField(required=False,
                                            help_text="公司id",
                                            allow_null=True)

    def create(self, validated_data):
        organization = Organization.objects.create(
            name=validated_data.get("name"),
            enterprise_id=validated_data.get("enterprise_id"),
            parent_id=validated_data.get("parent_id"))
        return organization

    def validate(self, attrs):
        attrs["enterprise_id"] = self.context.get("enterprise_id")
        return attrs


class OrganizationListSerializer(ModelSerializer):
    class Meta:
        model = Organization
        fields = ("id", "name", "children")

    def to_representation(self, instance):
        return instance.get_relation_repr()


class OrganizationInfoSerializer(ModelSerializer):
    parent = serializer.SerializerMethodField()

    def get_parent(self, obj):
        return

    class Meta:
        model = Organization
        fields = ("id", "name", "parent")


class OrganizationAccsSerializer(ModelSerializer):
    id = SerializerMethodField()
    name = SerializerMethodField()
    childrens = SerializerMethodField()
