"""
管理员模块模型 - 独立于App用户的账户体系
"""
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models


class AdminUserManager(BaseUserManager):
    """管理员用户管理器"""
    
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError('用户名不能为空')
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, username, password=None, **extra_fields):
        extra_fields.setdefault('role', 'super_admin')
        return self.create_user(username, password, **extra_fields)


class AdminUser(AbstractBaseUser):
    """
    管理员用户模型 - Web后台使用
    与App端User模型完全独立
    不使用PermissionsMixin以避免与User模型冲突
    """
    
    ROLE_CHOICES = [
        ('super_admin', '超级管理员'),
        ('admin', '管理员'),
        ('operator', '操作员'),
    ]
    
    id = models.BigAutoField(primary_key=True)
    username = models.CharField('用户名', max_length=50, unique=True)
    name = models.CharField('姓名', max_length=50, blank=True, default='')
    email = models.EmailField('邮箱', blank=True, default='')
    phone = models.CharField('手机号', max_length=20, blank=True, default='')
    role = models.CharField('角色', max_length=20, choices=ROLE_CHOICES, default='operator')
    is_active = models.BooleanField('是否启用', default=True)
    last_login_ip = models.GenericIPAddressField('最后登录IP', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    
    objects = AdminUserManager()
    
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []
    
    class Meta:
        db_table = 'admin_user'
        verbose_name = '管理员'
        verbose_name_plural = '管理员'
    
    @property
    def is_staff(self):
        """Django admin兼容"""
        return self.role in ['super_admin', 'admin']
    
    @property
    def is_superuser(self):
        """超级管理员检查"""
        return self.role == 'super_admin'
    
    def has_perm(self, perm, obj=None):
        """权限检查"""
        return self.role in ['super_admin', 'admin']
    
    def has_module_perms(self, app_label):
        """模块权限检查"""
        return self.role in ['super_admin', 'admin']
    
    def __str__(self):
        return f"{self.username} ({self.get_role_display()})"
