from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db.models import Q


class RegisterForm(forms.Form):
    username = forms.CharField(
        max_length=150,
        widget=forms.TextInput(attrs={
            'placeholder': '请输入用户名',
            'class': 'form-control form-control-lg'
        }))
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
            'placeholder': '请输入有效邮箱',
            'class': 'form-control form-control-lg'
        }))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': '请输入密码',
            'class': 'form-control form-control-lg'
        }))
    password_confirm = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'placeholder': '请再次输入密码',
            'class': 'form-control form-control-lg'
        }))
    captcha = CaptchaField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 专门为验证码字段设置样式
        if 'captcha' in self.fields:
            # 为验证码输入框添加Bootstrap样式
            self.fields['captcha'].widget.attrs.update({
                'class':
                'form-control form-control-lg captcha-input',
                'placeholder':
                '请输入图片中的验证码',
                'style':
                'max-width: 200px; display: inline-block;'
            })

    def clean_password_confirm(self):
        password = self.cleaned_data.get('password')
        password_confirm = self.cleaned_data.get('password_confirm')

        if password and password_confirm and password != password_confirm:
            raise ValidationError("两次输入的密码不一致")
        return password_confirm

    def clean_username(self):
        username = self.cleaned_data.get('username')
        if User.objects.filter(username=username).exists():
            raise ValidationError("用户名已存在")
        return username

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise ValidationError("该邮箱已被注册")
        return email


class LoginForm(forms.Form):
    username_or_email = forms.CharField(label="用户名/邮箱")
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'autocomplete': 'current-password'}))
    captcha = CaptchaField(label="验证码")

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)  # 安全移除request参数
        super().__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super().clean()
        username_or_email = cleaned_data.get('username_or_email')
        password = cleaned_data.get('password')

        # 双模式用户查询
        user = User.objects.filter(
            Q(username=username_or_email)
            | Q(email__iexact=username_or_email)  # 不区分大小写匹配邮箱
        ).first()

        # 认证流程
        if not user:
            raise forms.ValidationError("用户不存在")

        auth_user = authenticate(
            request=self.request,
            username=user.username,  # 使用实际用户名认证
            password=password)

        if not auth_user:
            raise forms.ValidationError("密码错误")
        if not auth_user.is_active:
            raise forms.ValidationError("账户未激活")

        self.user = auth_user  # 存储认证通过的用户
        return cleaned_data

    def get_user(self):
        return self.user  # 供视图获取用户对象


class ForgotPasswordForm(PasswordResetForm):
    captcha = CaptchaField()





class PasswordResetConfirmForm(SetPasswordForm):
    captcha = CaptchaField(label='验证码', error_messages={'invalid': '验证码错误'})

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['new_password1'].label = '新密码'
        self.fields['new_password2'].label = '确认密码'
