# models.py
from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from django.db import models


class UserProfile(models.Model):
    user = models.OneToOneField(User,
                                on_delete=models.CASCADE,
                                related_name='profile',
                                verbose_name="关联用户")

    # 基础信息
    GENDER_CHOICES = (
        ('M', '男性'),
        ('F', '女性'),
        ('O', '其他'),
    )
    gender = models.CharField('性别',
                              max_length=1,
                              choices=GENDER_CHOICES,
                              blank=True)
    birth_date = models.DateField('出生日期', blank=True, null=True)
    avatar = models.ImageField('头像',
                               upload_to='avatars/%Y/%m/',
                               blank=True,
                               null=True)

    # 联系信息
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="电话号码格式: +8613912345678")
    mobile_phone = models.CharField('手机号码',
                                    validators=[phone_regex],
                                    max_length=17,
                                    blank=True)
    address_street = models.CharField('街道地址', max_length=255, blank=True)
    address_city = models.CharField('城市', max_length=100, blank=True)
    address_postcode = models.CharField('邮编', max_length=20, blank=True)

    # 职业信息
    department = models.CharField('部门', max_length=100, blank=True)
    job_title = models.CharField('职位', max_length=100, blank=True)
    hire_date = models.DateField('入职日期', blank=True, null=True)

    # 社交信息
    wechat_id = models.CharField('微信ID', max_length=50, blank=True)
    dingtalk_id = models.CharField('钉钉ID', max_length=50, blank=True)

    # 系统信息
    timezone = models.CharField('时区', max_length=50, default='Asia/Shanghai')

    # 审计字段
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('最后更新', auto_now=True)

    failed_login_attempts = models.PositiveIntegerField(
        '登录失败次数',  # 中文标识
        default=0,
        help_text="记录用户连续登录失败的次数，用于安全锁定机制")
    lockout_until = models.DateTimeField(
        '锁定截止时间',  # 中文标识
        null=True,
        blank=True,
        help_text="当登录失败次数达到阈值时，账户将被锁定直到此时间")
    d_coin = models.PositiveIntegerField(default=0, )

    class Meta:
        verbose_name = '用户扩展资料'
        verbose_name_plural = '用户扩展资料'

    def __str__(self):
        return f"{self.user.username} 的资料"
