from rest_framework import serializers
from .models import CustomUser, InterestTag # 确保 InterestTag 也被导入
from django.contrib.auth.password_validation import validate_password

class InterestTagSerializer(serializers.ModelSerializer):
    class Meta:
        model = InterestTag
        fields = ('id', 'name', 'created_at')
        read_only_fields = ('id', 'created_at')

class UserRegistrationSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        write_only=True,
        required=True,
        validators=[validate_password],
        style={'input_type': 'password'}
    )
    password2 = serializers.CharField(
        write_only=True,
        required=True,
        label="确认密码",
        style={'input_type': 'password'}
    )
    avatar = serializers.ImageField(required=False, allow_null=True, max_length=None, use_url=True)

    class Meta:
        model = CustomUser
        fields = ('email', 'phone_number', 'nickname', 'password', 'password2', 'school', 'bio', 'avatar')
        extra_kwargs = {
            'nickname': {'required': True},
            'school': {'required': False, 'allow_blank': True},
            'bio': {'required': False, 'allow_blank': True},
        }

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({"password2": "两次输入的密码不匹配。"})
        return attrs

    def create(self, validated_data):
        validated_data.pop('password2')
        user = CustomUser.objects.create_user(**validated_data)
        return user

class UserProfileSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()
    interests = serializers.PrimaryKeyRelatedField(
        queryset=InterestTag.objects.all(),
        many=True,
        required=False,
        allow_empty=True
    )

    class Meta:
        model = CustomUser
        fields = (
            'id', 'email', 'phone_number', 'nickname', 
            'avatar', 'avatar_url', 'bio', 'school', 
            'interests',
            'date_joined', 'last_login', 'is_active'
        )
        read_only_fields = ('id', 'email', 'phone_number', 'date_joined', 'last_login', 'avatar_url')

    def get_avatar_url(self, obj):
        request = self.context.get('request')
        if obj.avatar and hasattr(obj.avatar, 'url'):
            if request is not None:
                return request.build_absolute_uri(obj.avatar.url)
            return obj.avatar.url
        return None

class RecommendedUserSerializer(serializers.ModelSerializer): # 新增的序列化器
    """
    用于推荐用户列表中显示用户信息的序列化器。
    """
    avatar_url = serializers.SerializerMethodField()
    common_interests_tags = InterestTagSerializer(many=True, read_only=True, source='common_interests_list') # 假设在视图中注入

    class Meta:
        model = CustomUser
        fields = (
            'id', 
            'nickname', 
            'avatar_url', 
            'school',
            'bio',
            'common_interests_tags',
        )

    def get_avatar_url(self, obj):
        request = self.context.get('request')
        if obj.avatar and hasattr(obj.avatar, 'url'):
            if request is not None:
                return request.build_absolute_uri(obj.avatar.url)
            return obj.avatar.url
        return None
    
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        bio = representation.get('bio')
        if bio and len(bio) > 50: # 截断bio到50字符
            representation['bio'] = bio[:50] + '...'
        return representation