from django.contrib import admin
from .models import User, Data, KnowledgeBase, Permission, ChatHistory, KnowledgeBasePermission

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('username', 'email', 'role', 'department', 'date_joined')
    list_filter = ('role', 'department', 'is_active')
    search_fields = ('username', 'email', 'department')

@admin.register(Data)
class DataAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'user_id', 'department', 'create_time')
    list_filter = ('type', 'department', 'create_time')
    search_fields = ('name', 'desc', 'user_id')
    readonly_fields = ('id', 'create_time', 'update_time')

@admin.register(KnowledgeBase)
class KnowledgeBaseAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'user_id', 'document_count', 'create_time')
    list_filter = ('type', 'create_time')
    search_fields = ('name', 'desc', 'user_id')
    readonly_fields = ('id', 'create_time', 'update_time', 'document_count')

@admin.register(Permission)
class PermissionAdmin(admin.ModelAdmin):
    list_display = [
        'knowledge_base', 
        'applicant', 
        'status',
        'get_permissions_display',  # 显示具体的权限
        'expires_at',  # 显示过期时间
        'created_at'
    ]
    list_filter = [
        'status',
        'created_at',
        'expires_at'
    ]
    search_fields = [
        'knowledge_base__name',
        'applicant__username',
        'reason',
        'response_message'
    ]
    readonly_fields = [
        'created_at',
        'updated_at'
    ]

    def get_permissions_display(self, obj):
        """格式化显示权限"""
        perms = []
        permissions = obj.permissions
        if permissions.get('can_read'):
            perms.append('读取')
        if permissions.get('can_edit'):
            perms.append('编辑')
        if permissions.get('can_delete'):
            perms.append('删除')
        return '、'.join(perms) if perms else '无权限'
    get_permissions_display.short_description = '权限'

@admin.register(ChatHistory)
class ChatHistoryAdmin(admin.ModelAdmin):
    list_display = ('user', 'role', 'conversation_id', 'created_at')
    list_filter = ('role', 'created_at')
    search_fields = ('user__username', 'content', 'conversation_id')
    readonly_fields = ('created_at',)

admin.site.register(KnowledgeBasePermission)
