# 多媒体管理 Admin 界面

from django.contrib import admin
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from django.urls import reverse

from blog.models_media import MediaFile, MediaFolder, MediaFileFolder


@admin.register(MediaFile)
class MediaFileAdmin(admin.ModelAdmin):
    """媒体文件管理界面"""

    list_display = [
        'id',
        'thumbnail_preview',
        'original_filename',
        'file_type',
        'file_size_display',
        'uploader_link',
        'upload_time',
        'reference_count',
        'is_public'
    ]

    list_filter = [
        'file_type',
        'is_public',
        'upload_time'
    ]

    search_fields = [
        'original_filename',
        'description',
        'uploader__username'
    ]

    readonly_fields = [
        'stored_filename',
        'file_hash',
        'file_size',
        'mime_type',
        'file_path',
        'thumbnail_path',
        'width',
        'height',
        'upload_time',
        'thumbnail_preview_large'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('original_filename', 'file_type', 'description', 'is_public')
        }),
        ('文件详情', {
            'fields': ('stored_filename', 'file_size', 'file_hash', 'mime_type', 'file_path')
        }),
        ('图片信息', {
            'fields': ('width', 'height', 'thumbnail_path', 'thumbnail_preview_large'),
            'classes': ('collapse',)
        }),
        ('用户信息', {
            'fields': ('uploader', 'upload_time', 'reference_count')
        }),
    )

    list_per_page = 50

    def thumbnail_preview(self, obj):
        """缩略图预览（列表）"""
        if obj.is_image():
            return format_html(
                '<img src="{}" style="max-width: 50px; max-height: 50px; object-fit: cover;" />',
                obj.get_thumbnail_url()
            )
        return '📄'

    thumbnail_preview.short_description = '预览'

    def thumbnail_preview_large(self, obj):
        """缩略图预览（详情）"""
        if obj.is_image():
            return format_html(
                '<img src="{}" style="max-width: 300px; max-height: 300px;" />',
                obj.get_absolute_url()
            )
        return '非图片文件'

    thumbnail_preview_large.short_description = '图片预览'

    def file_size_display(self, obj):
        """文件大小显示"""
        size = obj.file_size
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size < 1024.0:
                return f"{size:.1f} {unit}"
            size /= 1024.0
        return f"{size:.1f} TB"

    file_size_display.short_description = '文件大小'

    def uploader_link(self, obj):
        """上传者链接"""
        if obj.uploader:
            url = reverse('admin:accounts_bloguser_change', args=[obj.uploader.id])
            return format_html('<a href="{}">{}</a>', url, obj.uploader.username)
        return '-'

    uploader_link.short_description = '上传者'

    def has_add_permission(self, request):
        """禁止手动添加（应通过上传功能）"""
        return False


@admin.register(MediaFolder)
class MediaFolderAdmin(admin.ModelAdmin):
    """媒体文件夹管理界面"""

    list_display = [
        'id',
        'name',
        'full_path_display',
        'owner_link',
        'files_count_display',
        'created_time'
    ]

    list_filter = [
        'created_time'
    ]

    search_fields = [
        'name',
        'description',
        'owner__username'
    ]

    readonly_fields = [
        'created_time',
        'full_path_display'
    ]

    fieldsets = (
        ('文件夹信息', {
            'fields': ('name', 'parent', 'owner', 'description')
        }),
        ('详细信息', {
            'fields': ('created_time', 'full_path_display')
        }),
    )

    def full_path_display(self, obj):
        """完整路径显示"""
        return obj.get_full_path()

    full_path_display.short_description = '完整路径'

    def owner_link(self, obj):
        """所有者链接"""
        url = reverse('admin:accounts_bloguser_change', args=[obj.owner.id])
        return format_html('<a href="{}">{}</a>', url, obj.owner.username)

    owner_link.short_description = '所有者'

    def files_count_display(self, obj):
        """文件数量显示"""
        return obj.file_relations.count()

    files_count_display.short_description = '文件数量'


@admin.register(MediaFileFolder)
class MediaFileFolderAdmin(admin.ModelAdmin):
    """媒体文件-文件夹关联管理界面"""

    list_display = [
        'id',
        'file_link',
        'folder_link',
        'added_time'
    ]

    list_filter = [
        'added_time'
    ]

    search_fields = [
        'file__original_filename',
        'folder__name'
    ]

    readonly_fields = [
        'added_time'
    ]

    def file_link(self, obj):
        """文件链接"""
        url = reverse('admin:blog_mediafile_change', args=[obj.file.id])
        return format_html('<a href="{}">{}</a>', url, obj.file.original_filename)

    file_link.short_description = '文件'

    def folder_link(self, obj):
        """文件夹链接"""
        url = reverse('admin:blog_mediafolder_change', args=[obj.folder.id])
        return format_html('<a href="{}">{}</a>', url, obj.folder.name)

    folder_link.short_description = '文件夹'
