#wzc: 评论模块的后台管理配置
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _


def disable_commentstatus(modeladmin, request, queryset):
    """wzc: 批量禁用评论状态"""
    queryset.update(is_enable=False)


def enable_commentstatus(modeladmin, request, queryset):
    """wzc: 批量启用评论状态"""
    queryset.update(is_enable=True)


disable_commentstatus.short_description = _('Disable comments')
enable_commentstatus.short_description = _('Enable comments')


class CommentAdmin(admin.ModelAdmin):
    """wzc: 评论模型的后台管理配置"""
    list_per_page = 20
    list_display = (
        'id',
        'body',
        'link_to_userinfo',
        'link_to_article',
        'is_enable',
        'creation_time')
    list_display_links = ('id', 'body', 'is_enable')
    list_filter = ('is_enable',)
    exclude = ('creation_time', 'last_modify_time')
    actions = [disable_commentstatus, enable_commentstatus]
    raw_id_fields = ('author', 'article')
    search_fields = ('body',)

    def link_to_userinfo(self, obj):
        """wzc: 生成用户信息链接"""
        info = (obj.author._meta.app_label, obj.author._meta.model_name)
        link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
        #wzc: 使用昵称或邮箱作为显示文本
        display_text = obj.author.nickname if obj.author.nickname else obj.author.email
        return format_html(u'<a href="{}">{}</a>', link, display_text)

    def link_to_article(self, obj):
        """wzc: 生成文章链接"""
        info = (obj.article._meta.app_label, obj.article._meta.model_name)
        link = reverse('admin:%s_%s_change' % info, args=(obj.article.id,))
        return format_html(u'<a href="{}">{}</a>', link, obj.article.title)

    link_to_userinfo.short_description = _('User')
    link_to_article.short_description = _('Article')