from django.contrib import admin
from django.utils.html import format_html
from .models import Artwork, Category, About, Comment


class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'slug', 'created_at', 'updated_at')
    list_filter = ('created_at', 'updated_at')
    search_fields = ('name', 'slug')
    prepopulated_fields = {'slug': ('name',)}
    ordering = ('name',)


class ArtworkAdmin(admin.ModelAdmin):
    list_display = (
        'title',
        'category',
        'order',
        'view_count',
        'created_at',
        'thumbnail_preview'
    )
    list_filter = ('category', 'created_at')
    search_fields = ('title', 'description', 'slug')
    list_editable = ('order',)
    prepopulated_fields = {'slug': ('title',)}
    ordering = ('order', '-created_at')
    readonly_fields = ('view_count', 'created_at', 'updated_at', 'image_preview')
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'slug', 'description', 'category')
        }),
        ('图片设置', {
            'fields': ('image', 'image_preview', 'thumbnail')
        }),
        ('排序与统计', {
            'fields': ('order', 'view_count')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    def thumbnail_preview(self, obj):
        if obj.thumbnail:
            return format_html(
                '<img src="{}" style="max-height: 50px; max-width: 50px;" />',
                obj.thumbnail.url
            )
        return "-"
    thumbnail_preview.short_description = '缩略图'

    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="max-height: 200px; max-width: 200px;" />',
                obj.image.url
            )
        return "-"
    image_preview.short_description = '图片预览'


class AboutAdmin(admin.ModelAdmin):
    list_display = ('title', 'created_at', 'updated_at')
    readonly_fields = ('created_at', 'updated_at', 'image_preview')
    fieldsets = (
        ('内容', {
            'fields': ('title', 'content', 'image')
        }),
        ('预览', {
            'fields': ('image_preview',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    def image_preview(self, obj):
        if obj.image:
            return format_html(
                '<img src="{}" style="max-height: 200px; max-width: 200px;" />',
                obj.image.url
            )
        return "-"
    image_preview.short_description = '图片预览'

    def has_add_permission(self, request):
        # 只允许有一个关于页面
        if About.objects.exists():
            return False
        return super().has_add_permission(request)

    def has_delete_permission(self, request, obj=None):
        # 不允许删除关于页面
        return False


class CommentAdmin(admin.ModelAdmin):
    """评论管理"""

    list_display = ['id', 'user', 'artwork', 'text_preview', 'has_image', 'created_at', 'is_active']
    list_filter = ['artwork', 'user', 'is_active', 'created_at']
    search_fields = ['text', 'user__username', 'artwork__title']
    list_editable = ['is_active']
    list_per_page = 20

    fieldsets = (
        ('基本信息', {
            'fields': ('artwork', 'user', 'is_active')
        }),
        ('评论内容', {
            'fields': ('text', 'image')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ('created_at', 'updated_at')

    def text_preview(self, obj):
        """文本内容预览"""
        if obj.text:
            return obj.text[:50] + '...' if len(obj.text) > 50 else obj.text
        return '-'
    text_preview.short_description = '评论内容'

    def has_image(self, obj):
        """是否有图片"""
        return bool(obj.image)
    has_image.short_description = '有图片'
    has_image.boolean = True

    actions = ['activate_comments', 'deactivate_comments']

    def activate_comments(self, request, queryset):
        """批量激活评论"""
        updated = queryset.update(is_active=True)
        self.message_user(request, f'已激活 {updated} 条评论')
    activate_comments.short_description = '激活选中评论'

    def deactivate_comments(self, request, queryset):
        """批量停用评论"""
        updated = queryset.update(is_active=False)
        self.message_user(request, f'已停用 {updated} 条评论')
    deactivate_comments.short_description = '停用选中评论'


admin.site.register(Category, CategoryAdmin)
admin.site.register(Artwork, ArtworkAdmin)
admin.site.register(About, AboutAdmin)
admin.site.register(Comment, CommentAdmin)

# 自定义管理站点标题
admin.site.site_header = 'Yitao-Ren Gallery 管理后台'
admin.site.site_title = '画廊管理'
admin.site.index_title = '欢迎使用画廊管理后台'