"""
管理员模块序列化器
"""
from rest_framework import serializers
from .models import AdminUser


class AdminUserSerializer(serializers.ModelSerializer):
    """管理员用户序列化器"""
    
    role_display = serializers.CharField(source='get_role_display', read_only=True)
    
    class Meta:
        model = AdminUser
        fields = ['id', 'username', 'name', 'email', 'phone', 'role', 'role_display', 
                  'is_active', 'last_login_ip', 'created_at']
        read_only_fields = ['id', 'last_login_ip', 'created_at']


class AdminLoginSerializer(serializers.Serializer):
    """管理员登录序列化器"""
    
    username = serializers.CharField(max_length=50, help_text='用户名')
    password = serializers.CharField(max_length=128, write_only=True, help_text='密码')


class AdminChangePasswordSerializer(serializers.Serializer):
    """管理员修改密码序列化器"""
    
    old_password = serializers.CharField(max_length=128, write_only=True)
    new_password = serializers.CharField(max_length=128, write_only=True)
    
    def validate_new_password(self, value):
        if len(value) < 6:
            raise serializers.ValidationError('密码长度不能少于6位')
        return value


class CreateAdminUserSerializer(serializers.ModelSerializer):
    """创建管理员序列化器"""
    
    password = serializers.CharField(max_length=128, write_only=True)
    
    class Meta:
        model = AdminUser
        fields = ['username', 'password', 'name', 'email', 'phone', 'role']
    
    def create(self, validated_data):
        password = validated_data.pop('password')
        admin = AdminUser(**validated_data)
        admin.set_password(password)
        admin.save()
        return admin
