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

# Register your models here.
from .models import Article, Category, Tag, Links, SideBar, BlogSettings

#zhq: 文章表单类 - 可用于定制文章编辑表单
class ArticleForm(forms.ModelForm):
    # body = forms.CharField(widget=AdminPagedownWidget())

    class Meta:
        model = Article
        fields = '__all__'

#zhq: Admin动作函数 - 批量发布文章
def makr_article_publish(modeladmin, request, queryset):
    queryset.update(status='p')

#zhq: Admin动作函数 - 批量设为草稿
def draft_article(modeladmin, request, queryset):
    queryset.update(status='d')

#zhq: Admin动作函数 - 批量关闭评论
def close_article_commentstatus(modeladmin, request, queryset):
    queryset.update(comment_status='c')

#zhq: Admin动作函数 - 批量开启评论
def open_article_commentstatus(modeladmin, request, queryset):
    queryset.update(comment_status='o')

#zhq: 设置动作的描述信息
makr_article_publish.short_description = _('Publish selected articles')
draft_article.short_description = _('Draft selected articles')
close_article_commentstatus.short_description = _('Close article comments')
open_article_commentstatus.short_description = _('Open article comments')

#zhq: 文章管理类 - 定制文章在Admin中的显示和行为
class ArticlelAdmin(admin.ModelAdmin):
    list_per_page = 20
    search_fields = ('body', 'title')
    form = ArticleForm
    list_display = (
        'id',
        'title',
        'author',
        'link_to_category',
        'creation_time',
        'views',
        'status',
        'type',
        'article_order',
        'version_count')  # 添加版本数量显示
    list_display_links = ('id', 'title')
    list_filter = ('status', 'type', 'category')
    date_hierarchy = 'creation_time'
    filter_horizontal = ('tags',)
    exclude = ('creation_time', 'last_modify_time')
    view_on_site = True
    actions = [
        makr_article_publish,
        draft_article,
        close_article_commentstatus,
        open_article_commentstatus]  #zhq: 注册批量动作
    raw_id_fields = ('author', 'category',)

    def link_to_category(self, obj):
        # zhq: 自定义方法，生成分类的管理后台链接
        info = (obj.category._meta.app_label, obj.category._meta.model_name)
        link = reverse('admin:%s_%s_change' % info, args=(obj.category.id,))
        return format_html(u'<a href="%s">%s</a>' % (link, obj.category.name))

    link_to_category.short_description = _('category')

    def version_count(self, obj):
        """显示文章版本数量和链接"""
        from blog.models_version import ArticleVersion
        count = ArticleVersion.objects.filter(article=obj).count()
        if count > 0:
            url = reverse('admin:blog_articleversion_changelist') + f'?article__id__exact={obj.id}'
            return format_html('<a href="{}">{} 个版本</a>', url, count)
        return '无版本'

    version_count.short_description = _('Versions')

    def get_form(self, request, obj=None, **kwargs):
        # zhq: 限制作者字段只能选择超级用户
        form = super(ArticlelAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['author'].queryset = get_user_model(
        ).objects.filter(is_superuser=True)
        return form

    def save_model(self, request, obj, form, change):
        super(ArticlelAdmin, self).save_model(request, obj, form, change)

    def get_view_on_site_url(self, obj=None):
        # zhq: 获取文章在前台的访问链接
        if obj:
            url = obj.get_full_url()
            return url
        else:
            from djangoblog.utils import get_current_site
            site = get_current_site().domain
            return site

    class Media:
        """引入草稿自动保存的 JavaScript"""
        js = ('blog/js/article-draft-autosave.js',)

#zhq: 标签管理类 - 简化管理界面
class TagAdmin(admin.ModelAdmin):
    exclude = ('slug', 'last_mod_time', 'creation_time')

#zhq: 分类管理类 - 显示父级分类信息
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'parent_category', 'index')
    exclude = ('slug', 'last_mod_time', 'creation_time')

#zhq: 友情链接管理类
class LinksAdmin(admin.ModelAdmin):
    exclude = ('last_mod_time', 'creation_time')

#zhq: 侧边栏管理类
class SideBarAdmin(admin.ModelAdmin):
    list_display = ('name', 'content', 'is_enable', 'sequence')
    exclude = ('last_mod_time', 'creation_time')

#zhq: 博客设置管理类 - 使用默认管理界面
class BlogSettingsAdmin(admin.ModelAdmin):
    pass

# 导入文章版本管理(导入模块以触发装饰器注册)
import blog.admin_version
# 导入文章草稿管理(导入模块以触发装饰器注册)
import blog.admin_draft
# 导入社交功能管理(导入模块以触发装饰器注册)
import blog.admin_social
# 导入多媒体管理(导入模块以触发装饰器注册)
import blog.admin_media
