from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserInfo

class RegisterForm(UserCreationForm):
    email = forms.EmailField(required=True, label="邮箱")
    nickname = forms.CharField(max_length=50, required=True, label="昵称")
    phone_number = forms.CharField(max_length=20, required=True, label="电话号码")

    class Meta:
        model = User
        fields = ["username", "email", "password1", "password2", "nickname", "phone_number"]

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

    def clean_password1(self):
        username = self.cleaned_data.get("username")
        password1 = self.cleaned_data.get("password1")
        if username == password1:
            raise forms.ValidationError("用户名与密码不可重复")
        return password1

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("邮箱已存在")
        return email

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get("username")
        password1 = cleaned_data.get("password1")
        if username == password1:
            self.add_error("password1", "用户名不可与密码重复")