# models.py
from django.db import models


class LinkGroup(models.Model):
    """友情链接分组模型"""
    name = models.CharField('分组名称', max_length=50, unique=True)
    alias = models.CharField('分组别名', max_length=50, blank=True)
    sort_order = models.PositiveIntegerField('排序权重', default=0)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '链接分组'
        verbose_name_plural = verbose_name
        ordering = ['sort_order', 'name']

    def __str__(self):
        return self.alias if self.alias else self.name


class FriendLink(models.Model):
    """友情链接详细信息模型"""
    title = models.CharField('网站名称', max_length=100)
    alias = models.CharField('网站别名', max_length=50, blank=True)
    url = models.URLField('链接地址', max_length=255, unique=True)
    logo = models.ImageField('网站LOGO', upload_to='friend_links/', blank=True)
    group = models.ForeignKey(LinkGroup,
                              on_delete=models.SET_NULL,
                              verbose_name='所属分组',
                              null=True,
                              blank=True)
    sort_order = models.PositiveIntegerField('排序权重', default=0)
    is_active = models.BooleanField('是否启用', default=True)
    description = models.TextField('网站描述', blank=True)
    is_nofollow = models.BooleanField('是否添加nofollow',
                                      default=False,
                                      help_text='启用后链接会添加rel=\"nofollow\"属性')
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        verbose_name = '友情链接'
        verbose_name_plural = verbose_name
        ordering = ['group', 'sort_order', 'title']

    def __str__(self):
        return self.title

    def clean(self):
        if self.alias == '':
            self.alias = self.title
        return super().clean()
