from django.contrib import admin
from django.utils.html import format_html
from .models import Achievement, UserAchievement

@admin.register(Achievement)
class AchievementAdmin(admin.ModelAdmin):
    list_display = ('name', 'display_icon', 'achievement_type', 'rarity', 'points', 'is_hidden', 'created_at')
    list_filter = ('achievement_type', 'rarity', 'is_hidden')
    search_fields = ('name', 'description')
    readonly_fields = ('created_at', 'updated_at')
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'icon', 'achievement_type', 'rarity', 'points', 'is_hidden')
        }),
        ('获取条件', {
            'fields': ('conditions',),
            'description': '使用JSON格式定义成就的获取条件'
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def display_icon(self, obj):
        if obj.icon:
            return format_html('<img src="{}" width="32" height="32" style="border-radius: 50%;" />', obj.icon.url)
        return "无图标"
    display_icon.short_description = '图标'


@admin.register(UserAchievement)
class UserAchievementAdmin(admin.ModelAdmin):
    list_display = ('user', 'achievement', 'display_icon', 'acquired_at', 'notification_shown')
    list_filter = ('acquired_at', 'notification_shown', 'achievement__achievement_type')
    search_fields = ('user__username', 'achievement__name')
    readonly_fields = ('acquired_at',)
    raw_id_fields = ('user', 'achievement')
    fieldsets = (
        ('关联信息', {
            'fields': ('user', 'achievement')
        }),
        ('获取信息', {
            'fields': ('acquired_at', 'acquisition_data', 'notification_shown')
        }),
    )
    date_hierarchy = 'acquired_at'
    
    def display_icon(self, obj):
        if obj.achievement.icon:
            return format_html('<img src="{}" width="24" height="24" style="border-radius: 50%;" />', obj.achievement.icon.url)
        return "无图标"
    display_icon.short_description = '成就图标'
