from django.contrib import admin
from django.db import models
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django_json_widget.widgets import JSONEditorWidget

from ..models.image_gallery import ImageGallery
from .mixins import SingletonAdminMixin


@admin.register(ImageGallery)
class ImageGalleryAdmin(SingletonAdminMixin, admin.ModelAdmin):
    formfield_overrides = {
        models.JSONField: {
            'widget': JSONEditorWidget(mode='code')  # 仅保留必要参数  
        }
    }
    list_display = ('title_truncated', 'thumb_preview', 'title', 'category',
                    'status_badge', 'license', 'create_time',
                    'extended_functionality')
    list_filter = ('category', 'status', 'license', 'create_time')
    search_fields = ('title', 'alt_text', 'meta_keywords')
    readonly_fields = ('exif_info', 'color_palette', 'aspect_ratio',
                       "create_time", "update_time", "hits")
    autocomplete_fields = ('related_tags', )
    # 日期导航
    @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 'create_time'
        except Exception:
            # 优雅处理异常，例如初次迁移时表可能不存在
            pass
        return None

    actions = ['make_cover']
    fieldsets = ((None, {
        'fields': (
            'title',
            'image',
            'thumb_image',
            'alt_text',
            'category',
        )
    }), ('版权信息', {
        'fields': ('license', 'is_cover'),
        'classes': ('collapse', )
    }), ('技术信息', {
        'fields': ('exif_info', 'color_palette', 'aspect_ratio'),
        'classes': ('collapse', )
    }), ('SEO设置', {
        'fields': ('slug', 'meta_title', 'meta_description', 'meta_keywords'),
        'classes': ('wide', )
    }), 
    # ('内容关联', {
    #     'fields': ('related_tags', ),
    #     'classes': ('collapse', )
    # }), 
    ('发布设置', {
        'fields': (('status', "editor"), 'template', 'allow_comment',
                   ('update_time', "create_time")),
        'classes': ('collapse', )
    }), ('权限控制', {
        'classes': ('collapse', ),
        'fields': ('staff_only', 'allowed_groups')
    }))

    def thumb_preview(self, obj):
        return format_html(
            '<img src="{}" style="max-height:80px; border-radius:3px;" />',
            obj.image.url) if obj.image else "-"

    thumb_preview.short_description = _('预览图')

    def status_badge(self, obj):
        colors = {'REVIEW': 'green', 'DRAFT': 'gray', 'ARCHIVED': 'orange'}
        return format_html(
            '<span style="padding:2px 6px; border-radius:12px; background:{}; color:white">{}</span>',
            colors.get(obj.status, 'gray'), obj.get_status_display())

    status_badge.short_description = _('状态')

    def make_cover(self, request, queryset):
        for obj in queryset:
            obj.category.cover = obj
            obj.category.save()

    make_cover.short_description = _('设为分类封面')
