from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import VerificationCode

User = get_user_model()


class RegisterSerializer(serializers.Serializer):
    """密码注册 serializer"""
    username = serializers.CharField(max_length=150)
    email = serializers.EmailField()
    phone = serializers.CharField(max_length=20)
    password = serializers.CharField(write_only=True, min_length=6)

    def validate_username(self, value):
        """验证用户名是否已存在"""
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError('用户名已存在')
        return value

    def validate_email(self, value):
        """验证邮箱是否已存在"""
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError('邮箱已被注册')
        return value

    def create(self, validated_data):
        """创建用户"""
        user = User.objects.create_user(
            username=validated_data['username'],
            email=validated_data['email'],
            phone=validated_data['phone'],
            password=validated_data['password'],
            role='seeker'
        )
        return user


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'phone', 'role', 'organization']
        read_only_fields = ['role']


class AdminUserSerializer(serializers.ModelSerializer):
    """超管用于创建/管理公司管理员账号"""
    password = serializers.CharField(write_only=True, min_length=6, required=False)

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'phone', 'role', 'organization', 'password', 'is_active']

    def validate(self, attrs):
        if not self.instance and not attrs.get('password'):
            raise serializers.ValidationError({'password': '创建用户时密码为必填项'})
        return attrs

    def create(self, validated_data):
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.save()
        return user

    def update(self, instance, validated_data):
        password = validated_data.pop('password', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        if password:
            instance.set_password(password)
        instance.save()
        return instance


class SendCodeSerializer(serializers.Serializer):
    """发送验证码 serializer"""
    email = serializers.EmailField()

    def validate_email(self, value):
        """验证邮箱是否存在于系统"""
        if not User.objects.filter(email=value).exists():
            raise serializers.ValidationError('该邮箱未在系统中注册')
        return value


class CodeLoginSerializer(serializers.Serializer):
    """邮箱验证码登入 serializer"""
    email = serializers.EmailField()
    code = serializers.CharField(max_length=6, min_length=6)

    def validate(self, attrs):
        """验证邮箱和验证码"""
        email = attrs.get('email')
        code = attrs.get('code')

        # 检查用户是否存在
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            raise serializers.ValidationError('用户不存在')

        # 检查验证码
        try:
            vc = VerificationCode.objects.filter(email=email).latest('created_at')
        except VerificationCode.DoesNotExist:
            raise serializers.ValidationError('请先获取验证码')

        # 检查是否被锁定
        if vc.locked_until:
            from django.utils import timezone
            if timezone.now() < vc.locked_until:
                raise serializers.ValidationError('验证码错误次数过多，请10分钟后重试')

        # 检查验证码是否有效
        if not vc.is_valid():
            raise serializers.ValidationError('验证码已过期或已使用')

        # 验证码是否正确
        if vc.code != code:
            vc.increment_attempts()
            raise serializers.ValidationError('验证码错误')

        attrs['user'] = user
        attrs['vc'] = vc
        return attrs


class PasswordLoginSerializer(serializers.Serializer):
    """邮箱/用户名 + 密码登入 serializer"""
    username = serializers.CharField(required=False, allow_blank=True)
    email = serializers.EmailField(required=False, allow_blank=True)
    password = serializers.CharField()

    def validate(self, attrs):
        """验证用户名/邮箱和密码"""
        username = attrs.get('username')
        email = attrs.get('email')
        password = attrs.get('password')

        if not username and not email:
            raise serializers.ValidationError('请输入用户名或邮箱')

        # 查找用户
        user = None
        if username:
            user = User.objects.filter(username=username).first()
        elif email:
            user = User.objects.filter(email=email).first()

        if not user:
            raise serializers.ValidationError('用户不存在')

        # 验证密码
        if not user.check_password(password):
            raise serializers.ValidationError('密码错误')

        attrs['user'] = user
        return attrs


class ResetPasswordSerializer(serializers.Serializer):
    """请求密码重置 serializer"""
    email = serializers.EmailField()

    def validate_email(self, value):
        """验证邮箱是否存在"""
        if not User.objects.filter(email=value).exists():
            raise serializers.ValidationError('该邮箱未在系统中注册')
        return value


class ConfirmResetPasswordSerializer(serializers.Serializer):
    """确认密码重置 serializer"""
    email = serializers.EmailField()
    code = serializers.CharField(max_length=6, min_length=6)
    new_password = serializers.CharField(write_only=True, min_length=6)

    def validate(self, attrs):
        """验证邮箱、验证码和新密码"""
        email = attrs.get('email')
        code = attrs.get('code')

        # 检查用户是否存在
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            raise serializers.ValidationError('用户不存在')

        # 检查验证码
        try:
            vc = VerificationCode.objects.filter(email=email).latest('created_at')
        except VerificationCode.DoesNotExist:
            raise serializers.ValidationError({'code': '请先获取验证码'})

        # 检查是否被锁定
        if vc.locked_until:
            from django.utils import timezone
            if timezone.now() < vc.locked_until:
                raise serializers.ValidationError('验证码错误次数过多，请10分钟后重试')

        # 检查验证码是否有效
        if not vc.is_valid():
            raise serializers.ValidationError({'code': '验证码已过期或已使用'})

        # 验证码是否正确
        if vc.code != code:
            vc.increment_attempts()
            raise serializers.ValidationError({'code': '验证码错误'})

        attrs['user'] = user
        attrs['vc'] = vc
        return attrs
