from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _

from ..models import Tag


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    exclude = ['slug']  # 隐藏slug输入框‌
    search_fields = ('title', )
    list_display = ('id', 'title', 'group', 'slug_show',
                    'extended_functionality')
    list_display_links = ('title', )
    search_fields = ('title', )
    # 过滤面板配置
    list_filter = (
        ('status'),  # 精确显示状态选项
    )

    def slug_show(self, obj):
        return obj.slug

    slug_show.short_description = '生成后的Slug'

    @admin.display(description=_('扩展功能'))
    def extended_functionality(self, obj):
        html = format_html(
            f'<nav aria-label="breadcrumb" class="nowrap"><ol class="breadcrumb"><li class="breadcrumb-item"><a href="{obj.get_absolute_url()}" target="_blank">前端浏览<a></li></ol></nav>'
        )
        return html

    extended_functionality.allow_tags = True  # 允许HTML渲染

    # prepopulated_fields = {'slug': ('title', )}  # 自动生成slug
    def save_model(self, request, obj, form, change):

        if not obj.slug:  # 如果slug为空
            obj.slug = obj.generate_slug()  # 调用模型的slug生成方法
        super().save_model(request, obj, form, change)


# class StatusChoices(models.IntegerChoices):
#     DRAFT = 1, _('草稿')
#     PENDING = 0, _('待审')
#     REVIEW = 99, _('审核通过')
#     ARCHIVED = 3, _('回收站')

    actions = [
        'make_draft', 'archive_pending', 'archive_archived', 'archive_revien'
    ]

    @admin.action(description=_('批量改为“草稿”状态'))
    def make_draft(self, request, queryset):
        updated = queryset.update(status=Tag.StatusChoices.DRAFT)
        self.message_user(request, f"成功将 {updated} 个标签改为“草稿”状态")

    @admin.action(description=_('批量改为“待审”状态'))
    def archive_pending(self, request, queryset):
        updated = queryset.update(status=Tag.StatusChoices.PENDING)
        self.message_user(request, f"成功将 {updated} 个标签改为“待审”状态")

    @admin.action(description=_('批量放入回收站'))
    def archive_archived(self, request, queryset):
        updated = queryset.update(status=Tag.StatusChoices.ARCHIVED)
        self.message_user(request, f"成功将 {updated} 个标签放入回收站")

    @admin.action(description=_('批量审核通过'))
    def archive_revien(self, request, queryset):
        updated = queryset.update(status=Tag.StatusChoices.REVIEW)
        self.message_user(request, f"成功将 {updated} 个标签审核通过")
