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


@admin.register(SearchHistory)
class SearchHistoryAdmin(admin.ModelAdmin):
    # 字段分组布局
    fieldsets = ((None, {
        'fields': (
            'title',
            'py_title',
            'status',
        )
    }), ('内容管理', {
        'fields': ('content', )
    }), ('发布设置', {
        'fields':
        ('allow_comment', 'hits', 'template', ('update_time', 'create_time'))
    }))
    list_display = ('id', 'title', 'status_badge', 'create_time',
                    'update_time', 'extended_functionality')
    # 只读字段
    readonly_fields = ('create_time', 'update_time', 'hits')
    list_display_links = ('title', )
    preserve_filters = True
    show_full_result_count = False
    # 分页配置
    list_per_page = 20
    # 自定义字段显示
    @admin.display(description=_('标题'), ordering='title')
    def title_truncated(self, obj):
        return obj.title[:48] + '...' if len(obj.title) > 50 else obj.title

    @admin.display(description=_('状态'))
    def status_badge(self, obj):
        from django.utils.html import format_html
        colors = {
            0: '#666',  # 已入库
            1: '#999',  # 草稿
            2: '#ffc107',  # 已提交
            3: '#17a2b8',  # 审核中
            4: '#28a745',  # 已通过
            5: '#dc3545',  # 已驳回
            6: '#6c757d',  # 已归档
            99: '#007bff'  # 已发布
        }
        return format_html(
            '<span style="padding:2px 8px; border-radius:12px; background:{}; color:white" class="nowrap">{}</span>',
            colors[obj.status], obj.get_status_display())

    @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><li class="breadcrumb-item"><a href="#" class="remove_static_a" data-url="{obj.get_absolute_url()}"data-object-id="{obj.id}">移除静态</a></li></ol></nav>'
        )
        return html

    extended_functionality.allow_tags = True  # 允许HTML渲染
