from django.db import models
from django.utils import timezone
from .ad_space import AdvertisementSpace
from django.utils.safestring import mark_safe


class Advertisement(models.Model):
    """ 广告内容实体 """
    AD_TYPE_CHOICES = (('image', '图片广告'), ('text', '文字广告'), ('code', '代码广告'))

    space = models.ForeignKey(AdvertisementSpace,
                              on_delete=models.CASCADE,
                              verbose_name='所属广告位')
    title = models.CharField('广告标题', max_length=100)
    content = models.TextField('广告内容', help_text="支持HTML/图片路径")
    start_time = models.DateTimeField('开始时间', default=timezone.now)
    end_time = models.DateTimeField('结束时间')
    priority = models.IntegerField('优先级', default=0)
    click_count = models.PositiveIntegerField('点击量', default=0, editable=False)
    show_count = models.PositiveIntegerField('展示量', default=0, editable=False)
    is_active = models.BooleanField('启用状态', default=True)
    audit_status = models.BooleanField('审核状态', default=False)

    class Meta:
        verbose_name = '广告内容'
        verbose_name_plural = verbose_name
        ordering = ['-priority']

    def is_valid(self):
        now = timezone.now()
        return mark_safe(
            '<span class="badge text-bg-success">有效</span>'
        ) if self.start_time <= now <= self.end_time and self.is_active else mark_safe(
            '<span class="badge text-bg-danger">无效</span>')

    # 设置方法在admin中显示的中文列头
    is_valid.short_description = '是否有效'
