# 文章草稿 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_draft import ArticleDraft


@admin.register(ArticleDraft)
class ArticleDraftAdmin(admin.ModelAdmin):
    """文章草稿管理界面"""

    list_display = [
        'id',
        'title_display',
        'author',
        'article_link',
        'preview',
        'last_update_time',
        'is_published',
        'action_buttons'
    ]

    list_filter = [
        'is_published',
        'author',
        'last_update_time',
        'creation_time'
    ]

    search_fields = [
        'title',
        'body',
        'author__username'
    ]

    readonly_fields = [
        'author',
        'article',
        'creation_time',
        'last_update_time',
        'session_id'
    ]

    fields = [
        'author',
        'article',
        'title',
        'body',
        'category_id',
        'tags_data',
        'status',
        'comment_status',
        'type',
        'session_id',
        'is_published',
        'creation_time',
        'last_update_time'
    ]

    list_per_page = 50

    def has_add_permission(self, request):
        """禁止手动添加草稿"""
        return False

    def title_display(self, obj):
        """显示标题"""
        title = obj.title or '(无标题)'
        if len(title) > 40:
            return title[:37] + '...'
        return title

    title_display.short_description = '标题'

    def article_link(self, obj):
        """文章链接"""
        if obj.article:
            url = reverse('admin:blog_article_change', args=[obj.article.id])
            return format_html('<a href="{}">{}</a>', url, obj.article.title)
        return '-'

    article_link.short_description = '文章'

    def preview(self, obj):
        """预览文本"""
        preview_text = obj.get_preview_text(30)
        return format_html('<span style="color: #666;">{}</span>', preview_text)

    preview.short_description = '预览'

    def action_buttons(self, obj):
        """操作按钮"""
        if not obj.is_published:
            apply_url = f'/blog/api/draft/apply/'
            delete_url = f'/blog/api/draft/delete/'

            return format_html(
                '<button class="button" onclick="applyDraft({})">应用到文章</button> '
                '<button class="button" onclick="deleteDraft({})">删除</button>',
                obj.id, obj.id
            )
        return '已发布'

    action_buttons.short_description = '操作'

    class Media:
        js = ('admin/js/draft_actions.js',)
