from apps.content.models.category import Category
from django import forms
from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from mptt.forms import TreeNodeChoiceField

from ..models import Wiki
from .mixins import SingletonAdminMixin


class WikiForm(forms.ModelForm):
    category = TreeNodeChoiceField(
        queryset=Category.objects.filter(content_type__model='wiki'),
        label="栏目",
        help_text="选择树状栏目",
    )

    class Meta:
        model = Wiki
        fields = '__all__'


@admin.register(Wiki)
class WikiAdmin(SingletonAdminMixin, admin.ModelAdmin):
    # form = WikiForm
    # 列表页配置
    search_fields = ('title', 'subtitle', 'alias', 'content')

    # 表单页配置
    fieldsets = ((_('基本信息'), {
        'fields': (('title', 'subtitle'), 'category', 'alias')
    }), (_('内容设置'), {
        'fields': (
            'basic',
            'content',
            'thumb_image',
            'template',
        )
    }), (_('SEO优化'), {
        'classes': ('collapse', ),
        'fields': ('meta_title', 'meta_description', 'meta_keywords',
                   ('slug', 'canonical_url'), ('og_title', 'og_description'),
                   'twitter_card_type')
    }), ('内容关联', {
        'classes': ('collapse', ),
        'fields': (('related_tags', 'about'), )
    }), (_('状态控制'), {
        'fields': (('status', 'allow_comment', 'is_top'),
                   ('create_time', "update_time"), 'editor', 'hits')
    }), ('权限控制', {
        'classes': ('collapse', ),
        'fields': ('staff_only', 'allowed_groups')
    }))
    list_filter = ('status', 'category', 'editor')
    filter_horizontal = ('about', )
    # radio_fields = {'status': admin.HORIZONTAL}
    readonly_fields = ('hits', 'create_time', "update_time")
    # 日期导航
    @property
    def date_hierarchy(self):
        """
        依赖 ContentConfig.get_solo() 方法自身的内置缓存。
        避免在模块加载时访问数据库，同时保证效率。
        """
        from apps.core.models.content_config import ContentConfig
        try:
            # 依赖于 get_solo() 方法内部的缓存实现
            content_config = ContentConfig.get_solo()
            if getattr(content_config, 'date_hierarchy', False):
                return 'update_time'
        except Exception:
            # 优雅处理异常，例如初次迁移时表可能不存在
            pass
        return None

    save_on_top = True
    autocomplete_fields = ('related_tags', 'about')

    class Media:
        css = {'all': ('css/admin-wiki.css', )}
        js = ('js/admin/wiki.js', )

    # 自定义方法 - 带颜色的状态显示
    @admin.display(description=_("审核状态"))
    def status_with_color(self, obj):
        colors = {
            0: '#4a7ebb',  # 已入库
            1: '#999',  # 草稿
            2: '#f0ad4e',  # 已提交
            3: '#d9534f',  # 审核中
            4: '#5cb85c',  # 已通过
            5: '#d33',  # 已驳回
            6: '#777'  # 已归档
        }
        return format_html('<span style="color: {};">{}</span>',
                           colors.get(obj.status, '#000'),
                           obj.get_status_display())

    # 自定义方法 - 推荐状态显示
    @admin.display(description=_("是否推荐"), boolean=True)
    def is_top_display(self, obj):
        return obj.is_top == obj.BooleanFlags.YES

    # 富文本编辑器配置
    class Media:
        css = {'all': ('css/admin/wiki.css', )}
        js = ('js/admin/wiki.js', )

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # 捕获 URL 中的 category_id 参数
        category_id = request.GET.get('category_id')
        if category_id:
            # 将参数注入表单字段初始值
            form.base_fields['category'].initial = Category.objects.get(
                id=category_id)
        return form
