#ht: 用户管理后台配置模块，自定义Django Admin的用户管理界面
from django import forms
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.forms import UsernameField
from django.utils.translation import gettext_lazy as _

# Register your models here.
from .models import BlogUser


class BlogUserCreationForm(forms.ModelForm):
    """ht: 用户创建表单，用于在Admin后台创建新用户"""
    password1 = forms.CharField(label=_('password'), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_('Enter password again'), widget=forms.PasswordInput)

    class Meta:
        model = BlogUser
        fields = ('email',)

    def clean_password2(self):
        """ht: 验证两次输入的密码是否一致"""
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(_("passwords do not match"))
        return password2

    def save(self, commit=True):
        """ht: 保存用户，对密码进行哈希处理并设置来源标记"""
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.source = 'adminsite'  # ht: 标记用户来源为管理员后台
            user.save()
        return user


class BlogUserChangeForm(UserChangeForm):
    """ht: 用户信息修改表单"""
    class Meta:
        model = BlogUser
        fields = '__all__'
        field_classes = {'username': UsernameField}

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


class BlogUserAdmin(UserAdmin):
    """ht: 自定义用户管理类，配置Admin界面显示和搜索选项"""
    form = BlogUserChangeForm
    add_form = BlogUserCreationForm
    #ht: 列表显示字段
    list_display = (
        'id',
        'nickname',
        'username',
        'email',
        'last_login',
        'date_joined',
        'source')
    list_display_links = ('id', 'username')  # ht: 可点击链接的字段
    ordering = ('-id',)  # ht: 默认按ID倒序排列
    search_fields = ('username', 'nickname', 'email')  # ht: 搜索字段