#zzj: OAuth用户和配置的Django后台管理模块
import logging

from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html

logger = logging.getLogger(__name__)


class OAuthUserAdmin(admin.ModelAdmin):
    """OAuth用户后台管理类"""
    search_fields = ('nickname', 'email')
    list_per_page = 20
    list_display = (
        'id',
        'nickname',
        'link_to_usermodel',
        'show_user_image',
        'type',
        'email',
    )
    list_display_links = ('id', 'nickname')
    list_filter = ('author', 'type',)
    readonly_fields = []

    def get_readonly_fields(self, request, obj=None):
        """获取只读字段"""
        if obj is None:
            return self.readonly_fields
        return list(self.readonly_fields) + \
            [field.name for field in obj._meta.fields] + \
            [field.name for field in obj._meta.many_to_many]

    def has_add_permission(self, request):
        """禁用添加权限"""
        return False

    def link_to_usermodel(self, obj):
        """生成关联用户模型的链接"""
        if obj.author:
            info = (obj.author._meta.app_label, obj.author._meta.model_name)
            link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
            display_name = obj.author.nickname if obj.author.nickname else obj.author.email
            return format_html('<a href="{}">{}</a>', link, display_name)
        return "-"

    def show_user_image(self, obj):
        """显示用户头像"""
        if obj.picture:
            return format_html(
                '<img src="{}" style="width:50px;height:50px;object-fit:cover;">',
                obj.picture
            )
        return "-"

    link_to_usermodel.short_description = '关联用户'
    show_user_image.short_description = '用户头像'


class OAuthConfigAdmin(admin.ModelAdmin):
    """OAuth配置后台管理类"""
    list_display = ('type', 'appkey', 'appsecret', 'is_enable')
    list_filter = ('type',)
    list_editable = ('is_enable',)  #zzj: 允许直接在列表页启用/禁用配置